text:
class ReceiveSamplesController < ApplicationController

	before_filter :may_create_samples_required,
		:only => [:new,:create]

	before_filter :valid_study_subject_id_required,
		:only => [:create]

	before_filter :valid_sample_for_subject_required,
		:only => [:create]

	def new
		if !params[:study_subject_id].blank?
			unless @study_subject = StudySubject.where(
					:id => params[:study_subject_id] ).first.try(:child)
				flash.now[:warn] = "No Study Subjects Found."
			end
		elsif !params[:q].blank?
			#	As studyid and icf_master_id are different formats
			#	there should never actually be more than one match.
			study_subject = StudySubject.where(
				StudySubject.arel_table[:studyid].eq(params[:q]).or(
					StudySubject.arel_table[:icf_master_id].eq(params[:q]))).limit(1).first
#				'studyid = :q OR icf_master_id = :q', :q => params[:q]).limit(1).first

			#	get the child, in case given mother's icf_master_id
			#	if no study subject found, study_subject is nil, so use try
			study_subject = study_subject.try(:child)

			if study_subject
				@study_subject = study_subject
			else
				flash.now[:warn] = "No Study Subjects Found."
			end
		end
		if @study_subject
#
#	SHOULD be at least CCLS.
#	SHOULD also only include consented enrollments (but using all for now)
#
			@sample = Sample.new
		end
	end

	def create

		@sample = @sample_for_subject.samples.new(sample_params)
		@sample.received_by_ccls_at = DateTime.current

		#	All or nothin'
		Sample.transaction do
			@sample.save!
			@sample.sample_transfers.create!(
				:source_org_id => @sample.organization_id,
				:status        => 'waitlist')
			@sample_for_subject.operational_events.create!(
				:description               => "Sample received: #{@sample.sample_type}",
				:project_id                => @sample.project_id,
				:operational_event_type_id => OperationalEventType['sample_received'].id,
				:occurred_at               => DateTime.current
			)
			@sample_for_subject.ccls_enrollment.update_column(:vaccine_authorization_received_at,
				DateTime.current) if params[:vaccine_authorization_received].present?
		end

		flash.now[:notice] = "Sample and Transfer creation for #{@sample_source} succeeded."
		render :action => 'new'
	rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved
		flash.now[:error] = "Sample and Transfer creation failed."
		render :action => 'new'
	end

protected

	#	redefined as needed to change redirect
	def valid_study_subject_id_required
		if !params[:study_subject_id].blank? and
				StudySubject.exists?(params[:study_subject_id])
			@study_subject = StudySubject.find(params[:study_subject_id])
		else
			#	could be confusing as the study_subject_id is in the link,
			#	not explicitly provided by the user.
			access_denied("Invalid study_subject id!", new_receive_sample_path)
		end
	end

	def valid_sample_for_subject_required
		@sample_source = params[:sample_source] || 'child'
		#	@study_subject should really always be a child
		#	however, deal with possible
		@sample_for_subject = if( @sample_source.match(/mother/i) )
			( @study_subject.is_mother? ) ? @study_subject : @study_subject.mother
		else
			( @study_subject.is_child? ) ? @study_subject : @study_subject.child
		end
		if @sample_for_subject.blank?
			#@sample = Sample.new(params[:sample])	#	for valid form
			@sample = Sample.new(sample_params)	#	for valid form
			flash.now[:error] = "Sample source / subject type mismatch."
			#	this render trigger filter failure so nothing else happens.
			render :action => 'new'
		end
	end

	def sample_params
		params.require(:sample).permit(:project_id,:sample_type_id,:sample_temperature,
			:sent_to_subject_at, :collected_from_subject_at, :shipped_to_ccls_at)
	end

end
__END__


text:
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    'voku\\helper\\' => array($vendorDir . '/voku/urlify/src/voku/helper', $vendorDir . '/voku/email-check/src/voku/helper', $vendorDir . '/voku/anti-xss/src/voku/helper'),
    'voku\\' => array($vendorDir . '/voku/stop-words/src/voku', $vendorDir . '/voku/portable-ascii/src/voku', $vendorDir . '/voku/portable-utf8/src/voku'),
    'phpDocumentor\\Reflection\\' => array($vendorDir . '/phpdocumentor/reflection-common/src', $vendorDir . '/phpdocumentor/type-resolver/src', $vendorDir . '/phpdocumentor/reflection-docblock/src'),
    'WordpressLib\\' => array($baseDir . '/src'),
    'Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'),
    'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
    'Symfony\\Polyfill\\Php72\\' => array($vendorDir . '/symfony/polyfill-php72'),
    'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
    'Symfony\\Polyfill\\Intl\\Normalizer\\' => array($vendorDir . '/symfony/polyfill-intl-normalizer'),
    'Symfony\\Polyfill\\Intl\\Idn\\' => array($vendorDir . '/symfony/polyfill-intl-idn'),
    'Symfony\\Polyfill\\Intl\\Grapheme\\' => array($vendorDir . '/symfony/polyfill-intl-grapheme'),
    'Symfony\\Polyfill\\Iconv\\' => array($vendorDir . '/symfony/polyfill-iconv'),
    'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
    'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'),
    'Stringy\\' => array($vendorDir . '/voku/stringy/src'),
    'Functional\\' => array($vendorDir . '/lstrojny/functional-php/src/Functional'),
    'Defuse\\Crypto\\' => array($vendorDir . '/defuse/php-encryption/src'),
    'Arrayy\\' => array($vendorDir . '/voku/arrayy/src'),
);

redpajama_set_name: RedPajamaGithub


text:
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { DragulaModule } from '../ng2-dragula';

const html = ``;

describe('Component: ng2-dragula', () => {
  let fixture:ComponentFixture<any>;
  let context:TestNGDragulaComponent;
  let element:any;
  let clean:any;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestNGDragulaComponent],
      imports: [DragulaModule]
    });
    TestBed.overrideComponent(TestNGDragulaComponent, {set: {template: html}});
    fixture = TestBed.createComponent(TestNGDragulaComponent);
    context = fixture.componentInstance;
    element = fixture.nativeElement.querySelector('#c1');
    clean = fixture.nativeElement.querySelector('#c2');
    fixture.detectChanges();
  });

  it('fixture should not be null', () => {
    expect(fixture).not.toBeNull();
  });
});

@Component({
  selector: 'dragula-test',
  template: ''
})
class TestNGDragulaComponent {
}


text:
package griffon.core.editors;

import griffon.core.formatters.DoubleFormatter;
import griffon.core.formatters.Formatter;

import static griffon.util.GriffonNameUtils.isBlank;

/**
 * @author Andres Almiray
 * @since 2.0.0
 */
public class DoublePropertyEditor extends AbstractPropertyEditor {
    protected void setValueInternal(Object value) {
        if (null == value) {
            super.setValueInternal(null);
        } else if (value instanceof CharSequence) {
            handleAsString(String.valueOf(value));
        } else if (value instanceof Number) {
            handleAsNumber((Number) value);
        } else {
            throw illegalValue(value, Double.class);
        }
    }

    private void handleAsString(String str) {
        try {
            super.setValueInternal(isBlank(str) ? null : Double.parseDouble(str));
        } catch (NumberFormatException e) {
            throw illegalValue(str, Double.class, e);
        }
    }

    private void handleAsNumber(Number number) {
        super.setValueInternal(number.doubleValue());
    }

    protected Formatter<Double> resolveFormatter() {
        return isBlank(getFormat()) ? null : new DoubleFormatter(getFormat());
    }
}


text:
<?php
/**
 * Used to decrement a counter into a template
 *
 * @example
 * {% decrement value %}
 *
 * @author Viorel Dram
 *
 * @package Liquid
 */

class LiquidTagDecrement extends LiquidTag
{
    /**
     * Name of the variable to decrement
     *
     * @var int
     */
    private $_toDecrement;

    /**
     * Constructor
     *
     * @param string $markup
     * @param array $tokens
     * @param LiquidFileSystem $fileSystem
     * @return AssignLiquidTag
     */
    public function __construct($markup, &$tokens, &$fileSystem)
    {
        $syntax = new LiquidRegexp("/(" . LIQUID_ALLOWED_VARIABLE_CHARS . "+)/");

        if ($syntax->match($markup))
        {
            $this->_toDecrement = $syntax->matches[0];
        }
        else
        {
            throw new LiquidException("Syntax Error in 'decrement' - Valid syntax: decrement [var]");
        }
    }

    /**
     * Renders the tag
     *
     * @param LiquidContext $context
     */
    public function render(&$context)
    {
        // if the value is not set in the environment check to see if it
        // exists in the context, and if not set it to 0
        if (!isset($context->environments[0][$this->_toDecrement]))
        {
            // check for a context value
            $from_context = $context->get($this->_toDecrement);

            // we already have a value in the context
            $context->environments[0][$this->_toDecrement] = (null !== $from_context) ? $from_context : 0;
        }

        // decrement the environment value
        $context->environments[0][$this->_toDecrement]--;
    }
}


text:
module GrafikaApp {
    // Initialize and Configure Scroll Reveal Animation
    let sr = ScrollReveal();
    sr.reveal('.sr-icons', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 200);
    sr.reveal('.sr-button', {
        duration: 1000,
        delay: 200
    });
    sr.reveal('.sr-contact', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 300);
    window['sr'] = sr;

    // Initialize and Configure Magnific Popup Lightbox Plugin
    $('.popup-gallery').magnificPopup({
        delegate: 'a',
        type: 'ajax',
        closeMarkup: '<button title= "%title%" type= "button" class="mfp-close" style="margin-top: -40px; margin-right: -16px; color: white" >×</button>',
        mainClass: 'preview-animation-popup'
    });

    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $(document).on('click', 'a.page-scroll', function (event) {
        let $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    export class Home {
        public animPlayer: GrafikaApp.Player;

        public loadRandomAnimation(): Q.IPromise<any> {
            jQuery('#btn-random-animation').attr('disabled', 'disabled');

            if (!this.animPlayer)
                this.animPlayer = new GrafikaApp.Player('#header-canvas');
            let element = jQuery('#random-animation-author');
            if (element.text().trim().length > 0)
                element.fadeOut();

            return jQuery.ajax({ url: `${GrafikaApp.Configuration.baseApiUrl}/animations?isRandom=true&isPublic=true`, cache: false }).done((res) => {
                let animation = res[0] as Grafika.IAnimation;
                let slug = GrafikaApp.generateSlug(animation.name);
                element.html(`<a href="/animations/${animation._id}/${slug}" title="View this animation">${animation.name} by ${animation.author}</a>`).fadeIn();
                return this.animPlayer.loadAnimation(animation._id).then(() => {
                    jQuery('#btn-random-animation').removeAttr('disabled');
                    return this.animPlayer.play();
                });
            });
        }
    }

    $(document).ready(() => {
        let home = new GrafikaApp.Home();
        window['home'] = home;

        setTimeout(() => {
            home.loadRandomAnimation();
        }, 1000);
    });
}


text:
static const LONG UTIL_TAG = 'util';

// Change it to 0xCC when you want to install break points for patched code
static const UCHAR UTIL_HOOK_ENTRY_CODE = 0x90;

////////////////////////////////////////////////////////////////////////////////
//
// types
//

////////////////////////////////////////////////////////////////////////////////
//
// prototypes
//

////////////////////////////////////////////////////////////////////////////////
//
// variables
//

////////////////////////////////////////////////////////////////////////////////
//
// implementations
//

// Disable the write protection
EXTERN_C
void Ia32DisableWriteProtect()
{
    CR0_REG Cr0 = {};
    Cr0.All = __readcr0();
    Cr0.Field.WP = FALSE;
    __writecr0(Cr0.All);
}

// Enable the write protection
EXTERN_C
void Ia32EnableWriteProtect()
{
    CR0_REG Cr0 = {};
    Cr0.All = __readcr0();
    Cr0.Field.WP = TRUE;
    __writecr0(Cr0.All);
}

// Return an address of PXE
EXTERN_C
PHARDWARE_PTE MiAddressToPxe(
    __in void* Address)
{
    ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PXI_SHIFT - 3);
    Offset &= (PXI_MASK << 3);
    return reinterpret_cast<PHARDWARE_PTE>(PXE_BASE + Offset);
}

// Return an address of PPE
EXTERN_C
PHARDWARE_PTE MiAddressToPpe(
    __in void* Address)
{
    ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PPI_SHIFT - 3);
    Offset &= (0x3FFFF << 3);
    return reinterpret_cast<PHARDWARE_PTE>(PPE_BASE + Offset);
}

// Return an address of PDE
EXTERN_C
PHARDWARE_PTE MiAddressToPde(
    __in void* Address)
{
    ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PDI_SHIFT - 3);
    Offset &= (0x7FFFFFF << 3);
    return reinterpret_cast<PHARDWARE_PTE>(PDE_BASE + Offset);
}

// Return an address of PTE
EXTERN_C
PHARDWARE_PTE MiAddressToPte(
    __in void* Address)
{
    ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PTI_SHIFT - 3);
    Offset &= (0xFFFFFFFFFULL << 3);
    return reinterpret_cast<PHARDWARE_PTE>(PTE_BASE + Offset);
}

// Return a number of processors
EXTERN_C
ULONG KeQueryActiveProcessorCountCompatible(
    __out_opt PKAFFINITY ActiveProcessors)
{
#if (NTDDI_VERSION >= NTDDI_VISTA)
    return KeQueryActiveProcessorCount(ActiveProcessors);
#else
    ULONG numberOfProcessors = 0;
    KAFFINITY affinity = KeQueryActiveProcessors();

    if (ActiveProcessors)
    {
        *ActiveProcessors = affinity;
    }

    for (; affinity; affinity >>= 1)
    {
        if (affinity & 1)
        {
            numberOfProcessors++;
        }
    }
    return numberOfProcessors;
#endif
}

// Execute a given callback routine on all processors in DPC_LEVEL. Returns
// STATUS_SUCCESS when all callback returned STATUS_SUCCESS as well. When
// one of callbacks returns anything but STATUS_SUCCESS, this function stops
// to call remaining callbacks and returns the value.
EXTERN_C
NTSTATUS ForEachProcessors(
    __in NTSTATUS(*CallbackRoutine)(void*),
    __in_opt void* Context)
{
    const auto numberOfProcessors =
        KeQueryActiveProcessorCountCompatible(nullptr);
    for (ULONG processorNumber = 0; processorNumber < numberOfProcessors;
        processorNumber++)
    {
        // Switch the current processor
        KeSetSystemAffinityThread(static_cast<KAFFINITY>(1 << processorNumber));
        const auto affinity = std::experimental::scope_guard(
            KeRevertToUserAffinityThread);

        const auto oldIrql = std::experimental::unique_resource(
            KeRaiseIrqlToDpcLevel(), KeLowerIrql);

        // Execute callback
        const auto status = CallbackRoutine(Context);
        if (!NT_SUCCESS(status))
        {
            return status;
        }
    }
    return STATUS_SUCCESS;
}

// Random memory version strstr()
EXTERN_C
void* MemMem(
    __in const void* SearchBase,
    __in SIZE_T SearchSize,
    __in const void* Pattern,
    __in SIZE_T PatternSize)
{
    ASSERT(SearchBase);
    ASSERT(SearchSize);
    ASSERT(Pattern);
    ASSERT(PatternSize);

    if (PatternSize > SearchSize)
    {
        return nullptr;
    }
    auto searchBase = static_cast<const char*>(SearchBase);
    for (size_t i = 0; i <= SearchSize - PatternSize; i++)
    {
        if (!memcmp(Pattern, &searchBase[i], PatternSize))
        {
            return const_cast<char*>(&searchBase[i]);
        }
    }
    return nullptr;
}

// Replaces placeholder (0xffffffffffffffff) in AsmHandler with a given
// ReturnAddress. AsmHandler does not has to be writable. Race condition between
// multiple processors should be taken care of by a programmer it exists; this
// function does not care about it.
EXTERN_C
void FixupAsmCode(
    __in ULONG_PTR ReturnAddress,
    __in ULONG_PTR AsmHandler,
    __in ULONG_PTR AsmHandlerEnd)
{
    ASSERT(AsmHandlerEnd > AsmHandler);
    SIZE_T asmHandlerSize = AsmHandlerEnd - AsmHandler;

    ULONG_PTR pattern = 0xffffffffffffffff;
    auto returnAddr = MemMem(reinterpret_cast<void*>(AsmHandler),
        asmHandlerSize, &pattern, sizeof(pattern));
    ASSERT(returnAddr);
    PatchReal(returnAddr, &ReturnAddress, sizeof(ReturnAddress));
}

// Install a hook on PatchAddress by overwriting original code with JMP code
// that transfer execution to JumpDestination without modifying any registers.
// PatchAddress does not has to be writable. Race condition between multiple
// processors should be taken care of by a programmer it exists; this function
// does not care about it.
EXTERN_C
void InstallJump(
    __in ULONG_PTR PatchAddress,
    __in ULONG_PTR JumpDestination)
{
    // Code used to overwrite PatchAddress
    UCHAR patchCode[] =
    {
        UTIL_HOOK_ENTRY_CODE,                                       // nop or int 3
        0x50,                                                       // push rax
        0x48, 0xB8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // mov rax, 0ffffffffffffffffh
        0x48, 0x87, 0x04, 0x24,                                     // xchg rax, [rsp]
        0xC3,                                                       // ret
    };
    C_ASSERT(sizeof(patchCode) == 17);

    // Replace placeholder (0xffffffffffffffff) located at offset 4 of patchCode
    // with JumpDestination
    *reinterpret_cast<ULONG_PTR*>(patchCode + 4) = JumpDestination;

    // And install patch
    PatchReal(reinterpret_cast<void*>(PatchAddress), patchCode,
        sizeof(patchCode));
}

// Overwrites PatchAddr with PatchCode with disabling write protection and
// raising IRQL in order to avoid race condition on this processor.
EXTERN_C
void PatchReal(
    __in void* PatchAddr,
    __in const void* PatchCode,
    __in SIZE_T PatchBytes)
{
    auto oldIrql = std::experimental::unique_resource(
        KeRaiseIrqlToDpcLevel(), KeLowerIrql);
    Ia32DisableWriteProtect();
    auto protection = std::experimental::scope_guard(Ia32EnableWriteProtect);
    memcpy(PatchAddr, PatchCode, PatchBytes);
    __writecr3(__readcr3());
}

// Returns true if the address is canonical address
EXTERN_C
bool IsCanonicalAddress(
    __in ULONG_PTR Address)
{
    return (
        (Address & 0xFFFF000000000000) == 0xFFFF000000000000 ||
        (Address & 0xFFFF000000000000) == 0);
}


text:
local floor = math.floor

--The API
local AudioUtils = {}

-- C# D#   F# G# A#
--C  D  E F  G  A  B

--Convert from waveform id to waveform name, and vice versa.
AudioUtils.Waves = {
  "Square", "Pulse", "Sawtooth", "Triangle", "Noise";
  [-1] = "Silent", [0] = "Sine"
}

for i=-1,5 do
  AudioUtils.Waves[AudioUtils.Waves[i]] = i
end

--Convert from note letter to note number and vice versa.
AudioUtils.Notes = {
 "C","C#","D","D#","E","F","F#","G","G#","A","A#","B"
}

for i=1,12 do
  AudioUtils.Notes[AudioUtils.Notes[i]] = i
end

--Convert from note+oct to frequency.
--note can be the note name or note number (1,12), oct can be from 0 to 7.
local noteFreqConst, noteFreqCache = 2^(1/12), {}
function AudioUtils.noteFrequency(note,oct)

  if type(note) == "string" then
    note = AudioUtils.Notes[note]
  end

  note,oct = floor(note), floor(oct)

  if noteFreqCache[note.."x"..oct] then return noteFreqCache[note.."x"..oct] end

  local notepos = (oct)*12+note
  local notedist = notepos - 58
  local notehz = 440 --A4

  if notedist < 0 then
    for i=1,-notedist do
      notehz = notehz/noteFreqConst
    end
  elseif notedist > 0 then
    for i=1,notedist do
      notehz = notehz*noteFreqConst
    end
  end

  noteFreqCache[note.."x"..oct] = notehz

  return notehz

end

function AudioUtils.frequencyNote(freq)

  for oct=0,7 do
    for note=1,12 do
      local nfreq = AudioUtils.noteFrequency(note,oct)

      if nfreq >= freq then
        return note, oct
      end
    end
  end

  return 12, 7

end

--Make the AudioUtils a global
_G["AudioUtils"] = AudioUtils


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace GUI_OVFTOOL
{
    public partial class OVF_Conv : Form
    {
        //Main_Form main = Main_Form.getInstance();
        public String tex,s,filename;
        private string[] cmball = new[] { "ovf","ova", "vmx" };
        private string[] cmbovf = new[] { "ova", "vmx" };
        private string[] cmbova = new[] { "ovf", "vmx" };
        private string[] cmbvmx = new[] { "ovf", "ova" };
        public OVF_Conv()
        {
            InitializeComponent();
        }
        //private static OVF_Conv instance;
        ////Function creates only one instance of the form
        //public static OVF_Conv getInstance()
        //{
        //    if (instance == null || instance.IsDisposed)
        //        instance = new OVF_Conv();
        //    else
        //        instance.BringToFront();
        //    return instance;
        //}
        private void Form2_Load(object sender, EventArgs e)
        {
            this.AcceptButton = btnrun;
            txt_f_n1.GotFocus += new EventHandler(this.TextGotFocus);
            txt_f_n1.LostFocus += new EventHandler(this.TextLostFocus);

        }

        private void btnsrc_Click(object sender, EventArgs e)
        {

            openFileDialog1.ShowDialog();
            txtsrc.Text = openFileDialog1.FileName;
        }

        private void btntrg_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            txttrg.Text = folderBrowserDialog1.SelectedPath;
        }

        private void btnrun_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            label7.Text = "0%";
            btnlog.Visible = false;
            String eul_chk = "", log = "";
            if (txtsrc.Text == null || txtsrc.Text == "Drag and drop source file" || txtsrc.Text == "source location")
            {
                MessageBox.Show("Please browse or drag and drop source file");
            }
            else if (txttrg.Text == "" || txttrg.Text == "Target")
            {
                MessageBox.Show("Please browse the target location");
            }
            else if (txt_f_n1.Text == "" || txt_f_n1.Text == "Enter File Name")
            {
                MessageBox.Show("Please enter the save as file name");
            }
            else if (cmbtrg.Text == "Select extension" || cmbtrg.Text == "")
            {
                MessageBox.Show("Please select the extension for conversion");
            }
            else if (chklog.Checked && cmblog.Text == "")
            {
                MessageBox.Show("Please select the logging level");
            }
            else
            {
                UseWaitCursor = true;

                if (chklog.Checked)//Checks whether the logs option is enabled
                {
                    log = @"--X:logFile="+filename+" --X:logLevel="+cmblog.Text+" ";
                    s = log+txtsrc.Text.Trim() + " " + txttrg.Text.Trim() + "\\" + txt_f_n1.Text.Trim() + "." + cmbtrg.Text.Trim();
                    //String s=@"\"vcloud\:\/\/gayatrib@re.com:Cho@p10v1-vcd.vchs.vmware.com/cloud/org/m211057782-9439/?vdc=m211057782&org=M211057782-9439&vappTemplate=test&catalog=SG_Catalog" \"C:\Users\gayatrib\Desktop\exp\"";
                }
                else
                {
                    s = txtsrc.Text.Trim() + " " + txttrg.Text.Trim() + "\\" + txt_f_n1.Text.Trim() + "." + cmbtrg.Text.Trim();
                    //String s=@"\"vcloud\:\/\/gayatrib@re.com:Cho@p10v1-vcd.vchs.vmware.com/cloud/org/m211057782-9439/?vdc=m211057782&org=M211057782-9439&vappTemplate=test&catalog=SG_Catalog" \"C:\Users\gayatrib\Desktop\exp\"";
                }
                txtsynx.Text = s;
                OvfClass ovf = new OvfClass();
                eul_chk = ovf.eula_chk("--eula \"" + txtsrc.Text + "\"");//checking whether the manifest file has enduser licence agreement
                if (eul_chk != null)
                {
                    if (log == "")
                    {
                        s =  " --acceptAllEulas " + txtsrc.Text.Trim() + " " + txttrg.Text.Trim() + "\\" + txt_f_n1.Text.Trim() + "." + cmbtrg.Text.Trim();
                    }
                    else
                    {
                        s = log+" --acceptAllEulas " + txtsrc.Text.Trim() + " " + txttrg.Text.Trim() + "\\" + txt_f_n1.Text.Trim() + "." + cmbtrg.Text.Trim();
                    }
                    EULA f16 = new EULA(eul_chk, s,s, log);//Opens a new form to show the end user's licence agreement
                    f16.Show();
                }
                else
                {
                    txtres.Text = "Please Wait";
                    if (!backgroundWorker1.IsBusy)
                    {
                        // This method will start the execution asynchronously in the background
                        backgroundWorker1.RunWorkerAsync();
                    }
                }
            }
        }
        //Function used to fill the details in textbox when it gets focus
        public void TextGotFocus(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            if (tb.Text == "Enter File Name")
            {
                tb.Text = "";
                tb.ForeColor = Color.Black;
            }
        }
        //Function used to show the the text in the textbox when it loses focus
        public void TextLostFocus(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            if (tb.Text == "")
            {
                tb.Text = "Enter File Name";
                tb.ForeColor = Color.LightGray;
            }
        }
        //Function calls the Compute
        public void funcall()
        {
            UseWaitCursor = true;tex = "";
            String p = txtsynx.Text;
            //OvfClass ovf = new OvfClass();
            tex= compute(p,this);
            if (tex == "Extr")
            {
                //MessageBox.Show("allow extra config");
                s = "--allowAllExtraConfig " + s;
                tex = compute(s, this);
            }
        }

        private void btnsrc_MouseHover(object sender, EventArgs e)
        {
            toolTip1.SetToolTip(btnsrc, "Browse source location for OVF,OVA or VMX file");
        }

        private void btntrg_MouseHover(object sender, EventArgs e)
        {
            toolTip1.SetToolTip(btntrg,"Browse target folder to save the file");
        }

        private void cmbtrg_MouseHover(object sender, EventArgs e)
        {
            toolTip1.SetToolTip(cmbtrg,"Select the conversion extension");
        }
        //function checks the value of backgroundworker Reportprogress
        public void progress(int n, String res)
        {
            tex=res;
            if (n <= 95)
            {
                backgroundWorker1.ReportProgress(n);
            }
            //main.dum2.upload1(n, res);
            //Thread.Sleep(5000);
            return;
        }
        //BackgroundWorker class for executing a time-consuming operation asynchronously
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            UseWaitCursor = true;
            if (backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                funcall();
                //backgroundWorker1.ReportProgress(i);
            }
        }
        //ProgressChanged event to report the progress of an asynchronous operation
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label7.Text = e.ProgressPercentage.ToString() + "%";
            txtres.Text = tex;
            //if (label7.Text == "10%")
            //{
            //    main.dum2.Show();
            //    main.dum2.BringToFront();
            //    this.Hide();
            //}
        }
        //RunWorkerCompleted event to handle the result of an asynchronous operation.
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            txtres.Text = tex;
            progressBar1.Value = 100;
            label7.Text = "100%";
            UseWaitCursor = false;
            if (chklog.Checked)
            {
                btnlog.Visible = true;
            }
        }
        //Opens the log file
        private void btnlog_Click(object sender, EventArgs e)
        {
            try
            {
                System.IO.File.AppendAllText(filename, Environment.NewLine + "--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + Environment.NewLine);
                System.Diagnostics.Process.Start(filename);
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }
        }
        //Setting the path for loging files to be placed
        private void chklog_CheckedChanged(object sender, EventArgs e)
        {
            if(chklog.Checked)
            {
                if (!(Directory.Exists(@"C:\ProgramData\VMware")))
                {
                    Directory.CreateDirectory(@"C:\ProgramData\VMware");
                }
                filename = @"C:\ProgramData\VMware\upload.log";
                cmblog.Visible = true;
            }
            else
            {
                cmblog.Visible = false;
            }
        }
        //DrapDrop functionality implemented for source files
        private void txtsrc_DragDrop(object sender, DragEventArgs e)
        {
            Drag dr = new Drag();
            String msg = dr.drop(e);
            String chk = msg.Substring(msg.Length - 4, 4);
            if (chk==".ovf"||chk==".ova"||chk==".vmx")
                txtsrc.Text = msg;
            else
                MessageBox.Show("Please drag and drop only files with extension OVF/OVA/VMX");
        }

        private void txtsrc_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }
        //Function checks for the extension in the source file
        private void txtsrc_TextChanged(object sender, EventArgs e)
        {
            String msg = "";
            if (txtsrc.Text!="" && txtsrc.Text.Length>=3)
            {
                msg = txtsrc.Text.Substring(txtsrc.Text.Length - 3, 3);
            }
            if (msg == "ovf" || msg == "ova" || msg == "vmx")
            {
                switch (msg)
                {
                    case "ovf":
                        cmbtrg.Items.Clear();
                        cmbtrg.Items.AddRange(cmbovf);
                        break;
                    case "ova":
                        cmbtrg.Items.Clear();
                        cmbtrg.Items.AddRange(cmbova);
                        break;
                    case "vmx":
                        cmbtrg.Items.Clear();
                        cmbtrg.Items.AddRange(cmbvmx);
                        break;
                    default:
                        cmbtrg.Items.Clear();
                        cmbtrg.Items.AddRange(cmball);
                        break;
                }
            }
            else
            {
                MessageBox.Show("Please browse or drag and drop source file");
            }
        }

        private void OVF_Conv_KeyUp(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter)//When Enter is clicked the the application runs
            {
                this.AcceptButton = btnrun;
            }
        }
        //Function used to connect to the ovftool, pass arguments and get the output
        public String compute(String s, Object frm)
        {
            String tex = "", res = "";
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = @"C:\Program Files\VMware\VMware OVF Tool\ovftool.exe";
                psi.Arguments = s;
                psi.UseShellExecute = false;
                psi.RedirectStandardOutput = true;
                psi.CreateNoWindow = true;
                var proc = Process.Start(psi);
                String te = "", tf = "";
                te = proc.StandardOutput.ReadLine();//Reading the output of the ovf tool line by line
                tex += te + Environment.NewLine;
                progress(5, tex);
                for (int i = 0; i < 5; i++)
                {
                    if (tf == "Username")//checking for wrong username and password
                    {
                        res = "Please enter proper username and password \n" + tex + "erro";

                        return res;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                    if (te == null)
                    {
                        break;
                    }
                    if (te == "")
                    {
                        continue;
                    }
                    else
                    {
                        if (te.Length >= 8)
                        {
                            tf = te.Substring(0, 8);
                        }
                    }
                    if (te.Contains("ExtraConfig options exists in source"))//checking for ExtraConfig option in manifest file
                    {
                        return "Extr";
                    }
                }
                te = proc.StandardOutput.ReadLine();
                tex += te + Environment.NewLine;
                progress(10, tex);
                for (int i = 0; i < 10; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(20, tex);
                for (int i = 0; i < 10; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(30, tex);
                for (int i = 0; i < 10; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(40, tex);
                for (int i = 0; i < 10; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(50, tex);
                for (int i = 0; i < 10; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(60, tex);
                for (int i = 0; i < 10; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(70, tex);
                for (int i = 0; i < 10; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(80, tex);
                for (int i = 0; i < 10; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(90, tex);
                for (int i = 0; i < 30; i++)
                {
                    if (te == null)
                    {
                        break;
                    }
                    te = proc.StandardOutput.ReadLine();
                    tex += te + Environment.NewLine;
                }
                progress(100, tex);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return tex;
        }
    }
}


text:
package org.redisson.api;

/**
 *
 * @author Nikita Koksharov
 *
 */
public enum GeoOrder {
    ASC, DESC
}


text:
import React from 'react';
import { defaultArgTypes as argTypes } from '@looker/storybook';
import { Code } from './Code';
export default {
  argTypes,
  component: Code,
  title: 'Code'
};

const Template = args => React.createElement(Code, args);

export const Default = Template.bind({});
Default.args = {
  children: 'This is a simple example of some code'
};
//# sourceMappingURL=Code.stories.js.map


text:
#ifndef __CONSUMEMESSAGECONCURRENTLYSERVICE_H__
#define __CONSUMEMESSAGECONCURRENTLYSERVICE_H__

#include "ConsumeMessageService.h"

#include <list>
#include <string>
#include "MessageQueueLock.h"
#include "ConsumerStatManage.h"
#include "MessageExt.h"
#include "MessageListener.h"
#include "ProcessQueue.h"
#include "ThreadPool.h"
#include "TimerThread.h"

namespace rmq
{
  class DefaultMQPushConsumerImpl;
  class DefaultMQPushConsumer;
  class MessageListenerConcurrently;
  class ConsumeMessageConcurrentlyService;

  class ConsumeConcurrentlyRequest: public kpr::ThreadPoolWork
  {
  public:
      ConsumeConcurrentlyRequest(std::list<MessageExt*>& msgs,
                                 ProcessQueue* pProcessQueue,
                                 const MessageQueue& messageQueue,
                                 ConsumeMessageConcurrentlyService* pService);
      ~ConsumeConcurrentlyRequest();
      virtual void Do();

      std::list<MessageExt*>& getMsgs()
      {
          return m_msgs;
      }

      ProcessQueue* getProcessQueue()
      {
          return m_pProcessQueue;
      }

      MessageQueue getMessageQueue()
      {
          return m_messageQueue;
      }

  private:
      void resetRetryTopic(std::list<MessageExt*>& msgs);

  private:
      std::list<MessageExt*> m_msgs;
      ProcessQueue* m_pProcessQueue;
      MessageQueue m_messageQueue;
      ConsumeMessageConcurrentlyService* m_pService;
  };

  class ConsumeMessageConcurrentlyService : public ConsumeMessageService
  {
  public:
      ConsumeMessageConcurrentlyService(DefaultMQPushConsumerImpl* pDefaultMQPushConsumerImpl,
                                        MessageListenerConcurrently* pMessageListener);
	  ~ConsumeMessageConcurrentlyService();

      void start();
      void shutdown();

	  void cleanExpireMsg();
      ConsumerStat& getConsumerStat();

      bool sendMessageBack(MessageExt& msg, ConsumeConcurrentlyContext& context);
      void processConsumeResult(ConsumeConcurrentlyStatus status,
                                ConsumeConcurrentlyContext& context,
                                ConsumeConcurrentlyRequest& consumeRequest);

      void submitConsumeRequestLater(std::list<MessageExt*>& pMsgs,
                                     ProcessQueue* pProcessQueue,
                                     const MessageQueue& messageQueue);

      void submitConsumeRequest(std::list<MessageExt*>& pMsgs,
                                ProcessQueue* pProcessQueue,
                                const MessageQueue& messageQueue,
                                bool dispathToConsume);

      void updateCorePoolSize(int corePoolSize);

      std::string& getConsumerGroup();
      MessageListenerConcurrently* getMessageListener();
      DefaultMQPushConsumerImpl* getDefaultMQPushConsumerImpl();

  private:
      DefaultMQPushConsumerImpl* m_pDefaultMQPushConsumerImpl;
      DefaultMQPushConsumer* m_pDefaultMQPushConsumer;
      MessageListenerConcurrently* m_pMessageListener;
      std::string m_consumerGroup;
      kpr::ThreadPoolPtr m_pConsumeExecutor;
      kpr::TimerThreadPtr m_pScheduledExecutorService;
      kpr::TimerThreadPtr m_pCleanExpireMsgExecutors;
      kpr::TimerHandler* m_pCleanExpireMsgTask;
  };
}

#endif


text:
package reportingDSL
import scala.sys.process._

trait Execute {

  type Command = String
  def execute(command: Seq[String], cwd: String): Seq[String] = {
    sys.process.Process(command, new java.io.File(cwd)).!!.split("\n")
  }

  def executeInDirectory(command: Command, cwd: String): Seq[String] = {
    println(command, cwd)
    execute(command.split(" "), cwd)
  }
}


text:
package com.workshop.rest.level3;

import org.springframework.hateoas.ResourceSupport;

public class User extends ResourceSupport {

    private Long userid;
    private String name;

    User() { }

    public User(String name) {
        this.name = name;
    }

    public Long getUserid() {
        return userid;
    }

    public void setUserid(Long userid) {
        this.userid = userid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
ROSE_NAMESPACE_START

    BXDFSample::BXDFSample() {}

    BXDF::BXDF(BXDFType type) : type(type) {}

    BXDF::~BXDF() {}

    Spectrum BXDF::SampleF(const Vector3f &wo, const Vector2f &sample, BXDFSample *const bsdf_sample) const {
        // Cosine sample the BXDF
        bsdf_sample->wi = CosineHemisphereSample(sample);
        // Check if we need to swap the direction sampled
        if (wo.y() < 0.f) { bsdf_sample->wi.y() *= -1.f; }
        bsdf_sample->pdf = Pdf(wo, bsdf_sample->wi);
        bsdf_sample->sampled_type = type;

        return F(wo, bsdf_sample->wi);
    }

    float BXDF::Pdf(const Vector3f &wo, const Vector3f &wi) const {
        // Cosine pdf
        return SameHemisphere(wo, wi) ? Frame::AbsCosTheta(wi) * (float) M_1_PI : 0.f;
    }

    BSDF::BSDF(const SurfaceInteraction &interaction, float eta)
            : geom_n(interaction.geom_frame.N()), shading_frame(interaction.sh_frame), eta(eta) {}

    BSDF::~BSDF() {
        // Free BXDFs memory
        for (uint32_t i = 0; i < n_bxdfs; i++) {
            delete bxdfs[i];
        }
    }

    void BSDF::Add(BXDF *const b) {
        if (n_bxdfs < MAX_BSDFS) {
            bxdfs[n_bxdfs++] = b;
        }
    }

    uint32_t BSDF::NumComponents(BXDFType type) const {
        uint32_t n = 0;
        for (uint32_t i = 0; i < n_bxdfs; i++) {
            if (bxdfs[i]->MatchesFlags(type)) { n++; }
        }

        return n;
    }

    Spectrum BSDF::F(const Vector3f &wo_world, const Vector3f &wi_world, BXDFType type) const {
        Vector3f wo = shading_frame.ToLocal(wo_world);
        Vector3f wi = shading_frame.ToLocal(wi_world);
        if (wo.y() == 0.f) { return Spectrum(0.f); }
        // Check if we have reflection
        bool reflect = DotProduct(wo_world, geom_n) * DotProduct(wi_world, geom_n) > 0.f;
        Spectrum f(0.f);
        for (uint32_t i = 0; i < n_bxdfs; ++i) {
            if (bxdfs[i]->MatchesFlags(type) &&
                ((reflect && (bxdfs[i]->type & REFLECTION)) ||
                 (!reflect && (bxdfs[i]->type & TRANSMISSION)))) {
                f += bxdfs[i]->F(wo, wi);
            }
        }

        return f;
    }

    Spectrum BSDF::SampleF(const Vector3f &wo_world, const Vector2f &sample, BXDFSample *const bsdf_sample,
                           BXDFType type) const {
        // Choose which BXDF to sample
        uint32_t matching_comps = NumComponents(type);
        if (matching_comps == 0) {
            bsdf_sample->pdf = 0.f;
            bsdf_sample->sampled_type = BXDFType(0);
            return Spectrum(0.f);
        }
        uint32_t comp = std::min((uint32_t) std::floor(sample.x() * matching_comps), matching_comps - 1);

        // Get pointer to choosen BXDF
        BXDF *bxdf = nullptr;
        uint32_t count = comp;
        for (uint32_t i = 0; i < n_bxdfs; i++) {
            if (bxdfs[i]->MatchesFlags(type) && count-- == 0) {
                bxdf = bxdfs[i];
                break;
            }
        }

        assert(bxdf != nullptr);

        // Remap BXDF sample to [0,1)
        Vector2f sample_remapped(std::min(sample.x() * matching_comps - comp, 1.f - EPS), sample.y());

        // Sample chosen BXDF
        Vector3f wi;
        Vector3f wo = shading_frame.ToLocal(wo_world);
        if (wo.y() == 0.f) { return Spectrum(0.f); }
        bsdf_sample->pdf = 0.f;
        // Evaluate BXDF
        Spectrum f = bxdf->SampleF(wo, sample_remapped, bsdf_sample);
        if (bsdf_sample->pdf == 0.f) {
            bsdf_sample->sampled_type = BXDFType(0);
            return Spectrum(0.f);
        }
        // Store local wi
        wi = bsdf_sample->wi;
        // Transform wi to world
        bsdf_sample->wi = shading_frame.ToWorld(wi);

        // Compute overall PDF with all matching BXDFs
        if (!(bxdf->type & SPECULAR) && matching_comps > 1) {
            for (uint32_t i = 0; i < n_bxdfs; i++) {
                if (bxdfs[i] != bxdf && bxdfs[i]->MatchesFlags(type)) {
                    bsdf_sample->pdf += bxdfs[i]->Pdf(wo, wi);
                }
            }
        }
        if (matching_comps > 1) { bsdf_sample->pdf /= (float) matching_comps; }

        // Compute value of BSDF for sampled direction
        if (!(bxdf->type & SPECULAR) && matching_comps > 1) {
            bool reflect = DotProduct(bsdf_sample->wi, geom_n) * DotProduct(wo_world, geom_n) > 0.f;
            f = Spectrum(0.f);
            for (uint32_t i = 0; i < n_bxdfs; ++i) {
                if (bxdfs[i]->MatchesFlags(type) &&
                    ((reflect && (bxdfs[i]->type & REFLECTION)) ||
                     (!reflect && (bxdfs[i]->type & TRANSMISSION)))) {
                    f += bxdfs[i]->F(wo, wi);
                }
            }
        }

        return f;
    }

    float BSDF::Pdf(const Vector3f &wo_world, const Vector3f &wi_world, BXDFType type) const {
        if (n_bxdfs == 0) { return 0.f; }
        Vector3f wo = shading_frame.ToLocal(wo_world), wi = shading_frame.ToLocal(wi_world);
        if (wo.y() == 0.f) { return 0.f; }
        float pdf = 0.f;
        uint32_t matching_comps = 0;
        for (uint32_t i = 0; i < n_bxdfs; i++) {
            if (bxdfs[i]->MatchesFlags(type)) {
                ++matching_comps;
                pdf += bxdfs[i]->Pdf(wo, wi);
            }
        }
        float final_pdf = matching_comps > 0 ? pdf / (float) matching_comps : 0.f;

        return final_pdf;
    }

    SpecularReflection::SpecularReflection(const Spectrum &r, const FresnelInterface *const f)
            : BXDF(BXDFType(REFLECTION | SPECULAR)), R(r), fresnel(f) {}

    Spectrum SpecularReflection::F(const Vector3f &, const Vector3f &) const {
        return Spectrum(0.f);
    }

    Spectrum SpecularReflection::SampleF(const Vector3f &wo, const Vector2f &,
                                         BXDFSample *const bsdf_sample) const {
        // Compute perfect specular direction
        bsdf_sample->wi = Vector3f(-wo.x(), wo.y(), -wo.z());
        bsdf_sample->pdf = 1.f;
        bsdf_sample->sampled_type = type;

        return fresnel->Evaluate(Frame::CosTheta(bsdf_sample->wi)) * R / Frame::AbsCosTheta(bsdf_sample->wi);
    }

    SpecularTransmission::SpecularTransmission(const Spectrum &t, float ea, float eb)
            : BXDF(BXDFType(TRANSMISSION | SPECULAR)), T(t), eta_a(ea), eta_b(eb), fresnel(eta_a, eta_b) {}

    Spectrum SpecularTransmission::F(const Vector3f &, const Vector3f &) const {
        return Spectrum(0.f);
    }

    Spectrum SpecularTransmission::SampleF(const Vector3f &wo, const Vector2f &,
                                           BXDFSample *const bsdf_sample) const {
        // Figure out which eta is incident and which is transmitted
        bool entering = Frame::CosTheta(wo) > 0.f;
        float eta_i = entering ? eta_a : eta_b;
        float eta_t = entering ? eta_b : eta_a;
        // Compute ray direction
        if (!Refract(wo, FaceForward(Vector3f(0.f, 1.f, 0.f), wo), eta_i / eta_t, &(bsdf_sample->wi))) {
            return Spectrum(0.f);
        }
        bsdf_sample->pdf = 1.f;
        bsdf_sample->sampled_type = type;
        Spectrum ft = T * (Spectrum(1.f) - fresnel.Evaluate(Frame::CosTheta(bsdf_sample->wi)));
        // Account for non-symmetry of transmission
        ft *= (eta_i * eta_i) / (eta_t * eta_t);

        return ft / Frame::AbsCosTheta(bsdf_sample->wi);
    }

    FresnelSpecular::FresnelSpecular(const Spectrum &r, const Spectrum &t, float ea, float eb)
            : BXDF(BXDFType(REFLECTION | TRANSMISSION | SPECULAR)), R(r), T(t), eta_a(ea), eta_b(eb),
              fresnel(eta_a, eta_b) {}

    Spectrum FresnelSpecular::F(const Vector3f &, const Vector3f &) const {
        return Spectrum(0.f);
    }

    Spectrum FresnelSpecular::SampleF(const Vector3f &wo, const Vector2f &sample, BXDFSample *const bsdf_sample) const {
        float F = FrDielectric(Frame::CosTheta(wo), eta_a, eta_b);
        if (sample.x() < F) {
            // Compute perfect specular direction
            bsdf_sample->wi = Vector3f(-wo.x(), wo.y(), -wo.z());
            bsdf_sample->pdf = F;
            bsdf_sample->sampled_type = BXDFType(REFLECTION | SPECULAR);

            return F * R / Frame::AbsCosTheta(bsdf_sample->wi);
        } else {
            // Figure out which eta is incident and which is transmitted
            bool entering = Frame::CosTheta(wo) > 0.f;
            float eta_i = entering ? eta_a : eta_b;
            float eta_t = entering ? eta_b : eta_a;
            // Compute ray direction
            if (!Refract(wo, FaceForward(Vector3f(0.f, 1.f, 0.f), wo), eta_i / eta_t, &(bsdf_sample->wi))) {
                return Spectrum(0.f);
            }
            bsdf_sample->pdf = 1.f - F;
            bsdf_sample->sampled_type = BXDFType(TRANSMISSION | SPECULAR);
            Spectrum ft = T * (1.f - F);
            // Account for non-symmetry of transmission
            ft *= (eta_i * eta_i) / (eta_t * eta_t);

            return ft / Frame::AbsCosTheta(bsdf_sample->wi);
        }
    }

    LambertianReflection::LambertianReflection(const Spectrum &r)
            : BXDF(BXDFType(REFLECTION | DIFFUSE)), R(r) {}

    Spectrum LambertianReflection::F(const Vector3f &, const Vector3f &) const {
        return R * M_1_PI;
    }

    OrenNayar::OrenNayar(const Spectrum &r, float sigma)
            : BXDF(BXDFType(REFLECTION | DIFFUSE)), R(r) {
        sigma = DegToRad(sigma);
        float sigma2 = sigma * sigma;
        A = 1.f - (sigma2 / (2.f * (sigma2 + 0.33f)));
        B = 0.45f * sigma2 / (sigma2 + 0.09f);
    }

    Spectrum OrenNayar::F(const Vector3f &wo, const Vector3f &wi) const {
        float sin_theta_i = Frame::SinTheta(wi);
        float sin_theta_o = Frame::SinTheta(wo);
        float max_cos = 0.f;
        if (sin_theta_i > 1e-4f && sin_theta_o > 1e-4f) {
            float sin_phi_i = Frame::SinPhi(wi);
            float cos_phi_i = Frame::CosPhi(wi);
            float sin_phi_o = Frame::SinPhi(wo);
            float cos_phi_o = Frame::CosPhi(wo);
            float d_cos = cos_phi_i * cos_phi_o + sin_phi_i * sin_phi_o;
            max_cos = std::max(0.f, d_cos);
        }

        // Compute sine and tangent terms of Oren Nayar
        float sin_alpha, tan_beta;
        if (Frame::AbsCosTheta(wi) > Frame::AbsCosTheta(wo)) {
            sin_alpha = sin_theta_o;
            tan_beta = sin_theta_i / Frame::AbsCosTheta(wi);
        } else {
            sin_alpha = sin_theta_i;
            tan_beta = sin_theta_o / Frame::AbsCosTheta(wo);
        }

        return R * M_1_PI * (A + B * max_cos * sin_alpha * tan_beta);
    }

    MicrofacetReflection::MicrofacetReflection(const Spectrum &r,
                                               const std::shared_ptr<const MicrofacetDistributionInterface> &m_d,
                                               const FresnelInterface *const f)
            : BXDF(BXDFType(REFLECTION | GLOSSY)), R(r), distribution(m_d), fresnel(f) {}

    Spectrum MicrofacetReflection::F(const Vector3f &wo, const Vector3f &wi) const {
        float cos_theta_o = Frame::AbsCosTheta(wo);
        float cos_theta_i = Frame::AbsCosTheta(wi);
        Vector3f wh = wi + wo;
        // Handle degenerate case
        if (cos_theta_i == 0.f || cos_theta_o == 0.f) { return Spectrum(0.f); }
        if (wh.x() == 0.f && wh.y() == 0.f && wh.z() == 0.f) { return Spectrum(0.f); }
        wh = Normalize(wh);
        Spectrum fr = fresnel->Evaluate(DotProduct(wi, wh));

        return R * distribution->D(wh) * distribution->G(wo, wi) * fr / (4.f * cos_theta_i * cos_theta_o);
    }

    Spectrum MicrofacetReflection::SampleF(const Vector3f &wo, const Vector2f &sample,
                                           BXDFSample *const bsdf_sample) const {
        // Sample microfacet orientation wh and reflected direction wi
        if (wo.y() == 0.f) { return Spectrum(0.f); }
        Vector3f wh = distribution->SampleWh(wo, sample);
        bsdf_sample->wi = Reflect(wo, wh);
        if (!SameHemisphere(wo, bsdf_sample->wi)) { return Spectrum(0.f); }

        // Compute pdf of wi for reflection
        bsdf_sample->pdf = distribution->Pdf(wo, wh) / (4.f * DotProduct(wo, wh));
        bsdf_sample->sampled_type = type;

        return F(wo, bsdf_sample->wi);
    }

    float MicrofacetReflection::Pdf(const Vector3f &wo, const Vector3f &wi) const {
        if (!SameHemisphere(wo, wi)) { return 0.f; }
        Vector3f wh = Normalize(wo + wi);

        return distribution->Pdf(wo, wh) / (4.f * DotProduct(wo, wh));
    }

    MicrofacetTransmission::MicrofacetTransmission(const Spectrum &t,
                                                   const std::shared_ptr<const MicrofacetDistributionInterface> &m_d,
                                                   float ea, float eb)
            : BXDF(BXDFType(TRANSMISSION | GLOSSY)), T(t), distribution(m_d), eta_a(ea), eta_b(eb),
              fresnel(eta_a, eta_b) {}

    Spectrum MicrofacetTransmission::F(const Vector3f &wo, const Vector3f &wi) const {
        if (SameHemisphere(wo, wi)) { return Spectrum(0.f); }

        float cos_theta_o = Frame::CosTheta(wo);
        float cos_theta_i = Frame::CosTheta(wi);
        if (cos_theta_i == 0.f || cos_theta_o == 0.f) { return Spectrum(0.f); }

        // Compute wh from wo and wi for microfacet distribution
        float eta = Frame::CosTheta(wo) > 0.f ? (eta_b / eta_a) : (eta_a / eta_b);
        Vector3f wh = Normalize(wo + wi * eta);
        if (wh.z() < 0.f) { wh = -wh; }

        Spectrum fr = fresnel.Evaluate(DotProduct(wo, wh));

        float sqrt_denom = DotProduct(wo, wh) + eta * DotProduct(wi, wh);
        float factor = 1.f / eta;

        return (Spectrum(1.f) - fr) * T *
               std::abs(distribution->D(wh) * distribution->G(wo, wi) * eta * eta *
                        AbsDotProduct(wi, wh) * AbsDotProduct(wo, wh) * factor * factor /
                        (cos_theta_i * cos_theta_o * sqrt_denom * sqrt_denom));
    }

    Spectrum MicrofacetTransmission::SampleF(const Vector3f &wo, const Vector2f &sample,
                                             BXDFSample *const bsdf_sample) const {
        if (wo.y() == 0.f) { return Spectrum(0.f); }
        Vector3f wh = distribution->SampleWh(wo, sample);
        float eta = Frame::CosTheta(wo) > 0.f ? (eta_a / eta_b) : (eta_b / eta_a);

        if (!Refract(wo, wh, eta, &(bsdf_sample->wi))) { return Spectrum(0.f); }
        bsdf_sample->pdf = Pdf(wo, bsdf_sample->wi);
        bsdf_sample->sampled_type = type;

        return F(wo, bsdf_sample->wi);
    }

    float MicrofacetTransmission::Pdf(const Vector3f &wo, const Vector3f &wi) const {
        if (SameHemisphere(wo, wi)) { return 0.f; }
        // Compute wh from wo and wi for microfacet distribution
        float eta = Frame::CosTheta(wo) > 0.f ? (eta_b / eta_a) : (eta_a / eta_b);
        Vector3f wh = Normalize(wo + wi * eta);

        // Compute change of variables for microfacet transmission
        float sqrt_denom = DotProduct(wo, wh) + eta * DotProduct(wi, wh);
        float dwh_dwi = std::abs((eta * eta * DotProduct(wi, wh)) / (sqrt_denom * sqrt_denom));

        return distribution->Pdf(wo, wh) * dwh_dwi;
    }

ROSE_NAMESPACE_END


text:
package com.cloudbees.util;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

import org.junit.Test;

/**
 * @author Cyrille Le Clerc
 */
public class Strings2Test {
    @Test
    public void testJoin() throws Exception {
        String[] in = {"this", "is", "a", "sentence"};
        String actual = Strings2.join(in, " ");
        String expected = "this is a sentence";
        assertThat(actual, is(expected));
    }

    @Test
    public void indent_multi_line_string() throws Exception {
        String indentation = "   ";
        String in = "line1\n" +
                "line2\n" +
                "line3";
        String actual = Strings2.indent(in, indentation);

        String expected = indentation + "line1\n" +
                indentation + "line2\n" +
                indentation + "line3";
        assertThat(actual, is(expected));
    }

    @Test
    public void indent_mono_line_string() throws Exception {
        String indentation = "   ";
        String in = "line1";
        String actual = Strings2.indent(in, indentation);

        String expected = indentation + "line1";
        assertThat(actual, is(expected));
    }

    @Test
    public void indent_blank_string() throws Exception {
        String indentation = "   ";
        String in = "";
        String actual = Strings2.indent(in, indentation);

        String expected = indentation + "";
        assertThat(actual, is(expected));
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.cloudycrew.cloudycar.createrequest.RouteSelector"
        />

    <Button
        android:layout_width="match_parent"
        android:text="@string/submit"
        android:layout_height="60dp"
        android:id="@+id/submit_route_from_map"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:gravity="center_vertical|center_horizontal"
        android:theme="@style/Button" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/map_search_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginLeft="@dimen/fab_margin"
        android:layout_marginRight="@dimen/fab_margin"
        android:tint="@color/white"
        app:srcCompat="@android:drawable/ic_search_category_default"
        android:layout_above="@+id/submit_route_from_map"
        android:layout_alignParentEnd="true" />
</RelativeLayout>


text:
  Avrainville est
       un village
       situé dans le département de Meurthe-et-Moselle en Lorraine. Elle totalisait 231 habitants en 2008.

À coté de Avrainville sont situées les communes de
Andilly à 4 km, 269 habitants,
Domèvre-en-Haye située à 5 km, 460 habitants,
Jaillon localisée à 2 km, 360 habitants,
Ménil-la-Tour à 5 km, 295 habitants,
Bouvron à 5 km, 231 habitants,
Tremblecourt localisée à 3 km, 185 habitants,
 entre autres. De plus, Avrainville est située à seulement 20 km de Nancy.

La ville compte quelques  équipements, elle propose entre autres un terrain de golf et un terrain de sport.

Le nombre de logements, à Avrainville, était réparti en 2011 en quatre appartements et 97 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de venir habiter à Avrainville, vous pourrez facilement trouver une maison à vendre.


text:
(function (window) {
  var Muuri = window.Muuri;

  QUnit.module('Grid events');

  QUnit.test('dragScroll: should be triggered when scroll occurs during drag process', function (
    assert
  ) {
    assert.expect(4);

    var done = assert.async();
    var docElem = document.documentElement;
    var body = document.body;
    var container = utils.createGridElements();
    var grid = new Muuri(container, {
      dragEnabled: true,
      dragSortInterval: 100,
      dragSortPredicate: {
        threshold: 50,
        action: 'move',
      },
    });
    var item = grid.getItems()[0];
    var calls = 0;
    var teardown = function () {
      grid.destroy();
      container.parentNode.removeChild(container);
      utils.setStyles(docElem, { height: '' });
      body.scrollTop = 0;
      done();
    };

    utils.setStyles(docElem, { height: '1000%' });

    grid.on('dragStart', function () {
      body.scrollTop = 100;
      docElem.scrollTop = 100;
    });

    grid.on('dragScroll', function (draggedItem, ev) {
      assert.strictEqual(arguments.length, 2, 'callback: should have receive two arguments');
      assert.strictEqual(draggedItem, item, 'callback: first argument should be the dragged item');
      assert.strictEqual(
        utils.isScrollEvent(ev),
        true,
        'callback: second argument should be a scroll event object'
      );
      ++calls;
    });

    utils.dragElement({
      element: item.getElement(),
      x: 0,
      y: 100,
      onFinished: function () {
        assert.strictEqual(calls, 1, 'should be called only once');
        teardown();
      },
    });
  });
})(this);


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Define: Analytically · Nicholas Tierney

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/lanyon.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700|PT+Sans:400">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/favicon-114.png">
  <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

Statistics and R Enthusiast

    Blog

          Bio

          Publications

          Resources

          About

          Archive

          CV

GitHub

      © Nicholas Tierney, 2016. All rights reserved.

            Nicholas Tierney
            Original witty remark

Define: Analytically

   20 Jun 2013
     Statistics

What does the word analytical, mean?

Wikipedia says:

"Analytic Solution"

A solution to a problem that can be written in "closed form" in terms of known functions, constants, etc.

I find that such a definition relies on the reader knowing what the words 'closed form', 'known functions' and 'constants' are.

So here's my definition:

"Analytic Solution"

A solution where everything needed to solve a particular question is presented clearly and logically, with all assumptions defined.

Waddaya reckon?

Please enable JavaScript to view the comments powered by Disqus.


text:
package elements

import (
    "github.com/go-gl/gl/v4.4-core/gl"
    "readit/render/graphics"
)

type Texture struct {
    program uint32
    vao uint32
    vbo uint32
    ebo uint32
    texture uint32
}

func CreateTexture(file string) Texture {
    // VAO
    var vao uint32
    gl.GenVertexArrays(1, &vao)
    gl.BindVertexArray(vao)

    // VBO
    var vbo uint32
    gl.GenBuffers(1, &vbo)

    vertices := []float32 {
        0.0, 1.0, 0.0, 0.0, // Top-left
        1.0, 1.0, 1.0, 0.0, // Top-right
        1.0, 0.0, 1.0, 1.0, // Bottom-right
        0.0, 0.0, 0.0, 1.0, // Bottom-left
    }

    gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
    gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*int(floatSize), gl.Ptr(vertices), gl.STATIC_DRAW)

    // EBO
    var ebo uint32
    gl.GenBuffers(1, &ebo)

    elements := []uint32 {
        0, 1, 2,
        2, 3, 0,
    }

    gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, ebo)
    gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(elements)*int(floatSize), gl.Ptr(elements), gl.STATIC_DRAW)

    // Shader parameters
    program := graphics.ProgramGui

    posAttrib := uint32(gl.GetAttribLocation(program, gl.Str("position\x00")))
    gl.EnableVertexAttribArray(posAttrib)
    gl.VertexAttribPointer(posAttrib, 2, gl.FLOAT, false, 4*int32(floatSize), gl.PtrOffset(0))

    texAttrib := uint32(gl.GetAttribLocation(program, gl.Str("texcoord\x00")))
    gl.EnableVertexAttribArray(texAttrib)
    gl.VertexAttribPointer(texAttrib, 2, gl.FLOAT, false, 4*int32(floatSize), gl.PtrOffset(2*int(floatSize)))

    texture, err := graphics.LoadImage(file)
    if err != nil {
        panic(err)
    }

    return Texture{program: program, vao: vao, vbo: vbo, ebo: ebo, texture: texture}
}

func (t *Texture) Render(x, y, width, height float32) {
    gl.UseProgram(t.program)

    transform := gl.GetUniformLocation(t.program, gl.Str("transform\x00"))
    gl.Uniform4f(transform, x, y, width, height)

    gl.BindTexture(gl.TEXTURE_2D, t.texture)
    gl.BindVertexArray(t.vao)
    gl.DrawElements(gl.TRIANGLES, 6, gl.UNSIGNED_INT, gl.PtrOffset(0))
}

func (t *Texture) Dispose()  {
    gl.DeleteTextures(1, &t.texture)
    gl.DeleteBuffers(1, &t.ebo)
    gl.DeleteBuffers(1, &t.vbo)
    gl.DeleteVertexArrays(1, &t.vao)
}


text:
                 {{ album.title }}

                 {{ album.artist }}

                 {{ album.songs.length }} songs


text:
package org.sanju.ml.deployer;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * All the utility methods that can be leveraged across different deployer implementations.
 *
 * @author Sanju Thomas
 *
 */
public class ModuleUtils {

	private static final Logger logger = LoggerFactory.getLogger(ModuleUtils.class);

	/**
	 * Load all files from a given location.
	 *
	 * @param sourceCodeLocation
	 * @return
	 * @throws IOException
	 */
	public static List<File> loadAssets(final String sourceCodeLocation) throws IOException {

		final List<File> files = new ArrayList<>();
		final File f = new File(sourceCodeLocation);
		if (f.exists() && f.isDirectory()) {
			try (Stream<Path> paths = Files.walk(Paths.get(sourceCodeLocation))) {
				paths.forEach(filePath -> {
					if (Files.isRegularFile(filePath)) {
						files.add(new File(filePath.toUri()));
					}
				});
			}
		}
		logger.info("Found {} files at {}", files.size(), sourceCodeLocation);
		return files;
	}
}


text:
Presentation slides.

## License

MIT licensed

Copyright (C) 2014 vst42


text:
layout:     post
title:      12x12
date:       2016-03-09
categories: video
---

12x12 - проект Британской высшей школы дизайна в Москве. Создатели описывают ее так:

> "12x12" — это уникальное событие с оригинальным форматом общения с аудиторией.

> Мы пригласили 12 самых интересных специалистов в области дизайна и дали каждому по 12 минут для того, чтобы они смогли поделиться самым важным — опытом!

### Ограничения

В произведениях Довлатова все слова в предложении начинаются на разные буквы.

Не возможно решить уравнение, не имея ограничений. Частное решение есть всегда. Непреодолимых ограничений нет.

-----

### Шероховатости в дизайне

Человек любит шероховатости, не любит когда все гладенько, ровненько.


text:
using System;
using System.Net;
using System.IO;
using System.Xml;
using OpenLiveWriter.Api;
using OpenLiveWriter.CoreServices;

namespace OpenLiveWriter.Extensibility.BlogClient
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public class BlogClientAttribute : Attribute
    {
        public BlogClientAttribute(string typeName, string protocolName)
        {
            _typeName = typeName;
            _protocolName = protocolName;
        }

        public string TypeName
        {
            get { return _typeName; }
        }

        /// <summary>
        /// The name of the standard protocol that this blog client
        /// adheres to. This is used to let wlwmanifest.xml provide
        /// API-specific options (i.e. Spaces has different maxRecentPosts
        /// values depending on MetaWeblog or Atom API).
        /// </summary>
        public string ProtocolName
        {
            get { return _protocolName; }
        }

        private readonly string _typeName;
        private readonly string _protocolName;
    }

    public interface IBlogClient
    {
        string ProtocolName { get; }

        IBlogClientOptions Options { get; }
        void OverrideOptions(IBlogClientOptions newClientOptions);

        bool VerifyCredentials();

        BlogInfo[] GetUsersBlogs();

        BlogPostCategory[] GetCategories(string blogId);
        BlogPostKeyword[] GetKeywords(string blogId);

        /// <summary>
        /// Returns recent posts
        /// </summary>
        /// <param name="blogId"></param>
        /// <param name="maxPosts"></param>
        /// <param name="includeCategories"></param>
        /// <param name="now">If null, then includes future posts.  If non-null, then only includes posts before the *UTC* 'now' time.</param>
        /// <returns></returns>
        BlogPost[] GetRecentPosts(string blogId, int maxPosts, bool includeCategories, DateTime? now);

        string NewPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish, out string etag, out XmlDocument remotePost);

        bool EditPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish, out string etag, out XmlDocument remotePost);

        /// <summary>
        /// Attempt to get a post with the specified id (note: may return null
        /// if the post could not be found on the remote server)
        /// </summary>
        BlogPost GetPost(string blogId, string postId);

        void DeletePost(string blogId, string postId, bool publish);

        BlogPost GetPage(string blogId, string pageId);

        PageInfo[] GetPageList(string blogId);

        BlogPost[] GetPages(string blogId, int maxPages);

        string NewPage(string blogId, BlogPost page, bool publish, out string etag, out XmlDocument remotePost);

        bool EditPage(string blogId, BlogPost page, bool publish, out string etag, out XmlDocument remotePost);

        void DeletePage(string blogId, string pageId);

        AuthorInfo[] GetAuthors(string blogId);

        bool? DoesFileNeedUpload(IFileUploadContext uploadContext);

        string DoBeforePublishUploadWork(IFileUploadContext uploadContext);

        void DoAfterPublishUploadWork(IFileUploadContext uploadContext);

        string AddCategory(string blogId, BlogPostCategory category);

        BlogPostCategory[] SuggestCategories(string blogId, string partialCategoryName);

        HttpWebResponse SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpRequestFilter filter);

        BlogInfo[] GetImageEndpoints();

        /// <summary>
        /// Returns false if credentials are sent in the clear
        /// </summary>
        bool IsSecure { get; }
    }

    public interface INewCategoryContext
    {
        void NewCategoryAdded(BlogPostCategory category);
    }

    public interface IFileUploadContext
    {
        string BlogId { get; }
        string PostId { get; }
        string PreferredFileName { get; }
        FileUploadRole Role { get; }
        Stream GetContents();
        string GetContentsLocalFilePath();
        IProperties Settings { get; }
        bool ForceDirectImageLink { get; }

        string FormatFileName(string filename);
    }

    public enum FileUploadRole { LinkedImage, InlineImage, File }

    public class PageInfo : ICloneable
    {
        public PageInfo(string id, string title, DateTime datePublished, string parentId)
        {
            _id = id;
            _title = title;
            _datePublished = datePublished;
            _parentId = parentId;
        }

        public string Id { get { return _id; } }

        public string Title { get { return _title; } }

        public DateTime DatePublished { get { return _datePublished; } }

        public string ParentId { get { return _parentId; } }

        public object Clone()
        {
            return new PageInfo(Id, Title, DatePublished, ParentId);
        }

        private string _id;
        private string _title;
        private DateTime _datePublished;
        private string _parentId;
    }

    public class AuthorInfo : ICloneable
    {
        public AuthorInfo(string id, string name)
        {
            _id = id;
            if (name != String.Empty)
                _name = name;
            else
                _name = _id;
        }

        public string Id { get { return _id; } }

        public string Name { get { return _name; } }

        public object Clone()
        {
            return new AuthorInfo(Id, Name);
        }

        private string _id;
        private string _name;

    }
}


text:
struct A {};

int main()
{
//  Test the explicit deduction guides

//  Test the implicit deduction guides
    {
//  deque (allocator &)
    std::deque deq((std::allocator<int>()));  // expected-error {{no viable constructor or deduction guide for deduction of template arguments of 'deque'}}
//  Note: The extra parens are necessary, since otherwise clang decides it is a function declaration.
//  Also, we can't use {} instead of parens, because that constructs a
//      deque<allocator<int>, allocator<allocator<int>>>
    }

}


text:
"""This holds a routine for restricting the current process memory on Windows."""
import multiprocessing
import ctypes

def set_memory_limit(memory_limit):
    """Creates a new unnamed job object and assigns the current process to it.
    The job object will have the given memory limit in bytes: the given process
    together with its descendant processes will not be allowed to exceed
    the limit. If purge_pid_on_exit is true, when the *calling* process exits
    (the calling process can be the same or different from the given process),
    the given process and all its descendant processes will be killed."""

    import os
    pid = os.getpid()
    purge_pid_on_exit = True

    # Windows API constants, used for OpenProcess and SetInformationJobObject.
    PROCESS_TERMINATE = 0x1
    PROCESS_SET_QUOTA = 0x100
    JobObjectExtendedLimitInformation = 9
    JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x100
    JOB_OBJECT_LIMIT_JOB_MEMORY = 0x200
    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000

    class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
        """Windows API structure, used as input to SetInformationJobObject."""

        class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
            _fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64),
                        ("PerJobUserTimeLimit", ctypes.c_int64),
                        ("LimitFlags", ctypes.c_uint32),
                        ("MinimumWorkingSetSize", ctypes.c_void_p),
                        ("MaximumWorkingSetSize", ctypes.c_void_p),
                        ("ActiveProcessLimit", ctypes.c_uint32),
                        ("Affinity", ctypes.c_void_p),
                        ("PriorityClass", ctypes.c_uint32),
                        ("SchedulingClass", ctypes.c_uint32)]

        class IO_COUNTERS(ctypes.Structure):
            _fields_ = [("ReadOperationCount", ctypes.c_uint64),
                        ("WriteOperationCount", ctypes.c_uint64),
                        ("OtherOperationCount", ctypes.c_uint64),
                        ("ReadTransferCount", ctypes.c_uint64),
                        ("WriteTransferCount", ctypes.c_uint64),
                        ("OtherTransferCount", ctypes.c_uint64)]

        _fields_ = [("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),
                    ("IoInfo", IO_COUNTERS),
                    ("ProcessMemoryLimit", ctypes.c_void_p),
                    ("JobMemoryLimit", ctypes.c_void_p),
                    ("PeakProcessMemoryUsed", ctypes.c_void_p),
                    ("PeakJobMemoryUsed", ctypes.c_void_p)]

    job_info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
    job_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY
    if purge_pid_on_exit:
        job_info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
    job_info.JobMemoryLimit = memory_limit

    kernel = ctypes.windll.kernel32
    job = kernel.CreateJobObjectA(None, None)
    if job == 0:
        raise RuntimeError("CreateJobObjectA failed")
    keep_job_handle = False
    try:
        if not kernel.SetInformationJobObject(
                   job,
                   JobObjectExtendedLimitInformation,
                   ctypes.POINTER(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)(job_info),
                   ctypes.sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)):
            raise RuntimeError("SetInformationJobObject failed")

        process = kernel.OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE,False, pid)
        if process == 0:
            raise RuntimeError("OpenProcess failed")
        try:
            if not kernel.AssignProcessToJobObject(job, process):
                raise RuntimeError("AssignProcessToJobObject failed")

            # If purge_pid_on_exit is true, we kill process pid and all its
            # descendants when the job handle is closed. So, we keep the handle
            # dangling, and it will be closed when *this* process terminates.
            keep_job_handle = purge_pid_on_exit
        finally:
            if not kernel.CloseHandle(process):
                raise RuntimeError("CloseHandle failed")
    finally:
        if not (keep_job_handle or kernel.CloseHandle(job)):
            raise RuntimeError("CloseHandle failed")

def allocate(bytes):
    import numpy
    try:
        result = numpy.zeros(shape=(bytes,), dtype='i1')
        print("allocation done:", bytes)
    except Exception as ex:
        print("Failed to allocate:", ex)
        raise

def runner(thunk, memory_limit, *args):
    set_memory_limit(memory_limit)
    thunk(*args)

def run_in_process_with_memory_limit(thunk, memory_limit, test_bytes):
    p = multiprocessing.Process(target=runner, args=(thunk, memory_limit, test_bytes))
    p.start()
    p.join()

def main():
    memory_limit = 1000*1000*100
    run_in_process_with_memory_limit(allocate, memory_limit=memory_limit, test_bytes=memory_limit)

if __name__ == "__main__":
    main()


text:
package gov.nih.nci.eagle.enumeration;

public enum EducationLevel {
    NONE(1, "None"),
    ELEMENTARY(2, "Elementary School"),
    LOWER_MIDDLE(3, "Lower Middle"),
    TEACHER_TRAINING(4, "Teacher Training High School"),
    TECHNICAL(5, "Technical, Industrial, Commercial H.School"),
    COLLEGE_PREP(6, "College Prep. High Schools (Classical, Science, Art)"),
    POST_HS(7, "Post H.S. Academies or Junior Colleges"),
    DEGREE(8, "Degree"),
    POSTGRAD(9, "Postgraduate"),
    OTHER(10, "Other");

    private final int value;
    private final String name;

    EducationLevel(int key, String name) {
        this.value = key;
    	this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getValue()	{
    	return value;
    }

}


text:
using UnityEngine;

public class Foo : MonoBehaviour
{
    [SerializeField] private static readonly int my{caret}Value;
}


text:
package com.orionplatform.math.linearalgebra.matrix.functional.tasks.construction;

import com.orionplatform.core.abstraction.Orion;
import com.orionplatform.data.data_structures.list.OrionList;
import com.orionplatform.data.data_structures.list.type.OrionArrayList;
import com.orionplatform.math.function.onevariable.Function1x1;
import com.orionplatform.math.geometry.vector.functional.VectorOfFunction1x1;
import com.orionplatform.math.linearalgebra.matrix.functional.MatrixOfFunction1x1;

public class ConstructIdentityMatrixOfFunction1x1Task extends Orion
{
    public static synchronized MatrixOfFunction1x1 run(int numberOfRowsAndColumns)
    {
        OrionList<VectorOfFunction1x1> elements = OrionArrayList.of(numberOfRowsAndColumns);

        for(int i = 0; i < numberOfRowsAndColumns; i++)
        {
            VectorOfFunction1x1 temp = VectorOfFunction1x1.of(numberOfRowsAndColumns);

            for(int j = 0; j < numberOfRowsAndColumns; j++)
            {
                if(i == j)
                {
                    temp.set(j, Function1x1.One);
                }
                else
                {
                    temp.set(j, Function1x1.Zero);
                }
            }

            elements.add(temp);
        }

        return MatrixOfFunction1x1.of(elements);
    }
}


text:
package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"testing"

	"github.com/golang/dep/internal/test"
)

// The TestMain function creates a dep command for testing purposes and
// deletes it after the tests have been run.
// Most of this is taken from https://github.com/golang/go/blob/master/src/cmd/go/go_test.go and reused here.
func TestMain(m *testing.M) {
	args := []string{"build", "-o", "testdep" + test.ExeSuffix}
	out, err := exec.Command("go", args...).CombinedOutput()
	if err != nil {
		fmt.Fprintf(os.Stderr, "building testdep failed: %v\n%s", err, out)
		os.Exit(2)
	}

	// Don't let these environment variables confuse the test.
	os.Unsetenv("GOPATH")
	os.Unsetenv("GIT_ALLOW_PROTOCOL")
	if home, ccacheDir := os.Getenv("HOME"), os.Getenv("CCACHE_DIR"); home != "" && ccacheDir == "" {
		// On some systems the default C compiler is ccache.
		// Setting HOME to a non-existent directory will break
		// those systems.  Set CCACHE_DIR to cope.  Issue 17668.
		os.Setenv("CCACHE_DIR", filepath.Join(home, ".ccache"))
	}
	os.Setenv("HOME", "/test-dep-home-does-not-exist")

	r := m.Run()

	os.Remove("testdep" + test.ExeSuffix)

	os.Exit(r)
}


text:
"""
Testing that functions from compat work as expected
"""

from pandas.compat import (range, zip, map, filter, lrange, lzip, lmap,
                           lfilter, builtins, iterkeys, itervalues, iteritems,
                           next)
import pandas.util.testing as tm

class TestBuiltinIterators(tm.TestCase):

    def check_result(self, actual, expected, lengths):
        for (iter_res, list_res), exp, length in zip(actual, expected,
                                                     lengths):
            self.assertNotIsInstance(iter_res, list)
            tm.assertIsInstance(list_res, list)
            iter_res = list(iter_res)
            self.assertEqual(len(list_res), length)
            self.assertEqual(len(iter_res), length)
            self.assertEqual(iter_res, exp)
            self.assertEqual(list_res, exp)

    def test_range(self):
        actual1 = range(10)
        actual2 = lrange(10)
        actual = [actual1, actual2],
        expected = list(builtins.range(10)),
        lengths = 10,

        actual1 = range(1, 10, 2)
        actual2 = lrange(1, 10, 2)
        actual += [actual1, actual2],
        lengths += 5,
        expected += list(builtins.range(1, 10, 2)),
        self.check_result(actual, expected, lengths)

    def test_map(self):
        func = lambda x, y, z: x + y + z
        lst = [builtins.range(10), builtins.range(10), builtins.range(10)]
        actual1 = map(func, *lst)
        actual2 = lmap(func, *lst)
        actual = [actual1, actual2],
        expected = list(builtins.map(func, *lst)),
        lengths = 10,
        self.check_result(actual, expected, lengths)

    def test_filter(self):
        func = lambda x: x
        lst = list(builtins.range(10))
        actual1 = filter(func, lst)
        actual2 = lfilter(func, lst)
        actual = [actual1, actual2],
        lengths = 9,
        expected = list(builtins.filter(func, lst)),
        self.check_result(actual, expected, lengths)

    def test_zip(self):
        lst = [builtins.range(10), builtins.range(10), builtins.range(10)]
        actual = [zip(*lst), lzip(*lst)],
        expected = list(builtins.zip(*lst)),
        lengths = 10,
        self.check_result(actual, expected, lengths)

    def test_dict_iterators(self):
        self.assertEqual(next(itervalues({1: 2})), 2)
        self.assertEqual(next(iterkeys({1: 2})), 1)
        self.assertEqual(next(iteritems({1: 2})), (1, 2))


text:
package com.jfinal.core;

import java.lang.reflect.Method;
import com.jfinal.aop.Interceptor;

/**
 * Action
 */
class Action {

	private final Class<? extends Controller> controllerClass;
	private final String controllerKey;
	private final String actionKey;
	private final Method method;
	private final String methodName;
	private final Interceptor[] interceptors;
	private final String viewPath;

	public Action(String controllerKey, String actionKey, Class<? extends Controller> controllerClass, Method method, String methodName, Interceptor[] interceptors, String viewPath) {
		this.controllerKey = controllerKey;
		this.actionKey = actionKey;
		this.controllerClass = controllerClass;
		this.method = method;
		this.methodName = methodName;
		this.interceptors = interceptors;
		this.viewPath = viewPath;
	}

	public Class<? extends Controller> getControllerClass() {
		return controllerClass;
	}

	public String getControllerKey() {
		return controllerKey;
	}

	public String getActionKey() {
		return actionKey;
	}

	public Method getMethod() {
		return method;
	}

	public Interceptor[] getInterceptors() {
		return interceptors;
	}

	public String getViewPath() {
		return viewPath;
	}

	public String getMethodName() {
		return methodName;
	}
}


text: I'm studying Angular2.


text:
.class public Landroid/app/job/JobParameters;
.super Ljava/lang/Object;
.source "JobParameters.java"

# interfaces
.implements Landroid/os/Parcelable;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/app/job/JobParameters$1;
    }
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/app/job/JobParameters;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field private final callback:Landroid/os/IBinder;

.field private final extras:Landroid/os/PersistableBundle;

.field private final jobId:I

.field private final overrideDeadlineExpired:Z

# direct methods
.method static constructor <clinit>()V
    .registers 1

    .prologue
    .line 96
    new-instance v0, Landroid/app/job/JobParameters$1;

    invoke-direct {v0}, Landroid/app/job/JobParameters$1;-><init>()V

    sput-object v0, Landroid/app/job/JobParameters;->CREATOR:Landroid/os/Parcelable$Creator;

    .line 29
    return-void
.end method

.method public constructor <init>(Landroid/os/IBinder;ILandroid/os/PersistableBundle;Z)V
    .registers 5
    .param p1, "callback"    # Landroid/os/IBinder;
    .param p2, "jobId"    # I
    .param p3, "extras"    # Landroid/os/PersistableBundle;
    .param p4, "overrideDeadlineExpired"    # Z

    .prologue
    .line 37
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 39
    iput p2, p0, Landroid/app/job/JobParameters;->jobId:I

    .line 40
    iput-object p3, p0, Landroid/app/job/JobParameters;->extras:Landroid/os/PersistableBundle;

    .line 41
    iput-object p1, p0, Landroid/app/job/JobParameters;->callback:Landroid/os/IBinder;

    .line 42
    iput-boolean p4, p0, Landroid/app/job/JobParameters;->overrideDeadlineExpired:Z

    .line 38
    return-void
.end method

.method private constructor <init>(Landroid/os/Parcel;)V
    .registers 4
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    const/4 v0, 0x1

    .line 76
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 77
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/job/JobParameters;->jobId:I

    .line 78
    invoke-virtual {p1}, Landroid/os/Parcel;->readPersistableBundle()Landroid/os/PersistableBundle;

    move-result-object v1

    iput-object v1, p0, Landroid/app/job/JobParameters;->extras:Landroid/os/PersistableBundle;

    .line 79
    invoke-virtual {p1}, Landroid/os/Parcel;->readStrongBinder()Landroid/os/IBinder;

    move-result-object v1

    iput-object v1, p0, Landroid/app/job/JobParameters;->callback:Landroid/os/IBinder;

    .line 80
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-ne v1, v0, :cond_1f

    :goto_1c
    iput-boolean v0, p0, Landroid/app/job/JobParameters;->overrideDeadlineExpired:Z

    .line 76
    return-void

    .line 80
    :cond_1f
    const/4 v0, 0x0

    goto :goto_1c
.end method

.method synthetic constructor <init>(Landroid/os/Parcel;Landroid/app/job/JobParameters;)V
    .registers 3
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    invoke-direct {p0, p1}, Landroid/app/job/JobParameters;-><init>(Landroid/os/Parcel;)V

    return-void
.end method

# virtual methods
.method public describeContents()I
    .registers 2

    .prologue
    .line 85
    const/4 v0, 0x0

    return v0
.end method

.method public getCallback()Landroid/app/job/IJobCallback;
    .registers 2

    .prologue
    .line 73
    iget-object v0, p0, Landroid/app/job/JobParameters;->callback:Landroid/os/IBinder;

    invoke-static {v0}, Landroid/app/job/IJobCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/app/job/IJobCallback;

    move-result-object v0

    return-object v0
.end method

.method public getExtras()Landroid/os/PersistableBundle;
    .registers 2

    .prologue
    .line 58
    iget-object v0, p0, Landroid/app/job/JobParameters;->extras:Landroid/os/PersistableBundle;

    return-object v0
.end method

.method public getJobId()I
    .registers 2

    .prologue
    .line 49
    iget v0, p0, Landroid/app/job/JobParameters;->jobId:I

    return v0
.end method

.method public isOverrideDeadlineExpired()Z
    .registers 2

    .prologue
    .line 68
    iget-boolean v0, p0, Landroid/app/job/JobParameters;->overrideDeadlineExpired:Z

    return v0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .registers 4
    .param p1, "dest"    # Landroid/os/Parcel;
    .param p2, "flags"    # I

    .prologue
    .line 90
    iget v0, p0, Landroid/app/job/JobParameters;->jobId:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 91
    iget-object v0, p0, Landroid/app/job/JobParameters;->extras:Landroid/os/PersistableBundle;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writePersistableBundle(Landroid/os/PersistableBundle;)V

    .line 92
    iget-object v0, p0, Landroid/app/job/JobParameters;->callback:Landroid/os/IBinder;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    .line 93
    iget-boolean v0, p0, Landroid/app/job/JobParameters;->overrideDeadlineExpired:Z

    if-eqz v0, :cond_18

    const/4 v0, 0x1

    :goto_14
    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 89
    return-void

    .line 93
    :cond_18
    const/4 v0, 0x0

    goto :goto_14
.end method


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "COPY TO" do
  before(:all) do
    ActiveRecord::Base.connection.execute %{
      TRUNCATE TABLE test_models;
      SELECT setval('test_models_id_seq', 1, false);
}
    TestModel.create :data => 'test data 1'
  end

  describe ".copy_to_string" do
    context "with no options" do
      subject{ TestModel.copy_to_string }
      it{ should == File.open('spec/fixtures/comma_with_header.csv', 'r').read }
    end

    context "with tab as delimiter" do
      subject{ TestModel.copy_to_string :delimiter => "\t" }
      it{ should == File.open('spec/fixtures/tab_with_header.csv', 'r').read }
    end
  end

  describe ".copy_to" do
    it "should copy and pass data to block if block is given and no path is passed" do
      File.open('spec/fixtures/comma_with_header.csv', 'r') do |f|
        TestModel.copy_to do |row|
          row.should == f.readline
        end
      end
    end

    it "should copy to disk if block is not given and a path is passed" do
      TestModel.copy_to '/tmp/export.csv'
      File.open('spec/fixtures/comma_with_header.csv', 'r') do |fixture|
        File.open('/tmp/export.csv', 'r') do |result|
          result.read.should == fixture.read
        end
      end
    end

    it "should raise exception if I pass a path and a block simultaneously" do
      lambda do
        TestModel.copy_to('/tmp/bogus_path') do |row|
        end
      end.should raise_error
    end
  end
end


text:
#include "instruction_set.h"

#include <gtest/gtest.h>

#include "base/stringprintf.h"

namespace art {

TEST(InstructionSetTest, GetInstructionSetFromString) {
  EXPECT_EQ(kArm, GetInstructionSetFromString("arm"));
  EXPECT_EQ(kArm64, GetInstructionSetFromString("arm64"));
  EXPECT_EQ(kX86, GetInstructionSetFromString("x86"));
  EXPECT_EQ(kX86_64, GetInstructionSetFromString("x86_64"));
  EXPECT_EQ(kMips, GetInstructionSetFromString("mips"));
  EXPECT_EQ(kMips64, GetInstructionSetFromString("mips64"));
  EXPECT_EQ(kNone, GetInstructionSetFromString("none"));
  EXPECT_EQ(kNone, GetInstructionSetFromString("random-string"));
}

TEST(InstructionSetTest, GetInstructionSetString) {
  EXPECT_STREQ("arm", GetInstructionSetString(kArm));
  EXPECT_STREQ("arm", GetInstructionSetString(kThumb2));
  EXPECT_STREQ("arm64", GetInstructionSetString(kArm64));
  EXPECT_STREQ("x86", GetInstructionSetString(kX86));
  EXPECT_STREQ("x86_64", GetInstructionSetString(kX86_64));
  EXPECT_STREQ("mips", GetInstructionSetString(kMips));
  EXPECT_STREQ("mips64", GetInstructionSetString(kMips64));
  EXPECT_STREQ("none", GetInstructionSetString(kNone));
}

TEST(InstructionSetTest, TestRoundTrip) {
  EXPECT_EQ(kRuntimeISA, GetInstructionSetFromString(GetInstructionSetString(kRuntimeISA)));
}

TEST(InstructionSetTest, PointerSize) {
  EXPECT_EQ(sizeof(void*), GetInstructionSetPointerSize(kRuntimeISA));
}

}  // namespace art


text:
/*! \file for_each.h
 *  \brief Sequential implementations of for_each functions.
 */

#pragma once

#include <thrust/detail/config.h>
#include <thrust/detail/function.h>
#include <thrust/system/detail/sequential/execution_policy.h>

namespace thrust
{
namespace system
{
namespace detail
{
namespace sequential
{

__thrust_hd_warning_disable__
template<typename DerivedPolicy,
         typename InputIterator,
         typename UnaryFunction>
__host__ __device__
InputIterator for_each(sequential::execution_policy<DerivedPolicy> &,
                       InputIterator first,
                       InputIterator last,
                       UnaryFunction f)
{
  // wrap f
  thrust::detail::wrapped_function<
    UnaryFunction,
    void
  > wrapped_f(f);

  for(; first != last; ++first)
  {
    wrapped_f(*first);
  }

  return first;
} // end for_each()

template<typename DerivedPolicy,
         typename InputIterator,
         typename Size,
         typename UnaryFunction>
__host__ __device__
InputIterator for_each_n(sequential::execution_policy<DerivedPolicy> &,
                         InputIterator first,
                         Size n,
                         UnaryFunction f)
{
  // wrap f
  thrust::detail::wrapped_function<
    UnaryFunction,
    void
  > wrapped_f(f);

  for(Size i = 0; i != n; i++)
  {
    // we can dereference an OutputIterator if f does not
    // try to use the reference for anything besides assignment
    wrapped_f(*first);
    ++first;
  }

  return first;
} // end for_each_n()

} // end namespace sequential
} // end namespace detail
} // end namespace system
} // end namespace thrust


text:
<?xml version="1.0"?>

<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
<document>

    <title>Using Scalable Vector Graphics (SVG)</title>

      Forrest can deliver raw SVG files for capable browsers, e.g. Firefox. See
      example.

      Forrest can convert SVG files into Portable Network Graphic (PNG). See
      example. Note that Forrest will first look for a
      pre-prepared PNG file, and if not found then it will generate the PNG from
      the SVG.

      Be careful. We only provide a local copy of the SVG 1.0 DTD so if you use
      SVG 1.1 then there will be network trips for the DTDs.
      Configure
      your local catalog entity resolver for your local DTD copies.

</document>