text:
<#
.SYNOPSIS
Install native tool

.DESCRIPTION
Install cmake native tool from Azure blob storage

.PARAMETER InstallPath
Base directory to install native tool to

.PARAMETER BaseUri
Base file directory or Url from which to acquire tool archives

.PARAMETER CommonLibraryDirectory
Path to folder containing common library modules

.PARAMETER Force
Force install of tools even if they previously exist

.PARAMETER Clean
Don't install the tool, just clean up the current install of the tool

.PARAMETER DownloadRetries
Total number of retry attempts

.PARAMETER RetryWaitTimeInSeconds
Wait time between retry attempts in seconds

.NOTES
Returns 0 if install succeeds, 1 otherwise
#>
[CmdletBinding(PositionalBinding=$false)]
Param (
  [Parameter(Mandatory=$True)]
  [string] $ToolName,
  [Parameter(Mandatory=$True)]
  [string] $InstallPath,
  [Parameter(Mandatory=$True)]
  [string] $BaseUri,
  [Parameter(Mandatory=$True)]
  [string] $Version,
  [string] $CommonLibraryDirectory = $PSScriptRoot,
  [switch] $Force = $False,
  [switch] $Clean = $False,
  [int] $DownloadRetries = 5,
  [int] $RetryWaitTimeInSeconds = 30
)

. $PSScriptRoot\..\pipeline-logging-functions.ps1

# Import common library modules
Import-Module -Name (Join-Path $CommonLibraryDirectory "CommonLibrary.psm1")

try {
  # Define verbose switch if undefined
  $Verbose = $VerbosePreference -Eq "Continue"

  $Arch = CommonLibrary\Get-MachineArchitecture
  $ToolOs = "win64"
  if($Arch -Eq "x32") {
    $ToolOs = "win32"
  }
  $ToolNameMoniker = "$ToolName-$Version-$ToolOs-$Arch"
  $ToolInstallDirectory = Join-Path $InstallPath "$ToolName\$Version\"
  $Uri = "$BaseUri/windows/$ToolName/$ToolNameMoniker.zip"
  $ShimPath = Join-Path $InstallPath "$ToolName.exe"

  if ($Clean) {
    Write-Host "Cleaning $ToolInstallDirectory"
    if (Test-Path $ToolInstallDirectory) {
      Remove-Item $ToolInstallDirectory -Force -Recurse
    }
    Write-Host "Cleaning $ShimPath"
    if (Test-Path $ShimPath) {
      Remove-Item $ShimPath -Force
    }
    $ToolTempPath = CommonLibrary\Get-TempPathFilename -Path $Uri
    Write-Host "Cleaning $ToolTempPath"
    if (Test-Path $ToolTempPath) {
      Remove-Item $ToolTempPath -Force
    }
    exit 0
  }

  # Install tool
  if ((Test-Path $ToolInstallDirectory) -And (-Not $Force)) {
    Write-Verbose "$ToolName ($Version) already exists, skipping install"
  }
  else {
    $InstallStatus = CommonLibrary\DownloadAndExtract -Uri $Uri `
                                                      -InstallDirectory $ToolInstallDirectory `
                                                      -Force:$Force `
                                                      -DownloadRetries $DownloadRetries `
                                                      -RetryWaitTimeInSeconds $RetryWaitTimeInSeconds `
                                                      -Verbose:$Verbose

    if ($InstallStatus -Eq $False) {
      Write-PipelineTelemetryError "Installation failed" -Category "NativeToolsetBootstrapping"
      exit 1
    }
  }

  $ToolFilePath = Get-ChildItem $ToolInstallDirectory -Recurse -Filter "$ToolName.exe" | % { $_.FullName }
  if (@($ToolFilePath).Length -Gt 1) {
    Write-Error "There are multiple copies of $ToolName in $($ToolInstallDirectory): `n$(@($ToolFilePath | out-string))"
    exit 1
  } elseif (@($ToolFilePath).Length -Lt 1) {
    Write-Host "$ToolName was not found in $ToolInstallDirectory."
    exit 1
  }

  # Generate shim
  # Always rewrite shims so that we are referencing the expected version
  $GenerateShimStatus = CommonLibrary\New-ScriptShim -ShimName $ToolName `
                                                     -ShimDirectory $InstallPath `
                                                     -ToolFilePath "$ToolFilePath" `
                                                     -BaseUri $BaseUri `
                                                     -Force:$Force `
                                                     -Verbose:$Verbose

  if ($GenerateShimStatus -Eq $False) {
    Write-PipelineTelemetryError "Generate shim failed" -Category "NativeToolsetBootstrapping"
    return 1
  }

  exit 0
}
catch {
  Write-Host $_.ScriptStackTrace
  Write-PipelineTelemetryError -Category "NativeToolsetBootstrapping" -Message $_
  exit 1
}


text:
import * as R from 'ramda'
import * as React from 'react'
import * as M from '@material-ui/core'

import { JsonSchema } from 'utils/json-schema'

import { JsonValue, COLUMN_IDS, EMPTY_VALUE, RowData } from './constants'
import { parseJSON, stringifyJSON } from './utils'

const useStyles = M.makeStyles((t) => ({
  root: {
    ...t.typography.body2,
    outline: `2px solid ${t.palette.primary.light}`,
    padding: t.spacing(0, 1),
    position: 'relative',
    width: '100%',
    zIndex: 1,
  },
}))

function getNormalizedValue(value: JsonValue, optSchema?: JsonSchema): JsonValue {
  // TODO: use json-schema#getEmptyValueFromSchema
  if (!optSchema && value === '') return EMPTY_VALUE // FIXME: think more on this

  if (value !== EMPTY_VALUE) return value

  if (!optSchema) return ''

  if (optSchema.enum && optSchema.enum.length) return optSchema.enum[0]

  if (optSchema.type) {
    switch (optSchema.type) {
      case 'string':
        return ''
      case 'number':
        return 0
      case 'object':
        return {}
      case 'null':
        return null
      case 'boolean':
        return true
      case 'array':
        return []
      // no default
    }
  }

  return ''
}

function getNormalizedValueStr(value: JsonValue, optSchema?: JsonSchema) {
  const normalizedValue = getNormalizedValue(value, optSchema)

  // FIXME: think more on this
  if (optSchema && (optSchema.type === 'null' || optSchema.type === 'boolean'))
    return normalizedValue

  if (normalizedValue === EMPTY_VALUE) return ''

  if (normalizedValue === '"') return '"'

  return stringifyJSON(normalizedValue)
}

function hasBrackets(valueStr: string) {
  if (valueStr.length < 2) return false
  return [
    ['"', '"'],
    ['[', ']'],
    ['{', '}'],
  ].some(([leftBracket, rightBracket]) =>
    R.both(R.startsWith(leftBracket), R.endsWith(rightBracket))(valueStr),
  )
}

const willBeNullInJson = (value: JsonValue) =>
  typeof value === 'number' && !Number.isFinite(value)

interface OnChange {
  (value: JsonValue): void
  (value: string): void
}

interface InputProps {
  columnId: 'key' | 'value'
  data: RowData
  onChange: OnChange
  onContextMenu: React.MouseEventHandler<HTMLElement>
  placeholder: string
  value: JsonValue
}

export default function Input({
  columnId,
  data,
  onChange,
  onContextMenu,
  placeholder,
  value: originalValue,
}: InputProps) {
  const classes = useStyles()

  const [value, setValue] = React.useState(() =>
    getNormalizedValue(originalValue, data.valueSchema),
  )
  const [valueStr, setValueStr] = React.useState(() =>
    getNormalizedValueStr(originalValue, data.valueSchema),
  )

  const inputRef = React.useRef<HTMLInputElement | null>(null)
  React.useEffect(() => {
    if (!inputRef.current || !valueStr) return
    if (hasBrackets(valueStr)) {
      // Set cursor before closing bracket/quote/brace
      inputRef.current.setSelectionRange(valueStr.length - 1, valueStr.length - 1)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const onChangeInternal = React.useCallback(
    (event) => {
      setValue(parseJSON(event.target.value))
      setValueStr(event.target.value)
    },
    [setValue, setValueStr],
  )

  const onBlur = React.useCallback(() => {
    if (R.is(String, value)) return onChange(value)
    if (columnId === COLUMN_IDS.KEY) return onChange(valueStr)
    if (willBeNullInJson(value)) return onChange(null)
    return onChange(value)
  }, [onChange, columnId, value, valueStr])

  const onKeyDown = React.useCallback(
    (event) => {
      switch (event.key) {
        case 'Escape':
          event.stopPropagation() // avoid closing the dialog
          break
        case 'Enter':
          event.preventDefault() // avoid submitting the form
          onBlur()
          break
        // no default
      }
    },
    [onBlur],
  )

  const handleContextMenu = (event: React.MouseEvent<HTMLElement>) => {
    event.preventDefault()
    onContextMenu(event)
  }

  return (
    <M.InputBase
      autoFocus
      inputRef={inputRef}
      className={classes.root}
      value={valueStr}
      onChange={onChangeInternal}
      onContextMenu={handleContextMenu}
      onBlur={onBlur}
      onKeyDown={onKeyDown}
      placeholder={placeholder}
    />
  )
}

redpajama_set_name: RedPajamaGithub


text:
#include <PCU.h>

#include "ph.h"
#include <cstdio>
#include <cstdlib>
#include <stdarg.h>
#include <cassert>
#include <sstream>
#include <iostream>
#include <fstream>

/* OS-specific things try to stay here */
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

namespace ph {

void fail(const char* format, ...)
{
  va_list ap;
  va_start(ap, format);
  vfprintf(stderr, format, ap);
  va_end(ap);
  fprintf(stderr,"\n");
  abort();
}

enum {
  DIR_MODE = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH
};

static bool my_mkdir(const char* name)
{
  errno = 0;
  int err = mkdir(name, DIR_MODE);
  if ((err == -1) && (errno == EEXIST)) {
    errno = 0;
    err = 0;
    return false;
  }
  assert(!err);
  return true;
}

static void my_chdir(const char* name)
{
  int err = chdir(name);
  assert(!err);
}

void goToParentDir() {
  my_chdir("..");
}

void goToStepDir(int step)
{
  std::stringstream ss;
  ss << step;
  std::string s = ss.str();
  if (!PCU_Comm_Self())
    my_mkdir(s.c_str());
  PCU_Barrier();
  my_chdir(s.c_str());
}

enum {
  DIR_FANOUT = 2048
};

std::string setupOutputDir()
{
  std::stringstream ss;
  ss << PCU_Comm_Peers() << "-procs_case/";
  std::string s = ss.str();
  if (!PCU_Comm_Self())
    my_mkdir(s.c_str());
  PCU_Barrier();
  return s;
}

void setupOutputSubdir(std::string& path)
{
  if (PCU_Comm_Peers() <= DIR_FANOUT)
    return;
  int self = PCU_Comm_Self();
  int subSelf = self % DIR_FANOUT;
  int subGroup = self / DIR_FANOUT;
  std::stringstream ss;
  ss << path << subGroup << '/';
  path = ss.str();
  if (!subSelf)
    my_mkdir(path.c_str());
  PCU_Barrier();
}

void setupInputSubdir(std::string& path)
{
  if (PCU_Comm_Peers() <= DIR_FANOUT)
    return;
  int self = PCU_Comm_Self();
  int subGroup = self / DIR_FANOUT;
  std::string newpath;
  std::stringstream ss;

  std::size_t found = path.find_last_of("/");
  if(found == std::string::npos) {
    //no "/" character was found in path
    //this means no directory specified in path, only filename such as restart
    //should not really happen since phasta files usually located in #-procs_case directories
    ss << "./" << subGroup << "/" << path;
  }
  else {
    //insert before the last "/" character the subgroup id 0, 1, 2 etc
    ss << path.substr(0,found) << "/" << subGroup << "/" << path.substr(found+1);
  }

//  printf("Rank: %d - Path in setupInputSubdir: %s\n", self, ss.str().c_str());
  path = ss.str();
  PCU_Barrier();
}

void writeAuxiliaryFiles(std::string path, int timestep)
{
  std::string numpePath = path;
  numpePath += "numpe.in";
  std::ofstream numpe(numpePath.c_str());
  assert(numpe.is_open());
  numpe << PCU_Comm_Peers() << '\n';
  numpe.close();
  std::string numstartPath = path;
  numstartPath += "numstart.dat";
  std::ofstream numstart(numstartPath.c_str());
  assert(numstart.is_open());
  numstart << timestep << '\n';
  numstart.close();
}

}


text:
@interface BaseViewController ()

@end

@implementation BaseViewController

- (void)loadView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = UIColor.whiteColor;
    self.view = view;

    // The label that shows info.
    self.infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 150, ScreenWidth-30, 50)];
    self.infoLabel.textColor = UIColor.blackColor;
    self.infoLabel.numberOfLines = 0;
    [self.view addSubview:self.infoLabel];

    // clear button
    self.clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.clearButton.frame = CGRectMake(15, 200, ScreenWidth-30, 50);
    self.clearButton.backgroundColor = UIColor.blueColor;
    [self.clearButton setTitle:@"clear" forState:UIControlStateNormal];
    [self.clearButton addTarget:self action:@selector(clearButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.clearButton];

}

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)clearButtonClicked:(UIButton *)button
{
    [self.securityField clear];
}

@end


text:
/*	$NetBSD: mscp_tape.c,v 1.15 2000/03/30 12:45:34 augustss Exp $ */
/*
 * Copyright (c) 1996 Ludd, University of Lule}, Sweden.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed at Ludd, University of
 *	Lule}, Sweden and its contributors.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * MSCP tape device driver
 */

/*
 * TODO
 *	Write status handling code.
 */

#include <sys/param.h>
#include <sys/device.h>
#include <sys/kernel.h>
#include <sys/buf.h>
#include <sys/ioccom.h>
#include <sys/mtio.h>
#include <sys/fcntl.h>
#include <sys/malloc.h>
#include <sys/systm.h>
#include <sys/proc.h>

#include <machine/bus.h>
#include <machine/cpu.h>

#include <dev/mscp/mscp.h>
#include <dev/mscp/mscpreg.h>
#include <dev/mscp/mscpvar.h>

#include "locators.h"

/*
 * Drive status, per drive
 */
struct mt_softc {
	struct	device mt_dev;	/* Autoconf struct */
	int	mt_state;	/* open/closed state */
	int	mt_hwunit;	/* Hardware unit number */
	int	mt_inuse;	/* Locks the tape drive for others */
	int	mt_waswrite;	/* Last operation was a write op */
	int	mt_serex;	/* Got serious exception */
	int	mt_ioctlerr;	/* Error after last ioctl */
};

#define MT_OFFLINE	0
#define MT_ONLINE	1

int	mtmatch __P((struct device *, struct cfdata *, void *));
void	mtattach __P((struct device *, struct device *, void *));
void	mtdgram __P((struct device *, struct mscp *, struct mscp_softc *));
void	mtiodone __P((struct device *, struct buf *));
int	mtonline __P((struct device *, struct mscp *));
int	mtgotstatus __P((struct device *, struct mscp *));
int	mtioerror __P((struct device *, struct mscp *, struct buf *));
void	mtfillin __P((struct buf *, struct mscp *));
int	mtopen __P((dev_t, int, int, struct proc *));
int	mtclose __P((dev_t, int, int, struct proc *));
void	mtstrategy __P((struct buf *));
int	mtread __P((dev_t, struct uio *));
int	mtwrite __P((dev_t, struct uio *));
int	mtioctl __P((dev_t, int, caddr_t, int, struct proc *));
int	mtdump __P((dev_t, daddr_t, caddr_t, size_t));
int	mtcmd __P((struct mt_softc *, int, int, int));
void	mtcmddone __P((struct device *, struct mscp *));
int	mt_putonline __P((struct mt_softc *));

struct	mscp_device mt_device = {
	mtdgram,
	mtiodone,
	mtonline,
	mtgotstatus,
	0,
	mtioerror,
	0,
	mtfillin,
	mtcmddone,
};

/* This is not good, should allow more than 4 tapes/device type */
#define mtunit(dev)	(minor(dev) & T_UNIT)
#define mtnorewind(dev) (dev & T_NOREWIND)
#define mthdensity(dev) (dev & T_1600BPI)

struct	cfattach mt_ca = {
	sizeof(struct mt_softc), mtmatch, mtattach
};

extern struct cfdriver mt_cd;

/*
 * More driver definitions, for generic MSCP code.
 */

int
mtmatch(parent, cf, aux)
	struct	device *parent;
	struct	cfdata *cf;
	void	*aux;
{
	struct	drive_attach_args *da = aux;
	struct	mscp *mp = da->da_mp;

	if ((da->da_typ & MSCPBUS_TAPE) == 0)
		return 0;
	if (cf->cf_loc[MSCPBUSCF_DRIVE] != MSCPBUSCF_DRIVE_DEFAULT &&
	    cf->cf_loc[MSCPBUSCF_DRIVE] != mp->mscp_unit)
		return 0;
	return 1;
}

/*
 * The attach routine only checks and prints drive type.
 */
void
mtattach(parent, self, aux)
	struct	device *parent, *self;
	void	*aux;
{
	struct	mt_softc *mt = (void *)self;
	struct	drive_attach_args *da = aux;
	struct	mscp *mp = da->da_mp;
	struct	mscp_softc *mi = (void *)parent;

	mt->mt_hwunit = mp->mscp_unit;
	mi->mi_dp[mp->mscp_unit] = self;

	disk_printtype(mp->mscp_unit, mp->mscp_guse.guse_mediaid);
}

/*
 * (Try to) put the drive online. This is done the first time the
 * drive is opened, or if it has fallen offline.
 */
int
mt_putonline(mt)
	struct mt_softc *mt;
{
	struct	mscp *mp;
	struct	mscp_softc *mi = (struct mscp_softc *)mt->mt_dev.dv_parent;
	volatile int i;

	(volatile int)mt->mt_state = MT_OFFLINE;
	mp = mscp_getcp(mi, MSCP_WAIT);
	mp->mscp_opcode = M_OP_ONLINE;
	mp->mscp_unit = mt->mt_hwunit;
	mp->mscp_cmdref = (long)&mt->mt_state;
	*mp->mscp_addr |= MSCP_OWN | MSCP_INT;

	/* Poll away */
	i = bus_space_read_2(mi->mi_iot, mi->mi_iph, 0);
	if (tsleep(&mt->mt_state, PRIBIO, "mtonline", 240 * hz))
		return MSCP_FAILED;

	if ((volatile int)mt->mt_state != MT_ONLINE)
		return MSCP_FAILED;

	return MSCP_DONE;
}
/*
 * Open a drive.
 */
/*ARGSUSED*/
int
mtopen(dev, flag, fmt, p)
	dev_t dev;
	int flag, fmt;
	struct	proc *p;
{
	struct mt_softc *mt;
	int unit;

	/*
	 * Make sure this is a reasonable open request.
	 */
	unit = mtunit(dev);
	if (unit >= mt_cd.cd_ndevs)
		return ENXIO;
	mt = mt_cd.cd_devs[unit];
	if (mt == 0)
		return ENXIO;

	if (mt->mt_inuse)
			return EBUSY;
	mt->mt_inuse = 1;

	if (mt_putonline(mt) == MSCP_FAILED) {
		mt->mt_inuse = 0;
		return EIO;
	}

	return 0;
}

/* ARGSUSED */
int
mtclose(dev, flags, fmt, p)
	dev_t dev;
	int flags, fmt;
	struct	proc *p;
{
	int unit = mtunit(dev);
	struct mt_softc *mt = mt_cd.cd_devs[unit];

	/*
	 * If we just have finished a writing, write EOT marks.
	 */
	if ((flags & FWRITE) && mt->mt_waswrite) {
		mtcmd(mt, MTWEOF, 0, 0);
		mtcmd(mt, MTWEOF, 0, 0);
		mtcmd(mt, MTBSR, 1, 0);
	}
	if (mtnorewind(dev) == 0)
		mtcmd(mt, MTREW, 0, 1);
	if (mt->mt_serex)
		mtcmd(mt, -1, 0, 0);

	mt->mt_inuse = 0; /* Release the tape */
	return 0;
}

void
mtstrategy(bp)
	struct buf *bp;
{
	int unit;
	struct mt_softc *mt;

	/*
	 * Make sure this is a reasonable drive to use.
	 */
	unit = mtunit(bp->b_dev);
	if (unit > mt_cd.cd_ndevs || (mt = mt_cd.cd_devs[unit]) == NULL) {
		bp->b_error = ENXIO;
		goto bad;
	}

	mt->mt_waswrite = bp->b_flags & B_READ ? 0 : 1;
	mscp_strategy(bp, mt->mt_dev.dv_parent);
	return;

bad:
	bp->b_flags |= B_ERROR;
	biodone(bp);
}

int
mtread(dev, uio)
	dev_t dev;
	struct uio *uio;
{

	return (physio(mtstrategy, NULL, dev, B_READ, minphys, uio));
}

int
mtwrite(dev, uio)
	dev_t dev;
	struct uio *uio;
{

	return (physio(mtstrategy, NULL, dev, B_WRITE, minphys, uio));
}

void
mtiodone(usc, bp)
	struct device *usc;
	struct buf *bp;
{

	biodone(bp);
}

/*
 * Fill in drive addresses in a mscp packet waiting for transfer.
 */
void
mtfillin(bp, mp)
	struct buf *bp;
	struct mscp *mp;
{
	int unit = mtunit(bp->b_dev);
	struct mt_softc *mt = mt_cd.cd_devs[unit];

	mp->mscp_unit = mt->mt_hwunit;
	if (mt->mt_serex == 2) {
		mp->mscp_modifier = M_MD_CLSEX;
		mt->mt_serex = 0;
	} else
		mp->mscp_modifier = 0;

	mp->mscp_seq.seq_bytecount = bp->b_bcount;
}

/*
 * Handle an error datagram.
 */
void
mtdgram(usc, mp, mi)
	struct device *usc;
	struct mscp *mp;
	struct mscp_softc *mi;
{
	if (mscp_decodeerror(usc == NULL?"unconf mt" : usc->dv_xname, mp, mi))
		return;
}

/*
 * A drive came on line, make sure it really _is_ on line before
 * trying to use it.
 */
int
mtonline(usc, mp)
	struct device *usc;
	struct mscp *mp;
{
	struct mt_softc *mt = (void *)usc;

	wakeup((caddr_t)&mt->mt_state);
	if ((mp->mscp_status & M_ST_MASK) == M_ST_SUCCESS)
		mt->mt_state = MT_ONLINE;

	return (MSCP_DONE);
}

/*
 * We got some (configured) unit's status.  Return DONE.
 */
int
mtgotstatus(usc, mp)
	struct device *usc;
	struct mscp *mp;
{
	return (MSCP_DONE);
}

static char *mt_ioerrs[] = {
	"invalid command",	/* 1 M_ST_INVALCMD */
	"command aborted",	/* 2 M_ST_ABORTED */
	"unit offline",		/* 3 M_ST_OFFLINE */
	"unknown",		/* 4 M_ST_AVAILABLE */
	"unknown",		/* 5 M_ST_MFMTERR */
	"unit write protected", /* 6 M_ST_WRPROT */
	"compare error",	/* 7 M_ST_COMPERR */
	"data error",		/* 8 M_ST_DATAERR */
	"host buffer access error",	/* 9 M_ST_HOSTBUFERR */
	"controller error",	/* 10 M_ST_CTLRERR */
	"drive error",		/* 11 M_ST_DRIVEERR */
	"formatter error",	/* 12 M_ST_FORMATTERR */
	"BOT encountered",	/* 13 M_ST_BOT */
	"tape mark encountered",/* 14 M_ST_TAPEMARK */
	"unknown",		/* 15 */
	"record data truncated",/* 16 M_ST_RDTRUNC */
};

/*
 * An I/O error, may be because of a tapemark encountered.
 * Check that before failing.
 */
/*ARGSUSED*/
int
mtioerror(usc, mp, bp)
	struct device *usc;
	struct mscp *mp;
	struct buf *bp;
{
	struct mt_softc *mt = (void *)usc;
	int st = mp->mscp_status & M_ST_MASK;

	if (mp->mscp_flags & M_EF_SEREX)
		mt->mt_serex = 1;
	if (st == M_ST_TAPEMARK)
		mt->mt_serex = 2;
	else {
		if (st && st < 17)
			printf("%s: error %d (%s)\n", mt->mt_dev.dv_xname, st,
			    mt_ioerrs[st-1]);
		else
			printf("%s: error %d\n", mt->mt_dev.dv_xname, st);
		bp->b_flags |= B_ERROR;
		bp->b_error = EROFS;
	}

	return (MSCP_DONE);
}

/*
 * I/O controls.
 */
int
mtioctl(dev, cmd, data, flag, p)
	dev_t dev;
	int cmd;
	caddr_t data;
	int flag;
	struct proc *p;
{
	int unit = mtunit(dev);
	struct mt_softc *mt = mt_cd.cd_devs[unit];
	struct	mtop *mtop;
	struct	mtget *mtget;
	int error = 0, count;

	count = mtop->mt_count;

	switch (cmd) {

	case MTIOCTOP:
		mtop = (void *)data;
		if (mtop->mt_op == MTWEOF) {
			while (mtop->mt_count-- > 0)
				if ((error = mtcmd(mt, mtop->mt_op, 0, 0)))
					break;
		} else
			error = mtcmd(mt, mtop->mt_op, mtop->mt_count, 0);

	case MTIOCGET:
		mtget = (void *)data;
		mtget->mt_type = MT_ISTMSCP;
		/* XXX we need to fill in more fields here */
		break;

	default:
		error = ENXIO;
		break;
	}
	return (error);
}

/*
 * No crash dump support...
 */
int
mtdump(dev, blkno, va, size)
	dev_t	dev;
	daddr_t blkno;
	caddr_t va;
	size_t	size;
{
	return -1;
}

/*
 * Send a command to the tape drive. Wait until the command is
 * finished before returning.
 * This routine must only be called when there are no data transfer
 * active on this device. Can we be sure of this? Or does the ctlr
 * queue up all command packets and take them in sequential order?
 * It sure would be nice if my manual stated this... /ragge
 */
int
mtcmd(mt, cmd, count, complete)
	struct mt_softc *mt;
	int cmd, count, complete;
{
	struct mscp *mp;
	struct mscp_softc *mi = (void *)mt->mt_dev.dv_parent;
	volatile int i;

	mp = mscp_getcp(mi, MSCP_WAIT);

	mt->mt_ioctlerr = 0;
	mp->mscp_unit = mt->mt_hwunit;
	mp->mscp_cmdref = -1;
	*mp->mscp_addr |= MSCP_OWN | MSCP_INT;

	switch (cmd) {
	case MTWEOF:
		mp->mscp_opcode = M_OP_WRITM;
		break;

	case MTBSF:
		mp->mscp_modifier = M_MD_REVERSE;
	case MTFSF:
		mp->mscp_opcode = M_OP_POS;
		mp->mscp_seq.seq_buffer = count;
		break;

	case MTBSR:
		mp->mscp_modifier = M_MD_REVERSE;
	case MTFSR:
		mp->mscp_opcode = M_OP_POS;
		mp->mscp_modifier |= M_MD_OBJCOUNT;
		mp->mscp_seq.seq_bytecount = count;
		break;

	case MTREW:
		mp->mscp_opcode = M_OP_POS;
		mp->mscp_modifier = M_MD_REWIND | M_MD_CLSEX;
		if (complete)
			mp->mscp_modifier |= M_MD_IMMEDIATE;
		mt->mt_serex = 0;
		break;

	case MTOFFL:
		mp->mscp_opcode = M_OP_AVAILABLE;
		mp->mscp_modifier = M_MD_UNLOAD | M_MD_CLSEX;
		mt->mt_serex = 0;
		break;

	case MTNOP:
		mp->mscp_opcode = M_OP_GETUNITST;
		break;

	case -1: /* Clear serious exception only */
		mp->mscp_opcode = M_OP_POS;
		mp->mscp_modifier = M_MD_CLSEX;
		mt->mt_serex = 0;
		break;

	default:
		printf("Bad ioctl %x\n", cmd);
		mp->mscp_opcode = M_OP_POS;
		break;
	}

	i = bus_space_read_2(mi->mi_iot, mi->mi_iph, 0);
	tsleep(&mt->mt_inuse, PRIBIO, "mtioctl", 0);
	return mt->mt_ioctlerr;
}

/*
 * Called from bus routines whenever a non-data transfer is finished.
 */
void
mtcmddone(usc, mp)
	struct device *usc;
	struct mscp *mp;
{
	struct mt_softc *mt = (void *)usc;

	if (mp->mscp_status) {
		mt->mt_ioctlerr = EIO;
		printf("%s: bad status %x\n", mt->mt_dev.dv_xname,
		    mp->mscp_status);
	}
	wakeup(&mt->mt_inuse);
}


text:
package com.douglaswhitehead.controller.view;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.douglaswhitehead.configuration.EnsightenManageConfigProperties;
import com.douglaswhitehead.controller.data.AbstractDataController;
import com.douglaswhitehead.datalayer.LoginDataLayer;
import com.douglaswhitehead.model.ShoppingCart;
import com.douglaswhitehead.model.User;

@Controller
@RequestMapping("/login")
public class LoginPageControllerImpl extends AbstractDataController implements LoginPageController {

	@Autowired
	protected EnsightenManageConfigProperties properties;

	@Autowired
	private LoginDataLayer dataLayer;

	@Override
	@RequestMapping(method = RequestMethod.GET)
	public String login(@RequestParam(value = "error", required = false) final String error,
			final HttpServletRequest request, final Device device, final HttpServletResponse response,
			final Model model) {
		boolean auth = isAuthenticated();
		String cartId;

		if (!checkCartIdCookie(request)) {
			cartId = setNewCartIdCookie(request, response);
		} else {
			Cookie cookie = getCartIdCookie(request);
			cartId = cookie.getValue();
		}

		ShoppingCart cart = cartService.get(UUID.fromString(cartId));
		User user = null;
		if (auth) {
			user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}

		String digitalData = digitalDataAdapter.adapt(dataLayer.login(error, request, response, device, cart, user));

		model.addAttribute("ensManAccountId", properties.getAccountId());
		model.addAttribute("ensManPublishPath", properties.getPublishPath());
		model.addAttribute("digitalData",digitalData);

		return "login";
	}

}


text:
const IGNORE_TIME = 250

let filter = true
export default function undoFilter (action, currState, prevState) {
  // other filters
  filter = actionsThrottlingFilter(action)
  return filter
}

// Store rapid actions of the same type at most once every x time.
let ignoreRapid = false
let prevActionType
function actionsThrottlingFilter (action) {
  if (action.type !== prevActionType) {
    ignoreRapid = false
    prevActionType = action.type
    return true
  }
  if (ignoreRapid) {
    return false
  }
  ignoreRapid = true
  setTimeout(() => {
    ignoreRapid = false
  }, IGNORE_TIME)
  return true
}


text:
import Ember from 'ember';
import Strings from '../utils/mappings/strings';
import Health from '../utils/mappings/health';
import healthToString from '../utils/convert/health-to-string';
import healthToIconClass from '../utils/convert/health-to-icon-class';
import operationalToString from '../utils/convert/operational-to-string';
import operationalToIconClass from '../utils/convert/operational-to-icon-class';
import slaToString from '../utils/convert/sla-to-string';
import slaToIconClass from '../utils/convert/sla-to-icon-class';
import trustToString from '../utils/convert/trust-to-string';
import trustToIconClass from '../utils/convert/trust-to-icon-class';
import stripFloat from '../utils/strip-float';
import readableSizeToBytes from '../utils/convert/readable-size-to-bytes';

export default Ember.Mixin.create({
  healthMessage: function() {
    return 'Health: ' + healthToString(this.get('status.health'), 'good').capitalize();
  }.property('status.health'),
  healthIconClass: function() {
    return healthToIconClass(this.get('status.health'));
  }.property('status.health'),
  operationalMessage: function() {
    return 'Operational State: ' + operationalToString(this.get('status.operational')).capitalize();
  }.property('status.operational'),
  operationalIconClass: function() {
    return operationalToIconClass(this.get('status.operational'));
  }.property('status.operational'),
  slaMessage: function() {
    return 'SLA Status: ' + slaToString(this.get('status.sla_status')).capitalize();
  }.property('status.sla_status'),
  slaIconClass: function() {
    if (this.get('isMonitored')) return 'fa-eye info';
    if (this.get('isAssuredCoresPhysical')) return 'fa-thumb-tack success';
    return slaToIconClass(this.get('status.sla_status'));
  }.property('status.sla_status'),
  trustMessage: function() {
    return 'Trust Status: ' + trustToString(this.get('status.trust')).capitalize();
  }.property('status.trust'),
  trustIconClass: function() {
    return trustToIconClass(this.get('status.trust'));
  }.property('status.trust'),
  memoryCurrent: function() {
    if (typeof this.get('utilization.memory') === 'number') {
      var memoryCurrent = parseInt(this.get('utilization.memory'));
      if (typeof memoryCurrent !== 'number') return null;
      return memoryCurrent * 1024;  // Assume input is KiB (cgroups API)
    } else if (typeof this.get('utilization.memory') === 'string') {
      return readableSizeToBytes(this.get('utilization.memory'), false);
    } else {
      return null;
    }
  }.property('utilization.memory'),
  memoryCurrentInGib: function() {
    if (Ember.isEmpty(this.get('memoryCurrent'))) return null;
    return (this.get('memoryCurrent') / Math.pow(1024, 3));  // bytes to GiB
  }.property('memoryCurrent'),
  memoryMax: function() {
    if (typeof this.get('capabilities.memory_size') === 'number') {
      var memoryMax = parseInt(this.get('capabilities.memory_size'));
      if (typeof memoryMax !== 'number') return null;
      return memoryMax * 1024;  // Assume input is KiB (cgroups API)
    } else if (typeof this.get('capabilities.memory_size') === 'string') {
      return readableSizeToBytes(this.get('capabilities.memory_size'), false);
    } else {
      return null;
    }
  }.property('capabilities.memory_size'),
  memoryMaxInGib: function() {
    if (Ember.isEmpty(this.get('memoryMax'))) return null;
    return (this.get('memoryMax') / Math.pow(1024, 3));  // bytes to GiB
  }.property('memoryMax'),
  hasMemoryRange: function() {
    return !Ember.isEmpty(this.get('memoryCurrent')) && !Ember.isEmpty(this.get('memoryMax'));
  }.property('memoryCurrent', 'memoryMax'),
  memoryPercent: function() {
    if (Ember.isEmpty(this.get('memoryCurrent')) || Ember.isEmpty(this.get('memoryMax'))) return null;
    return ((this.get('memoryCurrent') / this.get('memoryMax')) * 100).toFixed(0) + '%';
  }.property('memoryCurrent', 'memoryMax'),
  memoryStyle: function() {
    return 'width:' + this.get('memoryPercent');
  }.property('memoryPercent'),
  contentionCurrent: function() {
    var contention = this.get('contention.system.llc.value');
    if (Ember.isEmpty(contention)) contention = this.get('contention.llc.system.value');
    if (Ember.isEmpty(contention) || contention < 0) return null;
    return contention.toFixed(2);
  }.property('contention.system.llc.value'),
  hasContention: Ember.computed.notEmpty('contentionCurrent'),
  contentionPercent: function() {
    var contentionMax = 50;
    if (Ember.isEmpty(this.get('contentionCurrent'))) return null;
    var percent = (this.get('contentionCurrent') / contentionMax) * 100;
    if (percent > 0 && percent < 2) percent = 2;  // If any contention exists, show at least a small bar
    return percent.toFixed(0) + '%';
  }.property('contentionCurrent'),
  contentionStyle: function() {
    return 'width:' + this.get('contentionPercent');
  }.property('contentionPercent'),
  cpuFrequency: function() {
    var cpuFrequency = parseInt(this.get('node.capabilities.cpu_frequency')) / 1000;
    if (isNaN(cpuFrequency)) return Strings.NA;
    return stripFloat(cpuFrequency) + ' GHz';
  }.property('node.capabilities.cpu_frequency'),
  hasCores: Ember.computed.notEmpty('capabilities.cores'),
  cores: function() {
    var cores = this.get('capabilities.cores');
    if (Ember.isEmpty(cores)) return Strings.NA;
    return cores + ((cores === 1) ? ' core' : ' cores');
  }.property('capabilities.cores'),
  hasVcpus: Ember.computed.notEmpty('capabilities.vcpus'),
  vcpus: function() {
    var vcpus = this.get('capabilities.vcpus');
    if (Ember.isEmpty(vcpus)) return Strings.NA;
    return vcpus + ((vcpus === 1) ? ' vCPU' : ' vCPUs');
  }.property('capabilities.vcpus'),
  isAggressor: Ember.computed.gte('status.aggressor', Health.INFO),
  isVictim: Ember.computed.gte('status.victim', Health.INFO),

  // Compute SCU allocation floor/ceiling computed properties
  hasCompute: function() {
    return !Ember.isEmpty(this.get('utilizationTotal')) && !Ember.isEmpty(this.get('suFloor'));
  }.property('utilizationTotal', 'suFloor'),
  suFloor: Ember.computed.alias('capabilities.scu_allocated_min'),
  suCeiling: Ember.computed.alias('capabilities.scu_allocated_max'),
  isRange: function() {
    if (Ember.isEmpty(this.get('suFloor'))) return false;
    if (this.get('suFloor') > this.get('suCeiling')) return false;
    return this.get('suFloor') !== this.get('suCeiling');
  }.property('suFloor', 'suCeiling'),
  allocationMin: function() {
    if (Ember.isEmpty(this.get('capabilities.scu_allocated_min'))) return 0;
    if (!this.get('isRange')) return 100;
    return 100 * parseFloat(this.get('capabilities.scu_allocated_min')) / parseFloat(this.get('capabilities.scu_allocated_max'));
  }.property('isRange', 'capabilities.scu_allocated_min', 'capabilities.scu_allocated_max'),
  allocationMinWidth: function() {
    return 'width:' + this.get('allocationMin') + 'px;';
  }.property('allocationMin'),
  allocationMessage: function() {
    var message = '';
    if (this.get('isRange')) {
      message += 'Utilization: ' + stripFloat(this.get('utilizationTotal')) + '\n';
      if (this.get('utilizationBurst')) {
        message += 'Non-bursting: ' + stripFloat(this.get('utilizationCurrent')) + '\n';
        message += 'Bursting: ' + this.get('utilizationBurst').toFixed(2) + '\n';
      }
      message += 'Min Allocated: ' + stripFloat(this.get('capabilities.scu_allocated_min')) + '\n';
      message += 'Burst Allocated: ' + stripFloat(this.get('capabilities.scu_allocated_max'));
    } else {
      message += 'Utilization: ' + stripFloat(this.get('utilizationTotal')) + '\n';
      if (this.get('utilizationBurst')) {
        message += 'Non-bursting: ' + stripFloat(this.get('utilizationCurrent')) + '\n';
        message += 'Bursting: ' + stripFloat(this.get('utilizationBurst')) + '\n';
      }
      message += 'Allocated: ' + stripFloat(this.get('capabilities.scu_allocated_min'));
    }
    return message;
  }.property('isRange', 'utilizationTotal', 'utilizationCurrent', 'utilizationBurst', 'capabilities.scu_allocated_min', 'capabilities.scu_allocated_max'),
  utilizationBurst: function() {
    if (Ember.isEmpty(this.get('scuTotal')) || Ember.isEmpty(this.get('capabilities.scu_allocated_min'))) return 0;
    var burst = Math.max(0, this.get('scuTotal') - this.get('capabilities.scu_allocated_min'));
    return stripFloat(burst);
  }.property('capabilities.scu_allocated_min', 'scuTotal'),
  utilizationTotal: function() {
    var utilization = this.get('scuTotal');
    if (Ember.isEmpty(utilization)) utilization = this.get('utilization.scu_max');
    if (Ember.isEmpty(utilization) || utilization < 0) return null;
    return utilization;
  }.property('scuTotal', 'utilization.scu_max'),
  utilizationCurrent: function() {
    var total = this.get('utilizationTotal');
    if (Ember.isEmpty(total)) total = 0;
    return Math.max(0, total - this.get('utilizationBurst'));
  }.property('utilizationTotal', 'utilizationBurst'),
  utilizationBurstWidth: function() {
    if (Ember.isEmpty(this.get('capabilities.scu_allocated_max'))) return null;
    var percent = 100 * parseFloat(this.get('utilizationBurst')) / parseFloat(this.get('capabilities.scu_allocated_max'));
    return 'width:' + percent.toFixed(0) + 'px;';
  }.property('utilizationBurst', 'capabilities.scu_allocated_max'),
  utilizationCurrentWidth: function() {
    if (Ember.isEmpty(this.get('capabilities.scu_allocated_max'))) return null;
    var percent = 100 * parseFloat(this.get('utilizationCurrent')) / parseFloat(this.get('capabilities.scu_allocated_max'));
    return 'width:' + percent.toFixed(0) + 'px;';
  }.property('utilizationCurrent', 'capabilities.scu_allocated_max'),
  utilizationBurstLeft: function() {
    var percent;
    if (Ember.isEmpty(this.get('capabilities.scu_allocated_max'))) return null;
    if (!this.get('isRange')) {
      // Current
      percent = 100 * parseFloat(this.get('utilizationCurrent')) / parseFloat(this.get('capabilities.scu_allocated_max'));
      return 'left:' + percent.toFixed(0) + 'px;';
    } else {
      // Max of current and scu_allocated_min
      var left = Math.max(this.get('utilizationCurrent'), this.get('capabilities.scu_allocated_min'));
      percent = (100 * left / parseFloat(this.get('capabilities.scu_allocated_max'))) + 1;
      return 'left:' + percent.toFixed(0) + 'px;';
    }
  }.property('isRange', 'capabilities.scu_allocated_max', 'utilizationCurrent'),
  utilizationBurstStyle: function() {
    return this.get('utilizationBurstWidth') + this.get('utilizationBurstLeft');
  }.property('utilizationBurstWidth', 'utilizationBurstLeft')
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CloudNinja.Authorization.EntityFramework;

namespace CloudNinja.AuthorizationApi.Web.Models
{
    public class ClientViewModel
    {
        public int AbsoluteRefreshTokenLifetime { get; set; }
        public int AccessTokenLifetime { get; set; }
        public string AccessTokenType { get; set; }
        public bool AllowRememberConsent { get; set; }
        public bool AlwaysSendClientClaims { get; set; }
        public string ApplicationType { get; set; }
        public int AuthorizationCodeLifetime { get; set; }
        public ICollection<ClientClaim> Claims { get; set; }
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string ClientUri { get; set; }
        public DateTime Created { get; set; }
        public bool Enabled { get; set; }
        public string Flow { get; set; }
        public DateTime? LastModified { get; set; }
        public string LogoUri { get; set; }
        public string Name { get; set; }
        public bool PrefixClientClaims { get; set; }
        public ICollection<ClientRedirectUri> RedirectUris { get; set; }
        public string RefreshTokenExpiration { get; set; }
        public string RefreshTokenUsage { get; set; }
        public bool RequireConsent { get; set; }
        public ICollection<ClientScope> Scopes { get; set; }
        public int SlidingRefreshTokenLifetime { get; set; }
    }
}


text:
#include <stdio.h>
#include <string.h>
#include <sys/utsname.h>

int uname(struct utsname* buf) {
  memset(buf, 0, sizeof(struct utsname));
  snprintf(buf->sysname, _UTSNAME_LENGTH, "NaCl");
  /* TODO(sbc): Fill out the other fields with useful information. */
  return 0;
}


text:
void flush_cin() { std::cin.clear(); std::cin.ignore(1, '\n'); }
#define flush flush_cin()
inline int toInt(std::string s) { int v;std::istringstream istr(s);istr >> v;return v; }
template<class T> inline std::string toString(T x) { std::ostringstream sout;sout << x;return sout.str(); }
std::vector<std::string> split(const std::string &s, char delim = ' ') { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) elems.push_back(item); return elems; }
template <class ForwardIterator> void print_collection(ForwardIterator first, ForwardIterator last) { std::cout << *first; first++; while (first != last) { std::cout << " " << *first; first++; } }
#define print(v) if(len(v)) print_collection(all(v))
// C++ shortcuts
#define len(v) (int)((v).size())
#define first(v) (v)[0]
#define last(v)  (v)[len(v)-1]
#define all(v) (v).begin(), (v).end()
#define srt(v) sort(all(v))
#define rev(v) reverse(all(v))
#define forn(n) for(int _n(n), _i=0; _i<_n; _i++)
#define forin(i,n) for(int _n(n), i=0; i<_n; i++)
#define forimn(i,m,n) for(int _n(n), _m(m), i=_m; i<_n; i++)
// Debug
int _beacon = 0;
#define beacon cout << "Beacon " << ++_beacon << " OK!" << endl

using namespace std;

pair<int, int> left(pair<int, int> node) {
	pair<int, int> next;
	next.first = node.first;
	next.second = node.first + node.second;
	return next;
}

pair<int, int> right(pair<int, int> node) {
	pair<int, int> next;
	next.first = node.first + node.second;
	next.second = node.second;
	return next;
}

pair<int, int> parent(pair<int, int> node) {
	pair<int, int> next;
	if (node.first < node.second) {
		next.first = node.first;
		next.second = node.second - node.first;
	}
	else {
		next.first = node.first - node.second;
		next.second = node.second;
	}
	return next;
}

pair<int, int> step(pair<int,int> node) {

	if (node.second == 1)
		return make_pair(node.second, node.first + 1);
	if (node.second == 2)
		return make_pair(node.second, node.first);
	if (node.first < node.second)
		return make_pair(node.second, node.second - node.first);

	// p > q
	int levels = node.first / node.second;
	pair<int, int> ancestor = make_pair(node.first % node.second, node.second);
	pair<int, int> auntcestor = step(ancestor);
	return make_pair(auntcestor.first, auntcestor.second + auntcestor.first*levels);
}

int main() {

	int P, K, p, q;
	cin >> P;

	forn(P) {
		cin >> K;
		scanf(" %d/%d", &p, &q);
		pair<int, int> next = step(make_pair(p,q));
		cout << K << " " << next.first << "/" << next.second << endl;
	}

	return 0;
}


text:
module Mongoid
  class Criteria
    module Queryable

      # Key objects represent specifications for building query expressions
      # utilizing MongoDB selectors.
      #
      # Simple key-value conditions are translated directly into expression
      # hashes by Mongoid without utilizing Key objects. For example, the
      # following condition:
      #
      #   Foo.where(price: 1)
      #
      # ... is translated to the following simple expression:
      #
      #   {price: 1}
      #
      # More complex conditions would start involving Key objects. For example:
      #
      #   Foo.where(:price.gt => 1)
      #
      # ... causes a Key instance to be created as follows:
      #
      #   Key.new(:price, :__override__, '$gt')
      #
      # This Key instance utilizes +operator+ but not +expanded+ nor +block+.
      # The corresponding MongoDB query expression is:
      #
      #    {price: {'$gt' => 1}}
      #
      # A yet more more complex example is the following condition:
      #
      #   Foo.geo_spatial(:boundary.intersects_point => [1, 10])
      #
      # Processing this condition will cause a Key instance to be created as
      # follows:
      #
      #   Key.new(:location, :__override__, '$geoIntersects', '$geometry') do |value|
      #     { "type" => POINT, "coordinates" => value }
      #   end
      #
      # ... eventually producing the following MongoDB query expression:
      #
      # {
      #   boundary: {
      #     '$geoIntersects' => {
      #       '$geometry' => {
      #         type: "Point" ,
      #         coordinates: [ 1, 10 ]
      #       }
      #     }
      #   }
      # }
      #
      # Key instances can be thought of as procs that map a value to the
      # MongoDB query expression required to obtain the key's condition,
      # given the value.
      class Key

        # @return [ String | Symbol ] The name of the field.
        attr_reader :name

        # @return [ String ] The MongoDB query operator.
        attr_reader :operator

        # @return [ String ] The MongoDB expanded query operator.
        attr_reader :expanded

        # @return [ Symbol ] The name of the merge strategy.
        attr_reader :strategy

        # @return [ Proc ] The optional block to transform values.
        attr_reader :block

        # Does the key equal another object?
        #
        # @example Is the key equal to another?
        #   key == other
        #   key.eql? other
        #
        # @param [ Object ] other The object to compare to.
        #
        # @return [ true | false ] If the objects are equal.
        def ==(other)
          return false unless other.is_a?(Key)
          name == other.name && operator == other.operator && expanded == other.expanded
        end
        alias :eql? :==

        # Calculate the hash code for a key.
        #
        # @return [ Integer ] The hash code for the key.
        def hash
          [name, operator, expanded].hash
        end

        # Instantiate the new key.
        #
        # @example Instantiate a key.
        #   Key.new("age", :__override__, "$gt")
        #
        # @example Instantiate a key for sorting.
        #   Key.new(:field, :__override__, 1)
        #
        # @param [ String | Symbol ] name The field name.
        # @param [ Symbol ] strategy The name of the merge strategy.
        # @param [ String | Integer ] operator The MongoDB operator,
        #   or sort direction (1 or -1).
        # @param [ String ] expanded The Mongo expanded operator.
        def initialize(name, strategy, operator, expanded = nil, &block)
          unless operator.is_a?(String) || operator.is_a?(Integer)
            raise ArgumentError, "Operator must be a string or an integer: #{operator.inspect}"
          end

          @name, @strategy, @operator, @expanded, @block =
            name, strategy, operator, expanded, block
        end

        # Gets the raw selector that would be passed to Mongo from this key.
        #
        # @example Specify the raw selector.
        #   key.__expr_part__(50)
        #
        # @param [ Object ] object The value to be included.
        # @param [ true | false ] negating If the selection should be negated.
        #
        # @return [ Hash ] The raw MongoDB selector.
        def __expr_part__(object, negating = false)
          { name.to_s => transform_value(object, negating) }
        end

        def transform_value(value, negating = false)
          if block
            expr = block[value]
          else
            expr = value
          end

          if expanded
            expr = {expanded => expr}
          end

          expr = {operator => expr}

          if negating && operator != '$not'
            expr = {'$not' => expr}
          end

          expr
        end

        # Get the key as raw Mongo sorting options.
        #
        # @example Get the key as a sort.
        #   key.__sort_option__
        #
        # @return [ Hash ] The field/direction pair.
        def __sort_option__
          { name => operator }
        end
        alias :__sort_pair__ :__sort_option__

        # Convert the key to a string.
        #
        # @example Convert the key to a string.
        #   key.to_s
        #
        # @return [ String ] The key as a string.
        def to_s
          @name.to_s
        end
      end
    end
  end
end


text:
/*
 * Author:  David Robert Nadeau
 * Site:    http://NadeauSoftware.com/
 * License: Creative Commons Attribution 3.0 Unported License
 *          http://creativecommons.org/licenses/by/3.0/deed.en_US
 *
 * Refers:
 *          http://nadeausoftware.com/articles/2012/03/c_c_tip_how_measure_cpu_time_benchmarking
 *          http://nadeausoftware.com/articles/2012/04/c_c_tip_how_measure_elapsed_real_time_benchmarking
 */

#ifndef __BENCHMARK_H
#define __BENCHMARK_H

#if defined(_WIN32)
#include <Windows.h>

#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
#include <unistd.h>	/* POSIX flags */
#include <sys/resource.h>
#include <time.h>	/* clock_gettime(), time() */
#include <sys/time.h>	/* gethrtime(), gettimeofday() */
#include <sys/times.h>	/* gethrtime(), gettimeofday() */

#if defined(__MACH__) && defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#endif

#else
#error "Unable to define getRealTime( ) for an unknown OS."
#endif

/**
 * Returns the real time, in seconds, or -1.0 if an error occurred.
 *
 * Time is measured since an arbitrary and OS-dependent start time.
 * The returned real time is only useful for computing an elapsed time
 * between two calls to this function.
 */
double get_real_time(void) {
#if defined(_WIN32)
	FILETIME tm;
	ULONGLONG t;
#if defined(NTDDI_WIN8) && NTDDI_VERSION >= NTDDI_WIN8
	/* Windows 8, Windows Server 2012 and later. ---------------- */
	GetSystemTimePreciseAsFileTime( &tm );
#else
	/* Windows 2000 and later. ---------------------------------- */
	GetSystemTimeAsFileTime( &tm );
#endif
	t = ((ULONGLONG)tm.dwHighDateTime << 32) | (ULONGLONG)tm.dwLowDateTime;
	return (double)t / 10000000.0;

#elif (defined(__hpux) || defined(hpux)) || ((defined(__sun__) || defined(__sun) || defined(sun)) && (defined(__SVR4) || defined(__svr4__)))
	/* HP-UX, Solaris. ------------------------------------------ */
	return (double)gethrtime( ) / 1000000000.0;

#elif defined(__MACH__) && defined(__APPLE__)
	/* OSX. ----------------------------------------------------- */
	static double timeConvert = 0.0;
	if ( timeConvert == 0.0 )
	{
		mach_timebase_info_data_t timeBase;
		(void)mach_timebase_info( &timeBase );
		timeConvert = (double)timeBase.numer /
			(double)timeBase.denom /
			1000000000.0;
	}
	return (double)mach_absolute_time( ) * timeConvert;

#elif defined(_POSIX_VERSION)
	/* POSIX. --------------------------------------------------- */
#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
	{
		struct timespec ts;
#if defined(CLOCK_MONOTONIC_PRECISE)
		/* BSD. --------------------------------------------- */
		const clockid_t id = CLOCK_MONOTONIC_PRECISE;
#elif defined(CLOCK_MONOTONIC_RAW)
		/* Linux. ------------------------------------------- */
		const clockid_t id = CLOCK_MONOTONIC_RAW;
#elif defined(CLOCK_HIGHRES)
		/* Solaris. ----------------------------------------- */
		const clockid_t id = CLOCK_HIGHRES;
#elif defined(CLOCK_MONOTONIC)
		/* AIX, BSD, Linux, POSIX, Solaris. ----------------- */
		const clockid_t id = CLOCK_MONOTONIC;
#elif defined(CLOCK_REALTIME)
		/* AIX, BSD, HP-UX, Linux, POSIX. ------------------- */
		const clockid_t id = CLOCK_REALTIME;
#else
		const clockid_t id = (clockid_t)-1;	/* Unknown. */
#endif /* CLOCK_* */
		if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 )
			return (double)ts.tv_sec +
				(double)ts.tv_nsec / 1000000000.0;
		/* Fall thru. */
	}
#endif /* _POSIX_TIMERS */

	/* AIX, BSD, Cygwin, HP-UX, Linux, OSX, POSIX, Solaris. ----- */
	struct timeval tm;
	gettimeofday( &tm, NULL );
	return (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0;
#else
	return -1.0;		/* Failed. */
#endif
}

/**
 * Returns the amount of CPU time used by the current process,
 * in seconds, or -1.0 if an error occurred.
 */
double get_cpu_time(void)
{
#if defined(_WIN32)
	/* Windows -------------------------------------------------- */
	FILETIME createTime;
	FILETIME exitTime;
	FILETIME kernelTime;
	FILETIME userTime;
	if ( GetProcessTimes( GetCurrentProcess( ),
		&createTime, &exitTime, &kernelTime, &userTime ) != -1 )
	{
		SYSTEMTIME userSystemTime;
		if ( FileTimeToSystemTime( &userTime, &userSystemTime ) != -1 )
			return (double)userSystemTime.wHour * 3600.0 +
				(double)userSystemTime.wMinute * 60.0 +
				(double)userSystemTime.wSecond +
				(double)userSystemTime.wMilliseconds / 1000.0;
	}

#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
	/* AIX, BSD, Cygwin, HP-UX, Linux, OSX, and Solaris --------- */

#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
	/* Prefer high-res POSIX timers, when available. */
	{
		clockid_t id;
		struct timespec ts;
#if _POSIX_CPUTIME > 0
		/* Clock ids vary by OS.  Query the id, if possible. */
		if ( clock_getcpuclockid( 0, &id ) == -1 )
#endif
#if defined(CLOCK_PROCESS_CPUTIME_ID)
			/* Use known clock id for AIX, Linux, or Solaris. */
			id = CLOCK_PROCESS_CPUTIME_ID;
#elif defined(CLOCK_VIRTUAL)
			/* Use known clock id for BSD or HP-UX. */
			id = CLOCK_VIRTUAL;
#else
			id = (clockid_t)-1;
#endif
		if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 )
			return (double)ts.tv_sec +
				(double)ts.tv_nsec / 1000000000.0;
	}
#endif

#if defined(RUSAGE_SELF)
	{
		struct rusage rusage;
		if ( getrusage( RUSAGE_SELF, &rusage ) != -1 )
			return (double)rusage.ru_utime.tv_sec +
				(double)rusage.ru_utime.tv_usec / 1000000.0;
	}
#endif

#if defined(_SC_CLK_TCK)
	{
		const double ticks = (double)sysconf( _SC_CLK_TCK );
		struct tms tms;
		if ( times( &tms ) != (clock_t)-1 )
			return (double)tms.tms_utime / ticks;
	}
#endif

#if defined(CLOCKS_PER_SEC)
	{
		clock_t cl = clock( );
		if ( cl != (clock_t)-1 )
			return (double)cl / (double)CLOCKS_PER_SEC;
	}
#endif

#endif

	return -1;		/* Failed. */
}

#endif // !__BENCHMARK_H


text:
<?php

namespace Tests\Mongodb\Models;

use ManaPHP\Data\Mongodb\Model;

class City extends Model
{
    public $city_id;
    public $city;
    public $country_id;
    public $last_update;

    public function fieldTypes()
    {
        return [
            '_id'         => 'integer',
            'city_id'     => 'integer',
            'city'        => 'string',
            'country_id'  => 'integer',
            'last_update' => 'string'
        ];
    }
}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

//using System;

public class Brick : MonoBehaviour
{
	// we use statis to make sure there is only one variable across all Brick classes
	// that way we can increase/decrease the same variable inside each Brick independently
	public static int brickCounts = 0;
	public AudioClip crack;
	public Sprite[] hitSprites;
	public GameObject particles;
	public GameObject fallingObject;

	private bool hasObject = false;
	//private int fallingBallIndex = 1;
	private int timesHit, objectIndex;
	private LevelManager levelManager;
	private GameObject score, levelCompleteScore;
	private GameObject balls, dust;

	// Use this for initialization
	void Start ()
	{
		timesHit = 0;
		levelManager = GameObject.FindObjectOfType<LevelManager> ();
		score = GameObject.Find ("Score");
		score.GetComponent <Text> ().text = LevelManager.currentScore.ToString ();
		levelCompleteScore = GameObject.Find ("Level Complete Score");
		if (levelManager.fallingObjects > 0 && Random.Range (0f, 1f) > 0.5f) {
			hasObject = true;
			levelManager.fallingObjects--;
			SetObject ();
		}

		balls = GameObject.Find ("Balls No");
		balls.GetComponent <Text> ().text = LevelManager.ballCounts.ToString ();

		if (this.tag == "Breakable")
			brickCounts++;
	}

	private void SetObject ()
	{
		int maxBallIndex = (int)Mathf.Clamp (SceneManager.GetActiveScene ().buildIndex, 3, 100);
		//print ("ball: " + fallingBallIndex + " max: " + maxBallIndex);
		//print ("calculations: " + fallingBallIndex % maxBallIndex);
		if (levelManager.fallingObjectIndex == maxBallIndex)
			levelManager.fallingObjectIndex = 1; //Random.Range (1, max);
		else
			levelManager.fallingObjectIndex++;
		objectIndex = Random.Range (1, 13);//Random.Range (1, 13); //levelManager.fallingObjectIndex;
	}

	void OnCollisionEnter2D (Collision2D collision)
	{
		if (collision.transform.tag == "Ball" || collision.transform.tag == "Bullet") {
			//print ("COLLIDED and isTrigger is:" + this.GetComponent <BoxCollider2D> ().isTrigger.ToString ());
			AudioSource.PlayClipAtPoint (crack, this.transform.position);
			if (this.tag == "Breakable") {
				HandleScores ();
				HandleHits ();
			}
		}
	}

	// use this for break through balls
	void OnTriggerEnter2D (Collider2D other)
	{
		//if (other.tag == "Ball") {
		if (this.tag == "Breakable" && (other.tag == "Ball" || other.tag == "Bullet")) {
			AudioSource.PlayClipAtPoint (crack, this.transform.position);
			//print ("TRIGGERED and isTrigger is:" + this.GetComponent <BoxCollider2D> ().isTrigger.ToString ());
			HandleScores ();
			HandleHits ();
		}
	}

	void HandleScores ()
	{
		LevelManager.currentScore += 15;
		score.GetComponent <Text> ().text = LevelManager.currentScore.ToString ();
		levelCompleteScore.GetComponent <Text> ().text = LevelManager.currentScore.ToString ();
		if ((LevelManager.currentScore / (1000 * Ball.bonusFactor)) >= 1) {
			levelManager.AddBonusBall (balls);
		}
	}

	void HandleHits ()
	{
		timesHit++;
		if (timesHit >= hitSprites.Length + 1) {
			brickCounts--;
			UpdateView (this.gameObject);
			if (brickCounts <= 0) {
				levelManager.EvalDamage (0, true);
			}
		} else {
			LoadCrackedBrick ();
		}
	}

	void ShowParticles ()
	{
		dust =
			Instantiate (particles, this.gameObject.transform.position, Quaternion.identity) as GameObject;
		dust.GetComponent<ParticleSystem> ().startColor = this.GetComponent<SpriteRenderer> ().color;
		Destroy (dust, 1f);
	}

	void UpdateView (GameObject brick)
	{
		ShowParticles ();
		Destroy (this.gameObject);
		if (hasObject) {
			DropBall (objectIndex);
		}
		levelManager.IncreaseBackgroundAlpha ();
	}

	void DropBall (int index)
	{
		GameObject ball =
			Instantiate (fallingObject, this.gameObject.transform.position, Quaternion.identity) as GameObject;
		ball.GetComponent <SpriteRenderer> ().sprite = ball.GetComponent <FallingObjects> ().SetTheBall (index);
	}

	void LoadCrackedBrick ()
	{
		int index = timesHit - 1;
		if (hitSprites [index] != null)
			this.GetComponent<SpriteRenderer> ().sprite = hitSprites [index];
		else
			Debug.LogError ("Sprite is missing!");
	}
}


text:
<?php

namespace Magento\Catalog\Test\Block\Product\ProductList;

use Magento\Mtf\Block\Block;
use Magento\Mtf\Client\Locator;
use Magento\Mtf\Fixture\FixtureInterface;

/**
 * Base promoted products block.
 */
class PromotedSection extends Block
{
    /**
     * Product item block.
     *
     * @var string
     */
    protected $productItem = 'li.product-item';

    /**
     * Product item block by product name.
     *
     * @var string
     */
    protected $productItemByName = './/*[contains(@class,"product-item-link") and @title="%s"]/ancestor::li';

    /**
     * Check whether block is visible.
     *
     * @return bool
     */
    public function isVisible()
    {
        return $this->_rootElement->isVisible();
    }

    /**
     * Return product item block.
     *
     * @param FixtureInterface $product
     * @return ProductItem
     */
    public function getProductItem(FixtureInterface $product)
    {
        $locator = sprintf($this->productItemByName, $product->getName());

        return $this->blockFactory->create(
            'Magento\Catalog\Test\Block\Product\ProductList\ProductItem',
            ['element' => $this->_rootElement->find($locator, Locator::SELECTOR_XPATH)]
        );
    }

    /**
     * Return list of products.
     *
     * @return ProductItem[]
     */
    public function getProducts()
    {
        if (!$this->_rootElement->isVisible($this->productItem)) {
            return [];
        }

        $elements = $this->_rootElement->getElements($this->productItem, Locator::SELECTOR_CSS);
        $result = [];

        foreach ($elements as $element) {
            $result[] = $this->blockFactory->create(
                'Magento\Catalog\Test\Block\Product\ProductList\ProductItem',
                ['element' => $element]
            );
        }

        return $result;
    }
}


text:
# How-to: Integrate Profiles RestClient in Android

## Android Manifest

To enable network access for the client app, the app requires internet access. Add the [INTERNET](http://developer.android.com/reference/android/Manifest.permission.html#INTERNET "INTERNET PERMISSION") permission to your *AndroidManifest.xml*:

	<?xml version="1.0" encoding="utf-8"?>
	<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	    package="com.example.myprofilesapp"
	    android:versionCode="1"
	    android:versionName="1.0" >

	    <!-- add INTERNET permission here -->
	    <uses-permission android:name="android.permission.INTERNET" />

	    <!-- other declarations... -->

	</manifest>

## Libraries

Add following library files to the /libs folder (version numbers may vary):

 - utility-1.4.jar (Run **mvn clean install** to create the jar)
 - profiles-restclient-1.4.jar (Run **mvn clean install** to create the jar)
 - retrofit-1.9.0.jar (Maven [link](http://mvnrepository.com/artifact/com.squareup.retrofit/retrofit "RetroFit in Maven"))
 - gson-2.5.jar (Maven [link](http://mvnrepository.com/artifact/com.google.code.gson/gson "GSON in Maven"))

Notes:

 - These libraries have been tested with Android only. It is not guaranteed that they work with other Java VMs.
 - From version 1.1 on, profiles-restclient supports javadoc. Build the profiles-restclient with Maven to create the javadoc jar.

## App Activity

To access a Profiles endpoint, create a worker task by extending an AsyncTask and run the ProfilesRestClient inside of doInBackground. Using the AsyncTask prevents blocking the App UI (so the user does not believe the app has crashed).

	package com.example.myprofilesapp;

	/* other imports */

	// Import stuff for Profiles Client
	import net.smartcosmos.android.ProfilesRestClient;
	import net.smartcosmos.android.ProfilesRestClient.ProfilesRestResult;

	public class MyActivity extends Activity {

	    /* other activity functions */

	    // Run Worker Task
	    public void onQueryProfiles() {
	        new MyProfilesTask().execute(this);
	    }

	    // Implementation of Profiles Worker Task
	    private class MyProfilesTask extends AsyncTask<ParamsType, ProgressType, ResultType) {

	        @Override
	        protected ResultType doInBackground(ParamsType... params) {

	            try {
	                // Provide server address, username and password
	                // (for https:// the server needs a valid SSL certificate assigned by a trusted root CA)
	                // This is just a dumb example, do not hard-code the credentials in the app!!!
	                // Instead create an input dialog for the credentials.
	                ProfilesRestClient client = new ProfilesRestClient("https://profiles.example.com", "user-foo", "pw-bar");
	                // Access the method of the client
	                ProfilesRestResult result = client.getVerificationMessage("RR",  0);
	                if (result.httpStatus == 200) {
	                    String message = result.message();
	                } else {
	                    // handle bad HTTP status
	                }
	            } catch (Exception e) {
	                // handle the exception error...
	            }
	        }
	    }
	}

## Security Considerations

To secure the app and the Profiles service, perform following steps:

1. Never hard-code user/password credentials in the app. APK files can be easily reverse engineered, so it would be easy to obtain those keys.
2. Use SSL encrypted connections whenever possible. Obtain a SSL certificate from a trusted root CA for the server.
3. Avoid using Profiles Admin role users for the app. Create users with the standard User role instead and use them with the app.


text:
#ifndef NRF_MPU_H__
#define NRF_MPU_H__

#include <nrfx.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @defgroup nrf_mpu_hal MPU HAL
 * @{
 * @ingroup nrf_mpu
 * @brief   Hardware access layer for managing the Memory Protection Unit (MPU) peripheral.
 */

/**
 * @brief Macro for getting MPU region configuration mask for the specified peripheral.
 *
 * @param[in] base_addr Peripheral base address.
 *
 * @return MPU configuration mask for the specified peripheral.
 */
#define NRF_MPU_PERIPHERAL_MASK_GET(base_addr) (1UL << NRFX_PERIPHERAL_ID_GET(base_addr))

/**
 * @brief Function for setting the size of the RAM region 0.
 *
 * When memory protection is enabled, the Memory Protection Unit enforces
 * runtime protection and readback protection of resources classified as region 0.
 * See the product specification for more information.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] size  Size of the RAM region 0, in bytes. Must be word-aligned.
 */
__STATIC_INLINE void nrf_mpu_region0_ram_size_set(NRF_MPU_Type * p_reg, uint32_t size);

/**
 * @brief Function for configuring specified peripherals in the memory region 0.
 *
 * When the memory protection is enabled, the Memory Protection Unit enforces
 * runtime protection and readback protection of resources classified as region 0.
 * See the product specification for more information.
 *
 * After reset, all peripherals are configured as *not* assigned to region 0.
 *
 * @param[in] p_reg           Pointer to the structure of registers of the peripheral.
 * @param[in] peripheral_mask Mask that specifies peripherals to be configured in the memory region 0.
 *                            Compose this mask using @ref NRF_MPU_PERIPHERAL_MASK_GET macro.
 */
__STATIC_INLINE void nrf_mpu_region0_peripherals_set(NRF_MPU_Type * p_reg,
                                                     uint32_t       peripheral_mask);

/**
 * @brief Function for getting the bitmask that specifies peripherals configured in the memory region 0.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 *
 * @return Bitmask representing peripherals configured in region 0.
 */
__STATIC_INLINE uint32_t nrf_mpu_region0_peripherals_get(NRF_MPU_Type const * p_reg);

/**
 * @brief Function for enabling protection for specified non-volatile memory blocks.
 *
 * Blocks are arranged into groups of 32 blocks each. Each block size is 4 kB.
 * Any attempt to write or erase a protected block will result in hard fault.
 * The memory block protection can be disabled only by resetting the device.
 *
 * @param[in] p_reg      Pointer to the structure of registers of the peripheral.
 * @param[in] group_idx  Non-volatile memory group containing memory blocks to protect.
 * @param[in] block_mask Non-volatile memory blocks to protect. Each bit in bitmask represents
 *                       one memory block in the specified group.
 */
__STATIC_INLINE void nrf_mpu_nvm_blocks_protection_enable(NRF_MPU_Type * p_reg,
                                                          uint8_t        group_idx,
                                                          uint32_t       block_mask);

/**
 * @brief Function for setting the non-volatile memory (NVM) protection during debug.
 *
 * NVM protection during debug is disabled by default.
 *
 * @param[in] p_reg  Pointer to the structure of registers of the peripheral.
 * @param[in] enable True if NVM protection during debug is to be enabled.
 *                   False if otherwise.
 */
__STATIC_INLINE void nrf_mpu_nvm_protection_in_debug_set(NRF_MPU_Type * p_reg,
                                                         bool           enable);

#ifndef SUPPRESS_INLINE_IMPLEMENTATION

__STATIC_INLINE void nrf_mpu_region0_ram_size_set(NRF_MPU_Type * p_reg, uint32_t size)
{
    NRFX_ASSERT(nrfx_is_word_aligned((const void *)size));
    p_reg->RLENR0 = size;
}

__STATIC_INLINE void nrf_mpu_region0_peripherals_set(NRF_MPU_Type * p_reg,
                                                     uint32_t       peripheral_mask)
{
    p_reg->PERR0 = peripheral_mask;
}

__STATIC_INLINE uint32_t nrf_mpu_region0_peripherals_get(NRF_MPU_Type const * p_reg)
{
    return p_reg->PERR0;
}

__STATIC_INLINE void nrf_mpu_nvm_blocks_protection_enable(NRF_MPU_Type * p_reg,
                                                          uint8_t        group_idx,
                                                          uint32_t       block_mask)
{
    switch (group_idx)
    {
        case 0:
            p_reg->PROTENSET0 = block_mask;
            break;

        case 1:
            p_reg->PROTENSET1 = block_mask;
            break;

        default:
            NRFX_ASSERT(false);
            break;
    }
}

__STATIC_INLINE void nrf_mpu_nvm_protection_in_debug_set(NRF_MPU_Type * p_reg,
                                                         bool           enable)
{
    p_reg->DISABLEINDEBUG =
        (enable ? 0 : MPU_DISABLEINDEBUG_DISABLEINDEBUG_Msk);
}

#endif // SUPPRESS_INLINE_IMPLEMENTATION

/** @} */

#ifdef __cplusplus
}
#endif

#endif // NRF_MPU_H__


text:
.. _bigip_partition:

bigip_partition - Manage BIG-IP partitions
++++++++++++++++++++++++++++++++++++++++++

.. versionadded:: 2.2

.. contents::
   :local:
   :depth: 1

Synopsis
--------

Manage BIG-IP partitions

Requirements (on host that executes module)
-------------------------------------------

  * bigsuds
  * requests

Options
-------

.. raw:: html

    parameter
    required
    default
    choices
    comments

    description

    no
    None

The description to attach to the Partition

    route_domain

    no
    None

The default Route Domain to assign to the Partition. If no route domain is specified, then the default route domain for the system (typically zero) will be used only when creating a new partition. route_domain and route_domain_id are mutually exclusive.

    route_domain_id

    no
    None

The default Route Domain ID to assign to the Partition. If you track the route domains by their numeric identifier, then this argument can be used to supply that ID. route_domain and route_domain_id are mutually exclusive.

    server

    yes

BIG-IP host

    state

    no
    present

present

absent

Whether the partition should exist or not

    user

    no

BIG-IP username

    validate_certs

    no
    True

If no, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.

Examples
--------

 ::

    - name: Create partition "foo" using the default route domain
      bigip_partition:
          name: "foo"
          password: "secret"
          server: "lb.mydomain.com"
          user: "admin"

    - name: Delete the foo partition
      bigip_partition:
          name: "foo"
          password: "secret"
          server: "lb.mydomain.com"
          user: "admin"
          state: "absent"

Return Values
-------------

Common return values are documented here :doc:`common_return_values`, the following are the fields unique to this module:

.. raw:: html

    name
    description
    returned
    type
    sample

         route_domain_id
         ID of the route domain associated with the partition
         changed and success
         string
         0

         route_domain
         Name of the route domain associated with the partition
         changed and success
         string
         /Common/asdf

         description
         The description of the partition
         changed and success
         string
         Example partition

         name
         The name of the partition
         changed and success
         string
         /foo

Notes
-----

.. note:: Requires the bigsuds Python package on the host if using the iControl interface. This is as easy as pip install bigsuds

This is an Extras Module
------------------------

For more information on what this means please read :doc:`modules_extra`

For help in developing on modules, should you be so inclined, please read :doc:`community`, :doc:`developing_test_pr` and :doc:`developing_modules`.


text:
// page initialization
$(document).ready(function () {
    getExposureLevel();
});

$("#update-default-version").click(function () {
    var versionName = $("#default-version option:selected").val();

    jagg.post("../blocks/settings/settings.jag", {
        action: "updateDefaultVersion",
        applicationName: applicationName,
        defaultVersion: versionName
    },function defaultVersionUpdatedSuccess(result) {
        //alert(result);
        var defaultVersion = "Default version is set to " + $("#default-version option:selected").val();
        $("#lbl-default-version").text(defaultVersion);
        jagg.message({content: "Default version is successfully updated.", type: 'success', id: 'view_log'});
        setTimeout(redirectAppHome, 3000);
        function redirectAppHome(){
            window.location.replace("home.jag?applicationKey=" + result);
        }
    },function (jqXHR, textStatus, errorThrown) {
        jagg.message({content: jqXHR.responseText, type: 'error', id: 'view_log'});

    });
});

$("#update-exposure-level").click(function () {
    var versionName = $("#exposure-level-version-list option:selected").val();

    jagg.post("../blocks/application/application.jag", {
        action: "updateVersionExposureLevel",
        applicationName: applicationName,
        versionName: versionName,
        exposureLevel: $("input:radio[name='security-radio']:checked").val()
    },function exposureLevelUpdatedSuccess(result) {
        jagg.message({content: "Exposure level is successfully updated.", type: 'success', id: 'view_log'});

    },function (jqXHR, textStatus, errorThrown) {
        jagg.message({content: jqXHR.responseText, type: 'error', id: 'view_log'});

    });
});

$("#exposure-level-version-list").change(function () {
    getExposureLevel();
});

function getExposureLevel() {
    var versionName = $("#exposure-level-version-list option:selected").val();
    jagg.post("../blocks/application/application.jag", {
        action:"getExposureLevel",
        versionName:versionName,
        applicationName:applicationName
    },function (result) {
        $("#security-" + result).prop("checked", true);
    },function (jqXHR, textStatus, errorThrown) {
        jagg.message({content: "Error occurred while retrieving the endpoint security level of the selected "
                    + cloudSpecificApplicationRepresentation.toLowerCase() + " version", type: 'error', id:'view_log'});
    });
}


text:
#ifndef _LINUX_IOPORT_H
#define _LINUX_IOPORT_H
#include <linux/compiler.h>
#include <linux/types.h>
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
struct resource {
 resource_size_t start;
 resource_size_t end;
 const char *name;
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 unsigned long flags;
 struct resource *parent, *sibling, *child;
};
struct resource_list {
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 struct resource_list *next;
 struct resource *res;
 struct pci_dev *dev;
};
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_BITS 0x000000ff
#define IORESOURCE_IO 0x00000100
#define IORESOURCE_MEM 0x00000200
#define IORESOURCE_IRQ 0x00000400
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_DMA 0x00000800
#define IORESOURCE_PREFETCH 0x00001000
#define IORESOURCE_READONLY 0x00002000
#define IORESOURCE_CACHEABLE 0x00004000
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_RANGELENGTH 0x00008000
#define IORESOURCE_SHADOWABLE 0x00010000
#define IORESOURCE_BUS_HAS_VGA 0x00080000
#define IORESOURCE_DISABLED 0x10000000
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_UNSET 0x20000000
#define IORESOURCE_AUTO 0x40000000
#define IORESOURCE_BUSY 0x80000000
#define IORESOURCE_IRQ_HIGHEDGE (1<<0)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_IRQ_LOWEDGE (1<<1)
#define IORESOURCE_IRQ_HIGHLEVEL (1<<2)
#define IORESOURCE_IRQ_LOWLEVEL (1<<3)
#define IORESOURCE_IRQ_SHAREABLE (1<<4)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_DMA_TYPE_MASK (3<<0)
#define IORESOURCE_DMA_8BIT (0<<0)
#define IORESOURCE_DMA_8AND16BIT (1<<0)
#define IORESOURCE_DMA_16BIT (2<<0)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_DMA_MASTER (1<<2)
#define IORESOURCE_DMA_BYTE (1<<3)
#define IORESOURCE_DMA_WORD (1<<4)
#define IORESOURCE_DMA_SPEED_MASK (3<<6)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_DMA_COMPATIBLE (0<<6)
#define IORESOURCE_DMA_TYPEA (1<<6)
#define IORESOURCE_DMA_TYPEB (2<<6)
#define IORESOURCE_DMA_TYPEF (3<<6)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_MEM_WRITEABLE (1<<0)
#define IORESOURCE_MEM_CACHEABLE (1<<1)
#define IORESOURCE_MEM_RANGELENGTH (1<<2)
#define IORESOURCE_MEM_TYPE_MASK (3<<3)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_MEM_8BIT (0<<3)
#define IORESOURCE_MEM_16BIT (1<<3)
#define IORESOURCE_MEM_8AND16BIT (2<<3)
#define IORESOURCE_MEM_32BIT (3<<3)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_MEM_SHADOWABLE (1<<5)
#define IORESOURCE_MEM_EXPANSIONROM (1<<6)
#define IORESOURCE_ROM_ENABLE (1<<0)
#define IORESOURCE_ROM_SHADOW (1<<1)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define IORESOURCE_ROM_COPY (1<<2)
#define request_region(start,n,name) __request_region(&ioport_resource, (start), (n), (name))
#define request_mem_region(start,n,name) __request_region(&iomem_resource, (start), (n), (name))
#define rename_region(region, newname) do { (region)->name = (newname); } while (0)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define release_region(start,n) __release_region(&ioport_resource, (start), (n))
#define check_mem_region(start,n) __check_region(&iomem_resource, (start), (n))
#define release_mem_region(start,n) __release_region(&iomem_resource, (start), (n))
#endif
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */


text:
#define BOOST_TEST_MAIN

#include <boost/format.hpp>
#include <boost/test/unit_test.hpp>

#include <TudatCore/Astrodynamics/BasicAstrodynamics/unitConversions.h>
#include <TudatCore/Basics/testMacros.h>

#include "Tudat/Astrodynamics/BasicAstrodynamics/geodeticCoordinateConversions.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_geodetic_coordinate_conversions )

BOOST_AUTO_TEST_CASE( testGeodeticCoordinateConversions )
{
    using namespace tudat::basic_astrodynamics::coordinate_conversions;
    using namespace tudat::basic_astrodynamics::unit_conversions;

    // Expected Cartesian state, Montenbruck & Gill (2000) Exercise 5.3.
    const Eigen::Vector3d testCartesianPosition( 1917032.190, 6029782.349, -801376.113 );

    // Expected Cartesian state, Montenbruck & Gill (2000) Exercise 5.3.
    const Eigen::Vector3d testGeodeticPosition( -63.667,
                                                convertDegreesToRadians( -7.26654999 ),
                                                convertDegreesToRadians( 72.36312094 ) );

    // Central body characteristics (WGS84 Earth ellipsoid).
    const double flattening = 1.0 / 298.257223563;
    const double equatorialRadius = 6378137.0;

    // Test conversion to geodetic coordinates.
    {
        // Calculate geodetic position.
        const Eigen::Vector3d calculatedGeodeticPosition =
                convertCartesianToGeodeticCoordinates(
                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );

        // Compare per coefficients (different tolerances).
        BOOST_CHECK_SMALL( calculatedGeodeticPosition.x( ) - testGeodeticPosition.x( ), 1.0E-4 );
        BOOST_CHECK_SMALL( calculatedGeodeticPosition.y( ) - testGeodeticPosition.y( ), 1.0E-10 );
        BOOST_CHECK_SMALL( calculatedGeodeticPosition.z( ) - testGeodeticPosition.z( ), 1.0E-10 );
    }

    // Test separate functions for altitude and geodetic latitude.
    {
        // Calculate altitude and geodetic latitude using dedicated functions.
        const double directAltitude = calculateAltitudeOverOblateSpheroid(
                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );
        const double directGeodeticLatitude = calculateGeodeticLatitude(
                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );

        // Compare values.
        BOOST_CHECK_SMALL( directAltitude - testGeodeticPosition.x( ), 1.0E-4 );
        BOOST_CHECK_SMALL( directGeodeticLatitude - testGeodeticPosition.y( ), 1.0E-10 );
    }

    // Test conversions from geodetic coordinates to cartesian position.
    {
        const Eigen::Vector3d calculateCartesianPosition =
                convertGeodeticToCartesianCoordinates(
                    testGeodeticPosition, equatorialRadius, flattening  );

        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
                    calculateCartesianPosition, testCartesianPosition, 1.0E-9 );
    }
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat


text:
/* $NetBSD: t_mktime.c,v 1.5 2012/03/18 07:33:58 jruoho Exp $ */

/*-
 * Copyright (c) 2011 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <atf-c.h>

#include <err.h>
#include <errno.h>
#include <string.h>
#include <time.h>

ATF_TC(localtime_r_gmt);
ATF_TC_HEAD(localtime_r_gmt, tc)
{
	atf_tc_set_md_var(tc, "descr", "Test that localtime_r(3) "
	    "returns localtime, not GMT (PR lib/28324)");
}

ATF_TC_BODY(localtime_r_gmt, tc)
{
	struct tm *t;
	struct tm tt;
	time_t x;

	x = time(NULL);
	localtime_r(&x, &tt);
	t = localtime(&x);

	if (t->tm_sec != tt.tm_sec || t->tm_min != tt.tm_min ||
	    t->tm_hour != tt.tm_hour || t->tm_mday != tt.tm_mday)
		atf_tc_fail("inconsistencies between "
		    "localtime(3) and localtime_r(3)");
}

ATF_TC(mktime_negyear);
ATF_TC_HEAD(mktime_negyear, tc)
{
	atf_tc_set_md_var(tc, "descr", "Test mktime(3) with negative year");
}

ATF_TC_BODY(mktime_negyear, tc)
{
	struct tm tms;
	time_t t;

	(void)memset(&tms, 0, sizeof(tms));
	tms.tm_year = ~0;

	errno = 0;
	t = mktime(&tms);
	ATF_REQUIRE_ERRNO(0, t != (time_t)-1);
}

ATF_TC(timegm_epoch);
ATF_TC_HEAD(timegm_epoch, tc)
{
	atf_tc_set_md_var(tc, "descr", "Test timegm(3) close to the epoch");
}

ATF_TC_BODY(timegm_epoch, tc)
{
	struct tm tms;
	time_t t;

	/* midnight on 1 Jan 1970 */
	(void)memset(&tms, 0, sizeof(tms));
	errno = 0;
	tms.tm_year = 1970 - 1900;
	tms.tm_mday = 1;
	t = timegm(&tms);
	ATF_REQUIRE_ERRNO(0, t == (time_t)0);

	/* one second after midnight on 1 Jan 1970 */
	(void)memset(&tms, 0, sizeof(tms));
	errno = 0;
	tms.tm_year = 1970 - 1900;
	tms.tm_mday = 1;
	tms.tm_sec = 1;
	t = timegm(&tms);
	ATF_REQUIRE_ERRNO(0, t == (time_t)1);

	/*
	 * 1969-12-31 23:59:59 = one second before the epoch.
	 * Result should be -1 with errno = 0.
	 */
	(void)memset(&tms, 0, sizeof(tms));
	errno = 0;
	tms.tm_year = 1969 - 1900;
	tms.tm_mon = 12 - 1;
	tms.tm_mday = 31;
	tms.tm_hour = 23;
	tms.tm_min = 59;
	tms.tm_sec = 59;
	t = timegm(&tms);
	ATF_REQUIRE_ERRNO(0, t == (time_t)-1);

	/*
	 * Another way of getting one second before the epoch:
	 * Set date to 1 Jan 1970, and time to -1 second.
	 */
	(void)memset(&tms, 0, sizeof(tms));
	errno = 0;
	tms.tm_year = 1970 - 1900;
	tms.tm_mday = 1;
	tms.tm_sec = -1;
	t = timegm(&tms);
	ATF_REQUIRE_ERRNO(0, t == (time_t)-1);

	/*
	 * Two seconds before the epoch.
	 */
	(void)memset(&tms, 0, sizeof(tms));
	errno = 0;
	tms.tm_year = 1970 - 1900;
	tms.tm_mday = 1;
	tms.tm_sec = -2;
	t = timegm(&tms);
	ATF_REQUIRE_ERRNO(0, t == (time_t)-2);

}

ATF_TP_ADD_TCS(tp)
{

	ATF_TP_ADD_TC(tp, localtime_r_gmt);
	ATF_TP_ADD_TC(tp, mktime_negyear);
	ATF_TP_ADD_TC(tp, timegm_epoch);

	return atf_no_error();
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
  [<!ENTITY identifiableProperties SYSTEM "classpath://org/hisp/dhis/common/identifiableProperties.hbm">]
  >

<hibernate-mapping>
  <class name="org.hisp.dhis.dataentryform.DataEntryForm" table="dataentryform">

    <cache usage="read-write" />

    <id name="id" column="dataentryformid">
      <generator class="native" />
    </id>
    &identifiableProperties;

    <property name="name" not-null="true" unique="true" length="160" />

    <property name="style" length="40">
      <type name="org.hibernate.type.EnumType">
        <param name="enumClass">org.hisp.dhis.common.DisplayDensity</param>
        <param name="useNamed">true</param>
        <param name="type">12</param>
      </type>
    </property>

    <property name="htmlCode" column="htmlcode" type="text" />

    <property name="format" />

    <property name="translations" type="jblTranslations"/>

  </class>

</hibernate-mapping>


text:
require("should");
var _ = require("underscore");
var sinon = require("sinon");
var Platos = require("../../lib/platos-model");

describe("INTEGRATION - INHERITANCE", function () {
	var ParentModel, Model;

	beforeEach(function (done) {
		ParentModel = Platos.create("ParentModel");
		Model = Platos.create("Model");
		Model.inherits(ParentModel);

		Platos._db.collection("ParentModel").drop(function () {
			done();
		});
	});

	afterEach(function (done) {
		return done();
		Platos._db.collection("ParentModel").drop(done);
	});

	describe("save", function () {
		it("model.save() - with 1 parent instance and 1 child instance - should save without errors", function (done) {
			var parent = new ParentModel({ parent: "Why won't they..." });
			var model = new Model({ child: "talk to me?" });

			parent.save(function (err, document) {
				_.isNull(err).should.be.ok;
				document.should.have.property("parent");
				document.should.not.have.property("_model");

				model.save(function (err, document) {
					_.isNull(err).should.be.ok;
					document.should.have.property("child");
					document.should.not.have.property("_model");

					done();
				});
			});
		});

		it("model.save() - with three levels of inheritance - should save without errors", function (done) {
			var stub = sinon.stub();
			var Child = Platos.create("Child");

			Child.inherits(Model);

			var child = new Child({ inception: "not really" });

			child.save(function (err, document) {
				_.isNull(err).should.be.ok;
				document.should.have.property("inception");

				done();
			});
		});

		it("model.save() - with pre hook on parent and child - should call both hooks", function (done) {
			var stub = sinon.stub();
			var model = new Model();

			ParentModel.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(1);
				stub();
				next(callback);
			});

			Model.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(0);
				stub();
				next(callback);
			});

			model.save(function () {
				stub.callCount.should.equal(2);
				done();
			});
		});

		it("model.save() - with three levels of inheritance and pre hooks on all - should call all hooks", function (done) {
			var stub = sinon.stub();
			var Child = Platos.create("Child");

			Child.inherits(Model);

			var child = new Child();

			ParentModel.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(2);
				stub();
				next(callback);
			});

			Model.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(1);
				stub();
				next(callback);
			});

			Child.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(0);
				stub();
				next(callback);
			});

			child.save(function () {
				stub.callCount.should.equal(3);
				done();
			});
		});

		it("model.save() - with three levels of inheritance and pre hooks on all - each pre hook should access properties", function (done) {
			var Child = Platos.create("Child");

			Child.inherits(Model);

			var child = new Child({ important: "property"});

			ParentModel.prototype.pre("save", function (next, callback) {
				this.should.have.property("important");
				next(callback);
			});

			Model.prototype.pre("save", function (next, callback) {
				this.should.have.property("important");
				next(callback);
			});

			Child.prototype.pre("save", function (next, callback) {
				this.should.have.property("important");
				next(callback);
			});

			child.save(function (err, document) {
				document.should.have.property("important");
				done();
			});
		});

		it("model.save() - with pre hook parent and different child - should only call the parent hook", function (done) {
			var Model2 = Platos.create("Model2");
			var stub = sinon.stub();
			var model = new Model();

			Model2.inherits(ParentModel);

			ParentModel.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(0);
				stub();
				next(callback);
			});

			Model2.prototype.pre("save", function (next, callback) {
				stub();
				next(callback);
			});

			model.save(function () {
				stub.callCount.should.equal(1);
				done();
			});
		});

		it("model.save() - with pre hook on parent and late-bound inherited child - should call both hooks", function (done) {
			var stub = sinon.stub();
			var ParentModelEarly = Platos.create("ParentModelEarly", "ParentModel");

			ParentModelEarly.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(1);
				stub();
				next(callback);
			});

			var ModelLate = Platos.create("ModelLate");

			//Note that the model is inherited after parent hooks have been defined
			ModelLate.inherits(ParentModelEarly);

			ModelLate.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(0);
				stub();
				next(callback);
			});

			var model = new ModelLate();

			model.save(function () {
				stub.callCount.should.equal(2);
				done();
			});
		});

		it("model.save() - with pre hook on parent but different late-bound inherited child - should only call the parent hook", function (done) {
			var stub = sinon.stub();
			var ParentModelEarly = Platos.create("ParentModelEarly", "ParentModel");

			ParentModelEarly.prototype.pre("save", function (next, callback) {
				stub.callCount.should.equal(0);
				stub();
				next(callback);
			});

			var ModelLate = Platos.create("ModelLate");
			var ModelLate2 = Platos.create("ModelLate2");

			//Note that the model is inherited after parent hooks have been defined
			ModelLate.inherits(ParentModelEarly);
			ModelLate2.inherits(ParentModelEarly);

			ModelLate2.prototype.pre("save", function (next, callback) {
				stub();
				next(callback);
			});

			var model = new ModelLate();

			model.save(function () {
				stub.callCount.should.equal(1);
				done();
			});
		});

		describe("custom collections", function () {
			var CustomParentModel;
			var CustomModel;

			before(function () {
				CustomParentModel = Platos.create("CustomParentModel");
				CustomModel = Platos.create("Model", "ParentModel");

				Model.inherits(ParentModel);
			});

			it("model.save() - on child instance - should save to custom collection name", function (done) {
				var model = new CustomModel({ child: "Palm tree in the summer..." });

				model.save(function (err) {
					_.isNull(err).should.be.ok;

					Platos._db.collection("ParentModel").find(function (err, documents) {
						_.isNull(err).should.be.ok;
						_.isArray(documents).should.be.ok;
						documents.length.should.equal(1);
						documents[0].should.have.property("child");

						done();
					});
				});
			});
		});
	});

	describe("find", function () {
		beforeEach(function (done) {
			var parent = new ParentModel({ parent: "Why won't they..." });
			var model = new Model({ child: "talk to me?" });

			parent.save(function () {
				model.save(done);
			});
		});

		it("Model.find() - on parent with 1 parent instance and 1 child instance - should retrieve 2 instances", function (done) {
			ParentModel.find(function (err, models) {
				_.isNull(err).should.be.ok;
				models.length.should.equal(2);

				done();
			});
		});

		it("Model.find() - on parent with 1 parent instance and 1 child instance - instances should not contain metadata", function (done) {
			ParentModel.find(function (err, models) {
				_.isNull(err).should.be.ok;
				models[0].should.have.property("parent");
				models[1].should.have.property("child");
				models[0].should.not.have.property("_model");
				models[1].should.not.have.property("_model");

				done();
			});
		});

		it("Model.find() - on parent with 1 parent instance and 1 child instance - instances should be correct types", function (done) {
			ParentModel.find(function (err, models) {
				models[0]._meta.name.should.equal("ParentModel");
				models[1]._meta.name.should.equal("Model");

				done();
			});
		});
	});
});


text:
<?php
/**
 * This file is part of Cursosf2Application.
 *
 * Cursosf2Application is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cursosf2Application is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cursosf2Application.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace Cursosf2\UsuariosBundle\Form\Frontend;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class UsuarioType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->
            add('nombre')->
            add('apellidos')->
            add('descripcion','textarea')->
            add('email', 'email')->
            add('foto', 'file')->
            add('password', 'repeated', array(
                'type' => 'password',
                'invalid_message' => 'Las dos contraseñas deben coincidir',
                'options' => array('label' => 'Contraseña')
            ));
    }

    public function getName()
    {
        return 'cursosf2_usuariosbundle_usuariotype';
    }
}


text:
class EnlargeEventInfo < ActiveRecord::Migration
	def self.up
		change_column :events, :info, :text
	end

	def self.down
		change_column :events, :info, :string, :limit => 65535
	end
end


text:
/*
 * GET home page.
 */

exports.view = function(req, res){
  res.render('index');
};


text:
using System.Runtime.InteropServices;

namespace Grabacr07.KanColleViewer.Win32
{
	[StructLayout(LayoutKind.Sequential)]
	internal class RECT
	{
		public int left;
		public int top;
		public int width;
		public int height;
	}
}


text:
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Single;
using MathNet.Numerics.LinearAlgebra.Single.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;

namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Solvers.Preconditioners
{
    /// <summary>
    /// Diagonal preconditioner test.
    /// </summary>
    [TestFixture, Category("LASolver")]
    public sealed class DiagonalTest : PreconditionerTest
    {
        /// <summary>
        /// Create preconditioner.
        /// </summary>
        /// <returns>New preconditioner instance.</returns>
        internal override IPreconditioner<float> CreatePreconditioner()
        {
            return new DiagonalPreconditioner();
        }

        /// <summary>
        /// Check the result.
        /// </summary>
        /// <param name="preconditioner">Specific preconditioner.</param>
        /// <param name="matrix">Source matrix.</param>
        /// <param name="vector">Initial vector.</param>
        /// <param name="result">Result vector.</param>
        protected override void CheckResult(IPreconditioner<float> preconditioner, SparseMatrix matrix, Vector<float> vector, Vector<float> result)
        {
            Assert.AreEqual(typeof (DiagonalPreconditioner), preconditioner.GetType(), "#01");

            // Compute M * result = product
            // compare vector and product. Should be equal
            var product = new DenseVector(result.Count);
            matrix.Multiply(result, product);

            for (var i = 0; i < product.Count; i++)
            {
                Assert.IsTrue(((double) vector[i]).AlmostEqualNumbersBetween(product[i], -Epsilon.Magnitude()), "#02-" + i);
            }
        }
    }
}