text:
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/smp.h>
#include <linux/user.h>
#include <linux/security.h>
#include <linux/audit.h>
#include <linux/seccomp.h>

#include <asm/byteorder.h>
#include <asm/cpu.h>
#include <asm/dsp.h>
#include <asm/fpu.h>
#include <asm/mipsregs.h>
#include <asm/mipsmtregs.h>
#include <asm/pgtable.h>
#include <asm/page.h>
#include <asm/uaccess.h>
#include <asm/bootinfo.h>
#include <asm/reg.h>

/*
 * Called by kernel/ptrace.c when detaching..
 *
 * Make sure single step bits etc are not set.
 */
void ptrace_disable(struct task_struct *child)
{
	/* Don't load the watchpoint registers for the ex-child. */
	clear_tsk_thread_flag(child, TIF_LOAD_WATCH);
}

/*
 * Read a general register set.	 We always use the 64-bit format, even
 * for 32-bit kernels and for 32-bit processes on a 64-bit kernel.
 * Registers are sign extended to fill the available space.
 */
int ptrace_getregs(struct task_struct *child, __s64 __user *data)
{
	struct pt_regs *regs;
	int i;

	if (!access_ok(VERIFY_WRITE, data, 38 * 8))
		return -EIO;

	regs = task_pt_regs(child);

	for (i = 0; i < 32; i++)
		__put_user((long)regs->regs[i], data + i);
	__put_user((long)regs->lo, data + EF_LO - EF_R0);
	__put_user((long)regs->hi, data + EF_HI - EF_R0);
	__put_user((long)regs->cp0_epc, data + EF_CP0_EPC - EF_R0);
	__put_user((long)regs->cp0_badvaddr, data + EF_CP0_BADVADDR - EF_R0);
	__put_user((long)regs->cp0_status, data + EF_CP0_STATUS - EF_R0);
	__put_user((long)regs->cp0_cause, data + EF_CP0_CAUSE - EF_R0);

	return 0;
}

/*
 * Write a general register set.  As for PTRACE_GETREGS, we always use
 * the 64-bit format.  On a 32-bit kernel only the lower order half
 * (according to endianness) will be used.
 */
int ptrace_setregs(struct task_struct *child, __s64 __user *data)
{
	struct pt_regs *regs;
	int i;

	if (!access_ok(VERIFY_READ, data, 38 * 8))
		return -EIO;

	regs = task_pt_regs(child);

	for (i = 0; i < 32; i++)
		__get_user(regs->regs[i], data + i);
	__get_user(regs->lo, data + EF_LO - EF_R0);
	__get_user(regs->hi, data + EF_HI - EF_R0);
	__get_user(regs->cp0_epc, data + EF_CP0_EPC - EF_R0);

	/* badvaddr, status, and cause may not be written.  */

	return 0;
}

int ptrace_getfpregs(struct task_struct *child, __u32 __user *data)
{
	int i;
	unsigned int tmp;

	if (!access_ok(VERIFY_WRITE, data, 33 * 8))
		return -EIO;

	if (tsk_used_math(child)) {
		fpureg_t *fregs = get_fpu_regs(child);
		for (i = 0; i < 32; i++)
			__put_user(fregs[i], i + (__u64 __user *) data);
	} else {
		for (i = 0; i < 32; i++)
			__put_user((__u64) -1, i + (__u64 __user *) data);
	}

	__put_user(child->thread.fpu.fcr31, data + 64);

	preempt_disable();
	if (cpu_has_fpu) {
		unsigned int flags;

		if (cpu_has_mipsmt) {
			unsigned int vpflags = dvpe();
			flags = read_c0_status();
			__enable_fpu();
			__asm__ __volatile__("cfc1\t%0,$0" : "=r" (tmp));
			write_c0_status(flags);
			evpe(vpflags);
		} else {
			flags = read_c0_status();
			__enable_fpu();
			__asm__ __volatile__("cfc1\t%0,$0" : "=r" (tmp));
			write_c0_status(flags);
		}
	} else {
		tmp = 0;
	}
	preempt_enable();
	__put_user(tmp, data + 65);

	return 0;
}

int ptrace_setfpregs(struct task_struct *child, __u32 __user *data)
{
	fpureg_t *fregs;
	int i;

	if (!access_ok(VERIFY_READ, data, 33 * 8))
		return -EIO;

	fregs = get_fpu_regs(child);

	for (i = 0; i < 32; i++)
		__get_user(fregs[i], i + (__u64 __user *) data);

	__get_user(child->thread.fpu.fcr31, data + 64);

	/* FIR may not be written.  */

	return 0;
}

int ptrace_get_watch_regs(struct task_struct *child,
			  struct pt_watch_regs __user *addr)
{
	enum pt_watch_style style;
	int i;

	if (!cpu_has_watch || current_cpu_data.watch_reg_use_cnt == 0)
		return -EIO;
	if (!access_ok(VERIFY_WRITE, addr, sizeof(struct pt_watch_regs)))
		return -EIO;

#ifdef CONFIG_32BIT
	style = pt_watch_style_mips32;
#define WATCH_STYLE mips32
#else
	style = pt_watch_style_mips64;
#define WATCH_STYLE mips64
#endif

	__put_user(style, &addr->style);
	__put_user(current_cpu_data.watch_reg_use_cnt,
		   &addr->WATCH_STYLE.num_valid);
	for (i = 0; i < current_cpu_data.watch_reg_use_cnt; i++) {
		__put_user(child->thread.watch.mips3264.watchlo[i],
			   &addr->WATCH_STYLE.watchlo[i]);
		__put_user(child->thread.watch.mips3264.watchhi[i] & 0xfff,
			   &addr->WATCH_STYLE.watchhi[i]);
		__put_user(current_cpu_data.watch_reg_masks[i],
			   &addr->WATCH_STYLE.watch_masks[i]);
	}
	for (; i < 8; i++) {
		__put_user(0, &addr->WATCH_STYLE.watchlo[i]);
		__put_user(0, &addr->WATCH_STYLE.watchhi[i]);
		__put_user(0, &addr->WATCH_STYLE.watch_masks[i]);
	}

	return 0;
}

int ptrace_set_watch_regs(struct task_struct *child,
			  struct pt_watch_regs __user *addr)
{
	int i;
	int watch_active = 0;
	unsigned long lt[NUM_WATCH_REGS];
	u16 ht[NUM_WATCH_REGS];

	if (!cpu_has_watch || current_cpu_data.watch_reg_use_cnt == 0)
		return -EIO;
	if (!access_ok(VERIFY_READ, addr, sizeof(struct pt_watch_regs)))
		return -EIO;
	/* Check the values. */
	for (i = 0; i < current_cpu_data.watch_reg_use_cnt; i++) {
		__get_user(lt[i], &addr->WATCH_STYLE.watchlo[i]);
#ifdef CONFIG_32BIT
		if (lt[i] & __UA_LIMIT)
			return -EINVAL;
#else
		if (test_tsk_thread_flag(child, TIF_32BIT_ADDR)) {
			if (lt[i] & 0xffffffff80000000UL)
				return -EINVAL;
		} else {
			if (lt[i] & __UA_LIMIT)
				return -EINVAL;
		}
#endif
		__get_user(ht[i], &addr->WATCH_STYLE.watchhi[i]);
		if (ht[i] & ~0xff8)
			return -EINVAL;
	}
	/* Install them. */
	for (i = 0; i < current_cpu_data.watch_reg_use_cnt; i++) {
		if (lt[i] & 7)
			watch_active = 1;
		child->thread.watch.mips3264.watchlo[i] = lt[i];
		/* Set the G bit. */
		child->thread.watch.mips3264.watchhi[i] = ht[i];
	}

	if (watch_active)
		set_tsk_thread_flag(child, TIF_LOAD_WATCH);
	else
		clear_tsk_thread_flag(child, TIF_LOAD_WATCH);

	return 0;
}

long arch_ptrace(struct task_struct *child, long request,
		 unsigned long addr, unsigned long data)
{
	int ret;
	void __user *addrp = (void __user *) addr;
	void __user *datavp = (void __user *) data;
	unsigned long __user *datalp = (void __user *) data;

	switch (request) {
	/* when I and D space are separate, these will need to be fixed. */
	case PTRACE_PEEKTEXT: /* read word at location addr. */
	case PTRACE_PEEKDATA:
		ret = generic_ptrace_peekdata(child, addr, data);
		break;

	/* Read the word at location addr in the USER area. */
	case PTRACE_PEEKUSR: {
		struct pt_regs *regs;
		unsigned long tmp = 0;

		regs = task_pt_regs(child);
		ret = 0;  /* Default return value. */

		switch (addr) {
		case 0 ... 31:
			tmp = regs->regs[addr];
			break;
		case FPR_BASE ... FPR_BASE + 31:
			if (tsk_used_math(child)) {
				fpureg_t *fregs = get_fpu_regs(child);

#ifdef CONFIG_32BIT
				/*
				 * The odd registers are actually the high
				 * order bits of the values stored in the even
				 * registers - unless we're using r2k_switch.S.
				 */
				if (addr & 1)
					tmp = (unsigned long) (fregs[((addr & ~1) - 32)] >> 32);
				else
					tmp = (unsigned long) (fregs[(addr - 32)] & 0xffffffff);
#endif
#ifdef CONFIG_64BIT
				tmp = fregs[addr - FPR_BASE];
#endif
			} else {
				tmp = -1;	/* FP not yet used  */
			}
			break;
		case PC:
			tmp = regs->cp0_epc;
			break;
		case CAUSE:
			tmp = regs->cp0_cause;
			break;
		case BADVADDR:
			tmp = regs->cp0_badvaddr;
			break;
		case MMHI:
			tmp = regs->hi;
			break;
		case MMLO:
			tmp = regs->lo;
			break;
#ifdef CONFIG_CPU_HAS_SMARTMIPS
		case ACX:
			tmp = regs->acx;
			break;
#endif
		case FPC_CSR:
			tmp = child->thread.fpu.fcr31;
			break;
		case FPC_EIR: { /* implementation / version register */
			unsigned int flags;
#ifdef CONFIG_MIPS_MT_SMTC
			unsigned long irqflags;
			unsigned int mtflags;
#endif /* CONFIG_MIPS_MT_SMTC */

			preempt_disable();
			if (!cpu_has_fpu) {
				preempt_enable();
				break;
			}

#ifdef CONFIG_MIPS_MT_SMTC
			/* Read-modify-write of Status must be atomic */
			local_irq_save(irqflags);
			mtflags = dmt();
#endif /* CONFIG_MIPS_MT_SMTC */
			if (cpu_has_mipsmt) {
				unsigned int vpflags = dvpe();
				flags = read_c0_status();
				__enable_fpu();
				__asm__ __volatile__("cfc1\t%0,$0": "=r" (tmp));
				write_c0_status(flags);
				evpe(vpflags);
			} else {
				flags = read_c0_status();
				__enable_fpu();
				__asm__ __volatile__("cfc1\t%0,$0": "=r" (tmp));
				write_c0_status(flags);
			}
#ifdef CONFIG_MIPS_MT_SMTC
			emt(mtflags);
			local_irq_restore(irqflags);
#endif /* CONFIG_MIPS_MT_SMTC */
			preempt_enable();
			break;
		}
		case DSP_BASE ... DSP_BASE + 5: {
			dspreg_t *dregs;

			if (!cpu_has_dsp) {
				tmp = 0;
				ret = -EIO;
				goto out;
			}
			dregs = __get_dsp_regs(child);
			tmp = (unsigned long) (dregs[addr - DSP_BASE]);
			break;
		}
		case DSP_CONTROL:
			if (!cpu_has_dsp) {
				tmp = 0;
				ret = -EIO;
				goto out;
			}
			tmp = child->thread.dsp.dspcontrol;
			break;
		default:
			tmp = 0;
			ret = -EIO;
			goto out;
		}
		ret = put_user(tmp, datalp);
		break;
	}

	/* when I and D space are separate, this will have to be fixed. */
	case PTRACE_POKETEXT: /* write the word at location addr. */
	case PTRACE_POKEDATA:
		ret = generic_ptrace_pokedata(child, addr, data);
		break;

	case PTRACE_POKEUSR: {
		struct pt_regs *regs;
		ret = 0;
		regs = task_pt_regs(child);

		switch (addr) {
		case 0 ... 31:
			regs->regs[addr] = data;
			break;
		case FPR_BASE ... FPR_BASE + 31: {
			fpureg_t *fregs = get_fpu_regs(child);

			if (!tsk_used_math(child)) {
				/* FP not yet used  */
				memset(&child->thread.fpu, ~0,
				       sizeof(child->thread.fpu));
				child->thread.fpu.fcr31 = 0;
			}
#ifdef CONFIG_32BIT
			/*
			 * The odd registers are actually the high order bits
			 * of the values stored in the even registers - unless
			 * we're using r2k_switch.S.
			 */
			if (addr & 1) {
				fregs[(addr & ~1) - FPR_BASE] &= 0xffffffff;
				fregs[(addr & ~1) - FPR_BASE] |= ((unsigned long long) data) << 32;
			} else {
				fregs[addr - FPR_BASE] &= ~0xffffffffLL;
				fregs[addr - FPR_BASE] |= data;
			}
#endif
#ifdef CONFIG_64BIT
			fregs[addr - FPR_BASE] = data;
#endif
			break;
		}
		case PC:
			regs->cp0_epc = data;
			break;
		case MMHI:
			regs->hi = data;
			break;
		case MMLO:
			regs->lo = data;
			break;
#ifdef CONFIG_CPU_HAS_SMARTMIPS
		case ACX:
			regs->acx = data;
			break;
#endif
		case FPC_CSR:
			child->thread.fpu.fcr31 = data;
			break;
		case DSP_BASE ... DSP_BASE + 5: {
			dspreg_t *dregs;

			if (!cpu_has_dsp) {
				ret = -EIO;
				break;
			}

			dregs = __get_dsp_regs(child);
			dregs[addr - DSP_BASE] = data;
			break;
		}
		case DSP_CONTROL:
			if (!cpu_has_dsp) {
				ret = -EIO;
				break;
			}
			child->thread.dsp.dspcontrol = data;
			break;
		default:
			/* The rest are not allowed. */
			ret = -EIO;
			break;
		}
		break;
		}

	case PTRACE_GETREGS:
		ret = ptrace_getregs(child, datavp);
		break;

	case PTRACE_SETREGS:
		ret = ptrace_setregs(child, datavp);
		break;

	case PTRACE_GETFPREGS:
		ret = ptrace_getfpregs(child, datavp);
		break;

	case PTRACE_SETFPREGS:
		ret = ptrace_setfpregs(child, datavp);
		break;

	case PTRACE_GET_THREAD_AREA:
		ret = put_user(task_thread_info(child)->tp_value, datalp);
		break;

	case PTRACE_GET_WATCH_REGS:
		ret = ptrace_get_watch_regs(child, addrp);
		break;

	case PTRACE_SET_WATCH_REGS:
		ret = ptrace_set_watch_regs(child, addrp);
		break;

	default:
		ret = ptrace_request(child, request, addr, data);
		break;
	}
 out:
	return ret;
}

static inline int audit_arch(void)
{
	int arch = EM_MIPS;
#ifdef CONFIG_64BIT
	arch |=	 __AUDIT_ARCH_64BIT;
#endif
#if defined(__LITTLE_ENDIAN)
	arch |=	 __AUDIT_ARCH_LE;
#endif
	return arch;
}

/*
 * Notification of system call entry/exit
 * - triggered by current->work.syscall_trace
 */
asmlinkage void syscall_trace_enter(struct pt_regs *regs)
{
	/* do the secure computing check first */
	secure_computing_strict(regs->regs[2]);

	if (!(current->ptrace & PT_PTRACED))
		goto out;

	if (!test_thread_flag(TIF_SYSCALL_TRACE))
		goto out;

	/* The 0x80 provides a way for the tracing parent to distinguish
	   between a syscall stop and SIGTRAP delivery */
	ptrace_notify(SIGTRAP | ((current->ptrace & PT_TRACESYSGOOD) ?
				 0x80 : 0));

	/*
	 * this isn't the same as continuing with a signal, but it will do
	 * for normal use.  strace only continues with a signal if the
	 * stopping signal is not SIGTRAP.  -brl
	 */
	if (current->exit_code) {
		send_sig(current->exit_code, current, 1);
		current->exit_code = 0;
	}

out:
	audit_syscall_entry(audit_arch(), regs->regs[2],
			    regs->regs[4], regs->regs[5],
			    regs->regs[6], regs->regs[7]);
}

/*
 * Notification of system call entry/exit
 * - triggered by current->work.syscall_trace
 */
asmlinkage void syscall_trace_leave(struct pt_regs *regs)
{
	audit_syscall_exit(regs);

	if (!(current->ptrace & PT_PTRACED))
		return;

	if (!test_thread_flag(TIF_SYSCALL_TRACE))
		return;

	/* The 0x80 provides a way for the tracing parent to distinguish
	   between a syscall stop and SIGTRAP delivery */
	ptrace_notify(SIGTRAP | ((current->ptrace & PT_TRACESYSGOOD) ?
				 0x80 : 0));

	/*
	 * this isn't the same as continuing with a signal, but it will do
	 * for normal use.  strace only continues with a signal if the
	 * stopping signal is not SIGTRAP.  -brl
	 */
	if (current->exit_code) {
		send_sig(current->exit_code, current, 1);
		current->exit_code = 0;
	}
}


text:
/* automatically generated by rust-bindgen */

#![allow(
    dead_code,
    non_snake_case,
    non_camel_case_types,
    non_upper_case_globals
)]
#![cfg(target_os = "macos")]

#[macro_use]
extern crate objc;
#[allow(non_camel_case_types)]
pub type id = *mut objc::runtime::Object;
pub trait Foo {}
impl Foo for id {}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct FooStruct {
    pub foo: *mut id,
}
#[test]
fn bindgen_test_layout_FooStruct() {
    assert_eq!(
        ::std::mem::size_of::<FooStruct>(),
        8usize,
        concat!("Size of: ", stringify!(FooStruct))
    );
    assert_eq!(
        ::std::mem::align_of::<FooStruct>(),
        8usize,
        concat!("Alignment of ", stringify!(FooStruct))
    );
    assert_eq!(
        unsafe {
            &(*(::std::ptr::null::<FooStruct>())).foo as *const _ as usize
        },
        0usize,
        concat!(
            "Offset of field: ",
            stringify!(FooStruct),
            "::",
            stringify!(foo)
        )
    );
}
impl Default for FooStruct {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
extern "C" {
    pub fn fooFunc(foo: id);
}
extern "C" {
    pub static mut kFoo: *const id;
}

redpajama_set_name: RedPajamaGithub


text:
var path = require('path');
var chain = require('stack-chain');
var _ = require('lodash');

var currentFilter = null;
var cucumberPath = path.join(__dirname, '..');

function isFrameInCucumber(frame) {
  var fileName = frame.getFileName() || '';
  return fileName.indexOf(cucumberPath) !== -1;
}

function filter() {
  currentFilter = chain.filter.attach(function (error, frames) {
    if (frames.length > 0 && isFrameInCucumber(frames[0])) {
      return frames;
    }
    return frames.filter(_.negate(isFrameInCucumber));
  });
}

function unfilter() {
  chain.filter.deattach(currentFilter);
}

module.exports = {
  filter: filter,
  unfilter: unfilter
};


text:
<?php

namespace Oro\Bundle\ActivityBundle\Tests\Unit\Form\Type;

use Oro\Bundle\ActivityBundle\Form\Type\MultipleAssociationChoiceType;
use Oro\Bundle\EntityConfigBundle\Config\Id\EntityConfigId;
use Oro\Bundle\EntityExtendBundle\Form\Type\MultipleAssociationChoiceType as BaseMultipleAssociationChoiceType;
use Oro\Bundle\EntityExtendBundle\Form\Util\AssociationTypeHelper;
use Oro\Bundle\EntityExtendBundle\Tests\Unit\Form\Type\AssociationTypeTestCase;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormView;

class MultipleAssociationChoiceTypeTest extends AssociationTypeTestCase
{
    /** @var \PHPUnit\Framework\MockObject\MockObject */
    protected $entityConfigProvider;

    /**
     * {@inheritdoc}
     */
    protected function getFormType()
    {
        $entityClassResolver = $this->getMockBuilder('Oro\Bundle\EntityBundle\ORM\EntityClassResolver')
            ->disableOriginalConstructor()
            ->getMock();

        return new MultipleAssociationChoiceType(
            new AssociationTypeHelper($this->configManager, $entityClassResolver),
            $this->configManager
        );
    }

    public function testFinishViewForDisabled()
    {
        $this->configManager->expects($this->any())
            ->method('getProvider')
            ->will(
                $this->returnValueMap(
                    [
                        ['test', $this->testConfigProvider],
                    ]
                )
            );

        $this->testConfigProvider->expects($this->once())
            ->method('hasConfig')
            ->with('Test\Entity2')
            ->will($this->returnValue(false));
        $this->testConfigProvider->expects($this->never())
            ->method('getConfig');

        $view    = new FormView();
        $form    = new Form($this->createMock('Symfony\Component\Form\FormConfigInterface'));
        $options = [
            'config_id'         => new EntityConfigId('test', 'Test\Entity2'),
            'association_class' => 'test'
        ];

        $view->vars['disabled'] = false;

        $view->children[0] = new FormView($view);
        $view->children[1] = new FormView($view);

        $view->children[0]->vars['value'] = 'Test\Entity1';
        $view->children[1]->vars['value'] = 'Test\Entity2';

        $type = $this->getFormType();
        $type->finishView($view, $form, $options);

        $this->assertEquals(
            [
                'attr'     => [],
                'value'    => 'Test\Entity1'
            ],
            $view->children[0]->vars
        );
        $this->assertEquals(
            [
                'attr'     => [],
                'disabled' => true,
                'value'    => 'Test\Entity2'
            ],
            $view->children[1]->vars
        );
    }

    public function testGetName()
    {
        $this->assertEquals('oro_activity_multiple_association_choice', $this->getFormType()->getName());
    }

    public function testGetParent()
    {
        $this->assertEquals(BaseMultipleAssociationChoiceType::class, $this->getFormType()->getParent());
    }
}


text:
/**
 * Search for an item in a sorted array.
 * The value returned is either the position of the item or where it should be inserted.
 */
export function binarySearch<T>(arr: Array<T>, item: T, leftOffset?: number, rightOffset?: number): number {
    let left = Math.max(leftOffset ?? 0, 0);
    let right = Math.min(rightOffset ?? arr.length, arr.length);

    while (left < right) {
        const pos = (left + right) >> 1;
        if (arr[pos] < item) {
            left = pos + 1;
        } else {
            right = pos;
        }
    }

    return left;
}


text:
/* $Id: freopen.c 481 2010-12-08 05:53:09Z solar $ */

/* freopen( const char *, const char *, FILE * )

   This file is part of the Public Domain C Library (PDCLib).
   Permission is granted to use, modify, and / or redistribute at will.
*/

#include <stdio.h>

#ifndef REGTEST

#include <_PDCLIB_glue.h>
#include <stdlib.h>
#include <string.h>

struct _PDCLIB_file_t * freopen( const char * _PDCLIB_restrict filename, const char * _PDCLIB_restrict mode, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
{
    unsigned int status = stream->status & ( _IONBF | _IOLBF | _IOFBF | _PDCLIB_FREEBUFFER | _PDCLIB_DELONCLOSE );
    /* TODO: This function can change wide orientation of a stream */
    if ( stream->status & _PDCLIB_FWRITE )
    {
        _PDCLIB_flushbuffer( stream );
    }
    if ( ( filename == NULL ) && ( stream->filename == NULL ) )
    {
        /* TODO: Special handling for mode changes on std-streams */
        return NULL;
    }
    _PDCLIB_close( stream->handle );
    /* TODO: It is not nice to do this on a stream we just closed.
       It does not matter with the current implementation of clearerr(),
       but it might start to matter if someone replaced that implementation.
    */
    clearerr( stream );
    /* The new filename might not fit the old buffer */
    if ( filename == NULL )
    {
        /* Use previous filename */
        filename = stream->filename;
    }
    else if ( ( stream->filename != NULL ) && ( strlen( stream->filename ) >= strlen( filename ) ) )
    {
        /* Copy new filename into existing buffer */
        strcpy( stream->filename, filename );
    }
    else
    {
        /* Allocate new buffer */
        if ( ( stream->filename = (char *)malloc( strlen( filename ) ) ) == NULL )
        {
            return NULL;
        }
        strcpy( stream->filename, filename );
    }
    if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
    {
        return NULL;
    }
    if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
    {
        return NULL;
    }
    /* Re-add the flags we saved above */
    stream->status |= status;
    stream->bufidx = 0;
    stream->bufend = 0;
    stream->ungetidx = 0;
    /* TODO: Setting mbstate */
    if ( ( stream->handle = _PDCLIB_open( filename, stream->status ) ) == _PDCLIB_NOHANDLE )
    {
        return NULL;
    }
    return stream;
}

#endif

#ifdef TEST
#include <_PDCLIB_test.h>

int main( void )
{
    FILE * fin;
    FILE * fout;
    TESTCASE( ( fin = fopen( testfile1, "wb+" ) ) != NULL );
    TESTCASE( fputc( 'x', fin ) == 'x' );
    TESTCASE( fclose( fin ) == 0 );
    TESTCASE( ( fin = freopen( testfile1, "rb", stdin ) ) != NULL );
    TESTCASE( getchar() == 'x' );

    TESTCASE( ( fout = freopen( testfile2, "wb+", stdout ) ) != NULL );
    TESTCASE( putchar( 'x' ) == 'x' );
    rewind( fout );
    TESTCASE( fgetc( fout ) == 'x' );

    TESTCASE( fclose( fin ) == 0 );
    TESTCASE( fclose( fout ) == 0 );
    TESTCASE( remove( testfile1 ) == 0 );
    TESTCASE( remove( testfile2 ) == 0 );

    return TEST_RESULTS;
}

#endif


text:
namespace oless {
	namespace excel {
		namespace structures {
			namespace formulas {

				// see: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/ebf366bb-b39b-453f-a2c7-b27d53d8e43f
				class ExtPtgRefErr3D : public IParseable {
				public:
					virtual void Parse(unsigned char* buffer, std::size_t max, unsigned int offset) override {
						unsigned int index = offset;

						this->bytesRead = index - offset;
					}
				};
			}
		}
	}
}


text:
package com.konifar.annict.helper;

import com.konifar.annict.model.Program;

import java.util.ArrayList;
import java.util.List;

public class MockHelper {

    public static List<Program> mockPrograms(int programsCount) {
        List<Program> mockPrograms = new ArrayList<>();

        for (int i = 0; i < programsCount; i++) {
            mockPrograms.add(new Program());
        }
        return mockPrograms;
    }
}


text:
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef OPEN_SPIEL_GAMES_IMPL_CHESS_CHESS_BOARD_H_
#define OPEN_SPIEL_GAMES_IMPL_CHESS_CHESS_BOARD_H_

#include <array>
#include <cstdint>
#include <functional>
#include <ostream>
#include <string>
#include <utility>
#include <vector>

#include "open_spiel/abseil-cpp/absl/types/optional.h"
#include "open_spiel/games/chess/chess_common.h"
#include "open_spiel/spiel_utils.h"

namespace open_spiel {
namespace chess {

using chess_common::kInvalidSquare;  // NOLINT
using chess_common::Offset;
using chess_common::Square;
using chess_common::SquareToString;  // NOLINT

template <std::size_t... Dims>
using ZobristTableU64 = chess_common::ZobristTable<uint64_t, Dims...>;

enum class Color : int8_t { kBlack = 0, kWhite = 1, kEmpty = 2 };

inline int ToInt(Color color) { return color == Color::kWhite ? 1 : 0; }

inline Color OppColor(Color color) {
  return color == Color::kWhite ? Color::kBlack : Color::kWhite;
}

std::string ColorToString(Color c);

inline std::ostream& operator<<(std::ostream& stream, Color c) {
  return stream << ColorToString(c);
}

enum class CastlingDirection { kLeft, kRight };

int ToInt(CastlingDirection dir);

enum class PieceType : int8_t {
  kEmpty = 0,
  kKing = 1,
  kQueen = 2,
  kRook = 3,
  kBishop = 4,
  kKnight = 5,
  kPawn = 6
};

static inline constexpr std::array<PieceType, 6> kPieceTypes = {
    {PieceType::kKing, PieceType::kQueen, PieceType::kRook, PieceType::kBishop,
     PieceType::kKnight, PieceType::kPawn}};

// In case all the pieces are represented in the same plane, these values are
// used to represent each piece type.
static inline constexpr std::array<float, 6> kPieceRepresentation = {
    {1, 0.8, 0.6, 0.4, 0.2, 0.1}};

// Tries to parse piece type from char ('K', 'Q', 'R', 'B', 'N', 'P').
// Case-insensitive.
absl::optional<PieceType> PieceTypeFromChar(char c);

// Converts piece type to one character strings - "K", "Q", "R", "B", "N", "P".
// p must be one of the enumerator values of PieceType.
std::string PieceTypeToString(PieceType p, bool uppercase = true);

struct Piece {
  bool operator==(const Piece& other) const {
    return type == other.type && color == other.color;
  }

  bool operator!=(const Piece& other) const { return !(*this == other); }

  std::string ToUnicode() const;
  std::string ToString() const;

  Color color;
  PieceType type;
};

static inline constexpr Piece kEmptyPiece =
    Piece{Color::kEmpty, PieceType::kEmpty};

inline std::ostream& operator<<(std::ostream& stream, const Piece& p) {
  return stream << p.ToString();
}

inline absl::optional<int8_t> ParseRank(char c) {
  if (c >= '1' && c <= '8') return c - '1';
  return absl::nullopt;
}

inline absl::optional<int8_t> ParseFile(char c) {
  if (c >= 'a' && c <= 'h') return c - 'a';
  return absl::nullopt;
}

// Maps y = [0, 7] to rank ["1", "8"].
inline std::string RankToString(int8_t rank) {
  return std::string(1, '1' + rank);
}

// Maps x = [0, 7] to file ["a", "h"].
inline std::string FileToString(int8_t file) {
  return std::string(1, 'a' + file);
}

// Offsets for all possible knight moves.
inline constexpr std::array<Offset, 8> kKnightOffsets = {
    {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {2, -1}, {2, 1}, {1, -2}, {1, 2}}};

absl::optional<Square> SquareFromString(const std::string& s);

bool IsLongDiagonal(const chess::Square& from_sq, const chess::Square& to_sq,
                    int board_size);

// Forward declare ChessBoard here because it's needed in Move::ToSAN.
class ChessBoard;

struct Move {
  Square from;
  Square to;
  Piece piece;
  PieceType promotion_type;

  // We have to record castling here, because in Chess960 we may not be able to
  // tell just from "from" and "to" squares.
  bool is_castling = false;

  Move() : is_castling(false) {}
  Move(const Square& from, const Square& to, const Piece& piece,
       PieceType promotion_type = PieceType::kEmpty, bool is_castling = false)
      : from(from),
        to(to),
        piece(piece),
        promotion_type(promotion_type),
        is_castling(is_castling) {}

  std::string ToString() const;

  // Converts to long algebraic notation, as required by the UCI protocol.
  std::string ToLAN() const;

  // Converts to standard algebraic notation, as required by portable game
  // notation (PGN). It is a chess move notation that is designed to be
  // human-readable and concise.
  //
  // Unlike the LAN format, generating a SAN string requires the board the move
  // is generated from.
  //
  // There are 3 types of SAN moves -
  // 1. O-O (short castle)
  // 2. O-O-O (long castle)
  // 3. [piece type][from file][from rank][x][to square][=Promo][annotations]
  //
  // [piece type] is omitted for pawns
  // [from file] is only included if 1) move is a pawn capture, or 2) it's
  //     required for disambiguation (see below).
  // [from rank] is only included if it's required for disambiguation.
  // [x] is only included for captures
  // [to square] is always included
  // [=Promo] is only included for promotions ("=N", "=B", "=R", "=Q" depending
  //     on type promoting to).
  // [annotations] are a list of 0 or more characters added with different
  //     meanings. The ones we care about are '+' for check, and '#' for
  //     checkmate. All others are optional.
  //
  // Disambiguation:
  // If a move is not uniquely-identified otherwise, file and/or rank of the
  // from square is inserted to disambiguate. When either one will disambiguate,
  // file should be used. If file is unique, file is used. Otherwise if rank is
  // unique, rank is used. If neither is unique (this happens rarely, usually
  // after under-promoting to a minor piece with both original pieces still
  // intact, or double queen promotions with original queen still intact), both
  // are used.
  //
  // Examples:
  // * e4 (pawn to e4)
  // * exd5 (pawn on file e capture the piece on d5)
  // * Nf3 (knight to f3)
  // * Nxd5 (knight captures piece on d5)
  // * Bed5 (bishop on file e to d5)
  // * B5xc3 (bishop on rank 5 capture piece on c3)
  // * Ne5f7 (knight on e5 to f7, when there are 3 knights on the board, one on
  //          e file, and one on 5th rank)
  // * exd8=N#!! (pawn on e file capture piece on d8 and promote to knight
  //              resulting in checkmate in a surprisingly good move)
  // * O-O-O!!N+/- (a surprisingly good long castle that is a theoretical
  //                novelty that gives white a clear but not winning advantage)
  std::string ToSAN(const ChessBoard& board) const;

  bool operator==(const Move& other) const {
    return from == other.from && to == other.to && piece == other.piece &&
           promotion_type == other.promotion_type &&
           is_castling == other.is_castling;
  }
};

inline std::ostream& operator<<(std::ostream& stream, const Move& m) {
  return stream << m.ToString();
}

bool IsMoveCharacter(char c);

std::pair<std::string, std::string> SplitAnnotations(const std::string& move);

inline constexpr int kMaxBoardSize = 8;
inline constexpr int kDefaultBoardSize = 8;
inline constexpr int k2dMaxBoardSize = kMaxBoardSize * kMaxBoardSize;
inline const std::string kDefaultStandardFEN =
    "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
inline const std::string kDefaultSmallFEN = "r1kr/pppp/PPPP/R1KR w - - 0 1";

using ObservationTable = std::array<bool, k2dMaxBoardSize>;

// Specifies policy for pseudo legal moves generation.
enum PseudoLegalMoveSettings {
  // Standard legal moves (do not allow to move past enemy pieces).
  kAcknowledgeEnemyPieces,
  // Pseudo-legal moves, where a piece can move anywhere (according to the rules
  // for that piece), except if it was blocked from doing so by other player's
  // pieces. This is used in games, where the player may not know the position
  // of an enemy piece (like Kriegspiel or RBC) and it can try to move past the
  // enemy (for example a rook can try to move the other side of the board, even
  // if it is in fact blocked by an unseen opponent's pawn).
  kBreachEnemyPieces,
};

// Some chess variants (RBC) allow a "pass" action/move
inline constexpr open_spiel::Action kPassAction = 0;
inline const chess::Move kPassMove =
    Move(Square{-1, -1}, Square{-1, -1},
         Piece{Color::kEmpty, PieceType::kEmpty});

class ChessBoard {
 public:
  ChessBoard(int board_size = kDefaultBoardSize,
             bool king_in_check_allowed = false,
             bool allow_pass_move = false);

  // Constructs a chess board at the given position in Forsyth-Edwards Notation.
  // https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
  static absl::optional<ChessBoard> BoardFromFEN(
      const std::string& fen, int board_size = 8,
      bool king_in_check_allowed = false,
      bool allow_pass_move = false);

  const Piece& at(Square sq) const { return board_[SquareToIndex_(sq)]; }

  void set_square(Square sq, Piece p);

  const std::array<Piece, k2dMaxBoardSize>& pieces() const { return board_; }

  Color ToPlay() const { return to_play_; }
  void SetToPlay(Color c);

  Square EpSquare() const { return ep_square_; }
  void SetEpSquare(Square sq);

  int32_t IrreversibleMoveCounter() const { return irreversible_move_counter_; }
  int32_t Movenumber() const { return move_number_; }

  bool CastlingRight(Color side, CastlingDirection direction) const;
  void SetCastlingRight(Color side, CastlingDirection direction,
                        bool can_castle);

  // Find the location of any one piece of the given type, or kInvalidSquare.
  Square find(const Piece& piece) const;

  // Pseudo-legal moves are moves that may leave the king in check, but are
  // otherwise legal.
  // The generation functions call yield(move) for each move generated.
  // The yield function should return whether generation should continue.
  // For performance reasons, we do not guarantee that no more moves will be
  // generated if yield returns false. It is only for optimization.
  using MoveYieldFn = std::function<bool(const Move&)>;
  void GenerateLegalMoves(const MoveYieldFn& yield) const {
    GenerateLegalMoves(yield, to_play_);
  }
  void GenerateLegalMoves(const MoveYieldFn& yield, Color color) const;
  void GeneratePseudoLegalMoves(
      const MoveYieldFn& yield, Color color,
      PseudoLegalMoveSettings settings =
          PseudoLegalMoveSettings::kAcknowledgeEnemyPieces) const;

  // Optimization for computing number of pawn tries for kriegspiel
  void GenerateLegalPawnCaptures(const MoveYieldFn& yield, Color color) const;
  void GeneratePseudoLegalPawnCaptures(
      const MoveYieldFn& yield, Color color,
      PseudoLegalMoveSettings settings =
          PseudoLegalMoveSettings::kAcknowledgeEnemyPieces) const;

  bool HasLegalMoves() const {
    bool found = false;
    GenerateLegalMoves([&found](const Move&) {
      found = true;
      return false;  // We don't need any more moves.
    });
    return found;
  }

  bool IsMoveLegal(const Move& tested_move) const {
    bool found = false;
    GenerateLegalMoves([&found, &tested_move](const Move& found_move) {
      if (tested_move == found_move) {
        found = true;
        return false;  // We don't need any more moves.
      }
      return true;
    });
    return found;
  }

  // Does either side have sufficient material to mate?
  // FIDE rules say it must be impossible to mate even with "most unskilled"
  // counterplay. This would technically include things like pawns blocking
  // either side from making progress.
  // Eg. "8/4k3/8/p1p1p1p1/P1P1P1P1/8/4K3/8 w - -".
  // However, detecting all such positions will require solving chess... so
  // we detect a more generally-accepted subset of positions - those with the
  // following material combinations:
  // 1. K vs K
  // 2. K+B vs K
  // 3. K+N vs K
  // 4. K+B* vs K+B* (all bishops on same coloured squares)
  bool HasSufficientMaterial() const;

  // Parses a move in standard algebraic notation or long algebraic notation
  // (see below). Returns absl::nullopt on failure.
  absl::optional<Move> ParseMove(const std::string& move) const;

  // Parses a move in standard algebraic notation as defined by FIDE.
  // https://en.wikipedia.org/wiki/Algebraic_notation_(chess).
  // Returns absl::nullopt on failure.
  absl::optional<Move> ParseSANMove(const std::string& move) const;

  // Parses a move in long algebraic notation.
  // Long algebraic notation is not standardized and there are many variants,
  // but the one we care about is of the form "e2e4" and "f7f8q". This is the
  // form used by chess engine text protocols that are of interest to us.
  // Returns absl::nullopt on failure.
  absl::optional<Move> ParseLANMove(const std::string& move) const;

  void ApplyMove(const Move& move);

  // Applies a pseudo-legal move and returns whether it's legal. This avoids
  // applying and copying the whole board once for legality testing, and once
  // for actually applying the move.
  bool TestApplyMove(const Move& move);

  bool InBoardArea(const Square& sq) const {
    return sq.x >= 0 && sq.x < board_size_ && sq.y >= 0 && sq.y < board_size_;
  }

  bool IsEmpty(const Square& sq) const {
    const Piece& piece = board_[SquareToIndex_(sq)];
    return piece.type == PieceType::kEmpty;
  }

  bool IsEnemy(const Square& sq, Color our_color) const {
    const Piece& piece = board_[SquareToIndex_(sq)];
    return piece.type != PieceType::kEmpty && piece.color != our_color;
  }

  bool IsFriendly(const Square& sq, Color our_color) const {
    const Piece& piece = board_[SquareToIndex_(sq)];
    return piece.color == our_color;
  }

  bool IsEmptyOrEnemy(const Square& sq, Color our_color) const {
    const Piece& piece = board_[SquareToIndex_(sq)];
    return piece.color != our_color;
  }

  /* Whether the square is on the pawn starting rank for our_color. */
  bool IsPawnStartingRank(const Square& sq, Color our_color) const {
    return ((our_color == Color::kWhite && sq.y == 1) ||
            (our_color == Color::kBlack && sq.y == (board_size_ - 2)));
  }

  bool IsPawnPromotionRank(const Square& sq) const {
    // No need to test for color here because a pawn can't be on the "wrong"
    // promotion rank.
    return sq.y == 0 || sq.y == (board_size_ - 1);
  }

  /* Whether the sq is under attack by the opponent. */
  bool UnderAttack(const Square& sq, Color our_color) const;

  bool InCheck() const {
    return UnderAttack(find(Piece{to_play_, PieceType::kKing}), to_play_);
  }

  int BoardSize() const { return board_size_; }

  bool KingInCheckAllowed() const { return king_in_check_allowed_; }

  bool AllowPassMove() const { return allow_pass_move_; }

  uint64_t HashValue() const { return zobrist_hash_; }

  std::string DebugString() const;

  std::string ToUnicodeString() const;

  // Constructs a string describing the chess board position in Forsyth-Edwards
  // Notation. https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
  std::string ToFEN() const;

  /* Constructs a string describing the dark chess board position in a notation
   * similar to Forsyth-Edwards Notation.
   * https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
   *
   * There are several key differences to FEN:
   * 1) Only observable squares are shown. Squares invisible to the observer are
   *    represented by the character '?'
   * 2) Only observer's castling rights are shown
   * 3) en passant square is only shown if the observer is capable of performing
   *    an en passant capture
   *
   */
  std::string ToDarkFEN(const ObservationTable& observability_table,
                        Color color) const;

  bool IsBreachingMove(Move move) const;
  void BreachingMoveToCaptureMove(Move* move) const;

 private:
  size_t SquareToIndex_(Square sq) const { return sq.y * board_size_ + sq.x; }

  /* Generate*Destinations functions call yield(sq) for every potential
   * destination generated.
   * Eg.
   * std::vector<Move> knight_moves;
   * board.GenerateKnightDestinations(Square{3, 3},
   *                                  [](const Square& sq) {
   *                                    Move move{Square{3, 3}, sq,
   *                                              Piece{kWhite, kKnight}};
   *                                    knight_moves.push_back(move);
   *                                  });
   */

  /* All the Generate*Destinations functions work in the same slightly strange
   * way -
   * They assume there's a piece of the type in question at sq, and generate
   * potential destinations. Potential destinations may include moves that
   * will leave the king exposed, and are therefore illegal.
   * This strange semantic is to support reusing these functions for checking
   * whether one side is in check, which would otherwise require an almost-
   * duplicate move generator.
   */

  // King moves without castling.
  template <typename YieldFn>
  void GenerateKingDestinations_(Square sq, Color color,
                                 const YieldFn& yield) const;

  template <typename YieldFn>
  void GenerateCastlingDestinations_(Square sq, Color color,
                                     PseudoLegalMoveSettings settings,
                                     const YieldFn& yield) const;
  bool CanCastle(Square king_sq, Color color,
                 PseudoLegalMoveSettings settings) const;
  bool CanCastleBetween(Square sq1, Square sq2,
                        bool check_safe_from_opponent,
                        PseudoLegalMoveSettings settings) const;

  template <typename YieldFn>
  void GenerateQueenDestinations_(Square sq, Color color,
                                  PseudoLegalMoveSettings settings,
                                  const YieldFn& yield) const;

  template <typename YieldFn>
  void GenerateRookDestinations_(Square sq, Color color,
                                 PseudoLegalMoveSettings settings,
                                 const YieldFn& yield) const;

  template <typename YieldFn>
  void GenerateBishopDestinations_(Square sq, Color color,
                                   PseudoLegalMoveSettings settings,
                                   const YieldFn& yield) const;

  template <typename YieldFn>
  void GenerateKnightDestinations_(Square sq, Color color,
                                   const YieldFn& yield) const;

  template <typename YieldFn>
  // Pawn moves without captures.
  void GeneratePawnDestinations_(Square sq, Color color,
                                 PseudoLegalMoveSettings settings,
                                 const YieldFn& yield) const;

  template <typename YieldFn>
  // Pawn diagonal capture destinations, with or without en passant.
  void GeneratePawnCaptureDestinations_(Square sq, Color color,
                                        PseudoLegalMoveSettings settings,
                                        bool include_ep,
                                        const YieldFn& yield) const;

  // Helper function.
  template <typename YieldFn>
  void GenerateRayDestinations_(Square sq, Color color,
                                PseudoLegalMoveSettings settings,
                                Offset offset_step, const YieldFn& yield) const;

  void SetIrreversibleMoveCounter(int c);
  void SetMovenumber(int move_number);

  int board_size_;
  bool king_in_check_allowed_;
  bool allow_pass_move_;

  std::array<Piece, k2dMaxBoardSize> board_;
  Color to_play_;
  Square ep_square_;
  int32_t irreversible_move_counter_;

  // This starts at 1, and increments after each black move (a "full move" in
  // chess is a "half move" by white followed by a "half move" by black).
  int32_t move_number_;

  struct {
    bool left_castle;   // -x direction, AKA long castle
    bool right_castle;  // +x direction, AKA short castle
  } castling_rights_[2];

  uint64_t zobrist_hash_;
};

inline std::ostream& operator<<(std::ostream& stream, const ChessBoard& board) {
  return stream << board.DebugString();
}

inline std::ostream& operator<<(std::ostream& stream, const PieceType& pt) {
  return stream << PieceTypeToString(pt);
}

ChessBoard MakeDefaultBoard();
std::string DefaultFen(int board_size);

}  // namespace chess
}  // namespace open_spiel

#endif  // OPEN_SPIEL_GAMES_IMPL_CHESS_CHESS_BOARD_H_


text:
Since Scaldi Dependancy Injection is used locally within a project.
Configuration and DI is used here.


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
  <ru.mail.parking.ui.MultiscrollView
          android:id="@+id/scroll"
          android:layout_width="match_parent"
          android:layout_height="0dp"
          android:layout_weight="1"/>

  <TextView android:id="@+id/ok"
            style="@style/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>
</LinearLayout>


text:
'use strict';

// Configuring the Articles module
angular.module('resolucaos').run(['Menus',
	function(Menus) {
		// Set top bar menu items
		// Menus.addMenuItem('topbar', 'Resolucaos', 'resolucaos', 'dropdown', '/resolucaos(/create)?');
		// Menus.addSubMenuItem('topbar', 'resolucaos', 'List Resolucaos', 'resolucaos');
		// Menus.addSubMenuItem('topbar', 'resolucaos', 'New Resolucao', 'resolucaos/create');
	}
]);


text:
#ifndef GCC_TREE_CHREC_H
#define GCC_TREE_CHREC_H

/* The following trees are unique elements.  Thus the comparison of another
   element to these elements should be done on the pointer to these trees,
   and not on their value.  */

extern tree chrec_not_analyzed_yet;
extern GTY(()) tree chrec_dont_know;
extern GTY(()) tree chrec_known;

/* After having added an automatically generated element, please
   include it in the following function.  */

static inline bool
automatically_generated_chrec_p (const_tree chrec)
{
  return (chrec == chrec_dont_know
	  || chrec == chrec_known);
}

/* The tree nodes aka. CHRECs.  */

static inline bool
tree_is_chrec (const_tree expr)
{
  if (TREE_CODE (expr) == POLYNOMIAL_CHREC
      || automatically_generated_chrec_p (expr))
    return true;
  else
    return false;
}

enum ev_direction {EV_DIR_GROWS, EV_DIR_DECREASES, EV_DIR_UNKNOWN};
enum ev_direction scev_direction (const_tree);

/* Chrec folding functions.  */
extern tree chrec_fold_plus (tree, tree, tree);
extern tree chrec_fold_minus (tree, tree, tree);
extern tree chrec_fold_multiply (tree, tree, tree);
extern tree chrec_convert (tree, tree, gimple *, bool = true);
extern tree chrec_convert_rhs (tree, tree, gimple *);
extern tree chrec_convert_aggressive (tree, tree, bool *);

/* Operations.  */
extern tree chrec_apply (unsigned, tree, tree);
extern tree chrec_apply_map (tree, vec<tree> );
extern tree chrec_replace_initial_condition (tree, tree);
extern tree initial_condition (tree);
extern tree initial_condition_in_loop_num (tree, unsigned);
extern tree evolution_part_in_loop_num (tree, unsigned);
extern tree hide_evolution_in_other_loops_than_loop (tree, unsigned);
extern tree reset_evolution_in_loop (unsigned, tree, tree);
extern tree chrec_merge (tree, tree);
extern void for_each_scev_op (tree *, bool (*) (tree *, void *), void *);
extern bool convert_affine_scev (struct loop *, tree, tree *, tree *, gimple *,
				 bool);

/* Observers.  */
extern bool eq_evolutions_p (const_tree, const_tree);
extern bool is_multivariate_chrec (const_tree);
extern bool chrec_contains_symbols (const_tree);
extern bool chrec_contains_symbols_defined_in_loop (const_tree, unsigned);
extern bool chrec_contains_undetermined (const_tree);
extern bool tree_contains_chrecs (const_tree, int *);
extern bool evolution_function_is_affine_multivariate_p (const_tree, int);
extern bool evolution_function_is_univariate_p (const_tree);
extern unsigned nb_vars_in_chrec (tree);
extern bool evolution_function_is_invariant_p (tree, int);
extern bool scev_is_linear_expression (tree);
extern bool evolution_function_right_is_integer_cst (const_tree);

/* Determines whether CHREC is equal to zero.  */

static inline bool
chrec_zerop (const_tree chrec)
{
  if (chrec == NULL_TREE)
    return false;

  if (TREE_CODE (chrec) == INTEGER_CST)
    return integer_zerop (chrec);

  return false;
}

/* Determines whether CHREC is a loop invariant with respect to LOOP_NUM.
   Set the result in RES and return true when the property can be computed.  */

static inline bool
no_evolution_in_loop_p (tree chrec, unsigned loop_num, bool *res)
{
  tree scev;

  if (chrec == chrec_not_analyzed_yet
      || chrec == chrec_dont_know
      || chrec_contains_symbols_defined_in_loop (chrec, loop_num))
    return false;

  STRIP_NOPS (chrec);
  scev = hide_evolution_in_other_loops_than_loop (chrec, loop_num);
  *res = !tree_contains_chrecs (scev, NULL);
  return true;
}

/* Build a polynomial chain of recurrence.  */

static inline tree
build_polynomial_chrec (unsigned loop_num,
			tree left,
			tree right)
{
  bool val;

  if (left == chrec_dont_know
      || right == chrec_dont_know)
    return chrec_dont_know;

  if (!no_evolution_in_loop_p (left, loop_num, &val)
      || !val)
    return chrec_dont_know;

  /* Types of left and right sides of a chrec should be compatible, but
     pointer CHRECs are special in that the evolution is of ptroff type.  */
  if (POINTER_TYPE_P (TREE_TYPE (left)))
    gcc_checking_assert (ptrofftype_p (TREE_TYPE (right)));
  else
    {
      /* Pointer types should occur only on the left hand side, i.e. in
	 the base of the chrec, and not in the step.  */
      gcc_checking_assert (!POINTER_TYPE_P (TREE_TYPE (right))
			   && types_compatible_p (TREE_TYPE (left),
						  TREE_TYPE (right)));
    }

  if (chrec_zerop (right))
    return left;

  return build3 (POLYNOMIAL_CHREC, TREE_TYPE (left),
		 build_int_cst (NULL_TREE, loop_num), left, right);
}

/* Determines whether the expression CHREC is a constant.  */

static inline bool
evolution_function_is_constant_p (const_tree chrec)
{
  if (chrec == NULL_TREE)
    return false;

  switch (TREE_CODE (chrec))
    {
    case INTEGER_CST:
    case REAL_CST:
      return true;

    default:
      return false;
    }
}

/* Determine whether CHREC is an affine evolution function in LOOPNUM.  */

static inline bool
evolution_function_is_affine_in_loop (const_tree chrec, int loopnum)
{
  if (chrec == NULL_TREE)
    return false;

  switch (TREE_CODE (chrec))
    {
    case POLYNOMIAL_CHREC:
      if (evolution_function_is_invariant_p (CHREC_LEFT (chrec), loopnum)
	  && evolution_function_is_invariant_p (CHREC_RIGHT (chrec), loopnum))
	return true;
      else
	return false;

    default:
      return false;
    }
}

/* Determine whether CHREC is an affine evolution function or not.  */

static inline bool
evolution_function_is_affine_p (const_tree chrec)
{
  return chrec
    && TREE_CODE (chrec) == POLYNOMIAL_CHREC
    && evolution_function_is_invariant_p (CHREC_RIGHT (chrec),
					  CHREC_VARIABLE (chrec))
    && (TREE_CODE (CHREC_RIGHT (chrec)) != POLYNOMIAL_CHREC
	|| evolution_function_is_affine_p (CHREC_RIGHT (chrec)));
}

/* Determines whether EXPR does not contains chrec expressions.  */

static inline bool
tree_does_not_contain_chrecs (const_tree expr)
{
  return !tree_contains_chrecs (expr, NULL);
}

/* Returns the type of the chrec.  */

static inline tree
chrec_type (const_tree chrec)
{
  if (automatically_generated_chrec_p (chrec))
    return NULL_TREE;

  return TREE_TYPE (chrec);
}

static inline tree
chrec_fold_op (enum tree_code code, tree type, tree op0, tree op1)
{
  switch (code)
    {
    case PLUS_EXPR:
      return chrec_fold_plus (type, op0, op1);

    case MINUS_EXPR:
      return chrec_fold_minus (type, op0, op1);

    case MULT_EXPR:
      return chrec_fold_multiply (type, op0, op1);

    default:
      gcc_unreachable ();
    }

}

#endif  /* GCC_TREE_CHREC_H  */


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>spring-代理创建-ProxyFactoryBean - XasaKuras iBlog</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">

<meta name="author" content="XasaKura" />
  <meta name="description" content="自动代理创建 自动代理创建的方式一共有3种: BeanNameAutoProxyCreator DefaultAdvisorAutoProxyCreator AbstractAdvisorAutoProxyCreator 他们都调用了ProxyFactoryBean实现代理创建. ProxyFactoryBean的" />

  <meta name="keywords" content="XasaKura, blog, iblog8" />

<meta name="generator" content="Hugo 0.38-DEV" />

<link rel="canonical" href="http://iblog8.com/post/2016-08-23-spring-%E4%BB%A3%E7%90%86%E5%88%9B%E5%BB%BA-proxyfactorybean/" />

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">

<link href="/dist/even.min.css?v=3.1.1" rel="stylesheet">
<link href="/lib/fancybox/jquery.fancybox-3.1.20.min.css" rel="stylesheet">

<meta property="og:title" content="spring-代理创建-ProxyFactoryBean" />
<meta property="og:description" content="自动代理创建 自动代理创建的方式一共有3种: BeanNameAutoProxyCreator DefaultAdvisorAutoProxyCreator AbstractAdvisorAutoProxyCreator 他们都调用了ProxyFactoryBean实现代理创建. ProxyFactoryBean的" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://iblog8.com/post/2016-08-23-spring-%E4%BB%A3%E7%90%86%E5%88%9B%E5%BB%BA-proxyfactorybean/" />

<meta property="article:published_time" content="2016-08-23T00:00:00+08:00"/>

<meta property="article:modified_time" content="2016-08-23T00:00:00+08:00"/>

<meta itemprop="name" content="spring-代理创建-ProxyFactoryBean">
<meta itemprop="description" content="自动代理创建 自动代理创建的方式一共有3种: BeanNameAutoProxyCreator DefaultAdvisorAutoProxyCreator AbstractAdvisorAutoProxyCreator 他们都调用了ProxyFactoryBean实现代理创建. ProxyFactoryBean的">

<meta itemprop="datePublished" content="2016-08-23T00:00:00+08:00" />
<meta itemprop="dateModified" content="2016-08-23T00:00:00+08:00" />
<meta itemprop="wordCount" content="1138">

<meta itemprop="keywords" content="" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="spring-代理创建-ProxyFactoryBean"/>
<meta name="twitter:description" content="自动代理创建 自动代理创建的方式一共有3种: BeanNameAutoProxyCreator DefaultAdvisorAutoProxyCreator AbstractAdvisorAutoProxyCreator 他们都调用了ProxyFactoryBean实现代理创建. ProxyFactoryBean的"/>

    XasaKura

Home

Archives

Tags

Categories

  XasaKura

        Home

        Archives

        Tags

        Categories

spring-代理创建-ProxyFactoryBean

         2016-08-23

               java

         1138 words
         3 mins read

Contents

自动代理创建

ProxyFactoryBean的实现

自动代理创建

自动代理创建的方式一共有3种:

BeanNameAutoProxyCreator

DefaultAdvisorAutoProxyCreator

AbstractAdvisorAutoProxyCreator

他们都调用了ProxyFactoryBean实现代理创建.

ProxyFactoryBean的实现

ProxyFactoryBean继承自FactoryBean, 实现了getObject方法:

/**
    * Return a proxy. Invoked when clients obtain beans from this factory bean.
    * Create an instance of the AOP proxy to be returned by this factory.
    * The instance will be cached for a singleton, and create on each call to
    * <code>getObject()</code> for a proxy.
    * @return a fresh AOP proxy reflecting the current state of this factory
    */
public Object getObject() throws BeansException {
    initializeAdvisorChain();
    if (isSingleton()) {
        return getSingletonInstance();
    }
    else {
        if (this.targetName == null) {
            logger.warn("Using non-singleton proxies with singleton targets is often undesirable. " +
                    "Enable prototype proxies by setting the 'targetName' property.");
        }
        return newPrototypeInstance();
    }
}

Advisor链就是在initializeAdvisorChain()里面生成的, 简单来说就是吧advisor加入父类AdvisedSupport的advisors List变量.
getSingletonInstance() 的代码如下:

/**
    * Return the singleton instance of this class's proxy object,
    * lazily creating it if it hasn't been created already.
    * @return the shared singleton proxy
    */
private synchronized Object getSingletonInstance() {
    if (this.singletonInstance == null) {
        this.targetSource = freshTargetSource();
        if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
            // Rely on AOP infrastructure to tell us what interfaces to proxy.
            Class targetClass = getTargetClass();
            if (targetClass == null) {
                throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
            }
            setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
        }
        // Initialize the shared singleton instance.
        super.setFrozen(this.freezeProxy);
        this.singletonInstance = getProxy(createAopProxy());
    }
    return this.singletonInstance;
}

如果已经有实例化了就直接返回, 没有的话就创建 this.singletonInstance = getProxy(createAopProxy());
接下来看这个创建的方法:

protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}

继续看getAopProxyFactory:

private AopProxyFactory aopProxyFactory;
/**
    * Return the AopProxyFactory that this ProxyConfig uses.
    */
public AopProxyFactory getAopProxyFactory() {
    return this.aopProxyFactory;
}

返回的是AopProxyFactory 的实例, AopProxyFactory只是一个接口, 所以我们看一下他的实现类:
只有1个 DefaultAopProxyFactory :

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

    private static final boolean cglibAvailable =
            ClassUtils.isPresent("net.sf.cglib.proxy.Enhancer", DefaultAopProxyFactory.class.getClassLoader());

    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            Class targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: " +
                        "Either an interface or a target is required for proxy creation.");
            }
            if (targetClass.isInterface()) {
                return new JdkDynamicAopProxy(config);
            }
            if (!cglibAvailable) {
                throw new AopConfigException(
                        "Cannot proxy target class because CGLIB2 is not available. " +
                        "Add CGLIB to the class path or specify proxy interfaces.");
            }
            return CglibProxyFactory.createCglibProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }

    private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
        Class[] interfaces = config.getProxiedInterfaces();
        return (interfaces.length == 0 || (interfaces.length == 1 && SpringProxy.class.equals(interfaces[0])));
    }

    private static class CglibProxyFactory {

        public static AopProxy createCglibProxy(AdvisedSupport advisedSupport) {
            return new Cglib2AopProxy(advisedSupport);
        }
    }

}

这个方法比较重要, 所以全部贴出来了, createAopProxy方法 决定了代理是基于JDK 还是CGlib.

看下JdkDynamicAopProxy:
跟踪到JdkDynamicAopProxy

public Object getProxy(ClassLoader classLoader) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
    }
    Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
    return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

调用Proxy.newProxyInstance新建一个代理实例.

Cglib2AopProxy

public Object getProxy(ClassLoader classLoader) {
    try {
        Class rootClass = this.advised.getTargetClass();
        Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

        Class proxySuperClass = rootClass;
        if (AopUtils.isCglibProxyClass(rootClass)) {
            proxySuperClass = rootClass.getSuperclass();
            Class[] additionalInterfaces = rootClass.getInterfaces();
            for (Class additionalInterface : additionalInterfaces) {
                this.advised.addInterface(additionalInterface);
            }
        }

        // Validate the class, writing log messages as necessary.
        validateClassIfNecessary(proxySuperClass);

        // Configure CGLIB Enhancer...
        Enhancer enhancer = createEnhancer();
        if (classLoader != null) {
            enhancer.setClassLoader(classLoader);
            if (classLoader instanceof SmartClassLoader &&
                    ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                enhancer.setUseCache(false);
            }
        }
        enhancer.setSuperclass(proxySuperClass);
        enhancer.setStrategy(new UndeclaredThrowableStrategy(UndeclaredThrowableException.class));
        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
        enhancer.setInterceptDuringConstruction(false);

        Callback[] callbacks = getCallbacks(rootClass);
        enhancer.setCallbacks(callbacks);
        enhancer.setCallbackFilter(new ProxyCallbackFilter(
                this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));

        Class[] types = new Class[callbacks.length];
        for (int x = 0; x < types.length; x++) {
            types[x] = callbacks[x].getClass();
        }
        enhancer.setCallbackTypes(types);

        // Generate the proxy class and create a proxy instance.
        Object proxy;
        if (this.constructorArgs != null) {
            proxy = enhancer.create(this.constructorArgTypes, this.constructorArgs);
        }
        else {
            proxy = enhancer.create();
        }

        return proxy;
    }
    catch (CodeGenerationException ex) {
        throw new AopConfigException("Could not generate CGLIB subclass of class [" +
                this.advised.getTargetClass() + "]: " +
                "Common causes of this problem include using a final class or a non-visible class",
                ex);
    }
    catch (IllegalArgumentException ex) {
        throw new AopConfigException("Could not generate CGLIB subclass of class [" +
                this.advised.getTargetClass() + "]: " +
                "Common causes of this problem include using a final class or a non-visible class",
                ex);
    }
    catch (Exception ex) {
        // TargetSource.getTarget() failed
        throw new AopConfigException("Unexpected AOP exception", ex);
    }
}

具体就是返回了enhancer.create() 实现以后在研究.

    Author
    XasaKura

    LastMod
    2016-08-23

    License
    查看原文

            spring-aop-执行顺序
            Next

    Powered by Hugo

  |

    Theme -
    Even

    ©

      2017 -
    2018

    XasaKura


text:
package apple.foundation.protocol;

import apple.foundation.NSArray;
import apple.foundation.NSKeyedUnarchiver;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.ann.IsOptional;
import org.moe.natj.objc.ann.ObjCProtocolName;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

@Generated
@Library("Foundation")
@Runtime(ObjCRuntime.class)
@ObjCProtocolName("NSKeyedUnarchiverDelegate")
public interface NSKeyedUnarchiverDelegate {
    /**
     * error handling
     */
    @Generated
    @IsOptional
    @Selector("unarchiver:cannotDecodeObjectOfClassName:originalClasses:")
    default Class unarchiverCannotDecodeObjectOfClassNameOriginalClasses(NSKeyedUnarchiver unarchiver, String name,
            NSArray<String> classNames) {
        throw new java.lang.UnsupportedOperationException();
    }

    /**
     * substitution
     */
    @Generated
    @IsOptional
    @Selector("unarchiver:didDecodeObject:")
    @MappedReturn(ObjCObjectMapper.class)
    default Object unarchiverDidDecodeObject(NSKeyedUnarchiver unarchiver,
            @Mapped(ObjCObjectMapper.class) Object object) {
        throw new java.lang.UnsupportedOperationException();
    }

    /**
     * notification
     */
    @Generated
    @IsOptional
    @Selector("unarchiver:willReplaceObject:withObject:")
    default void unarchiverWillReplaceObjectWithObject(NSKeyedUnarchiver unarchiver,
            @Mapped(ObjCObjectMapper.class) Object object, @Mapped(ObjCObjectMapper.class) Object newObject) {
        throw new java.lang.UnsupportedOperationException();
    }

    /**
     * Notifies the delegate that decoding is about to finish.
     */
    @Generated
    @IsOptional
    @Selector("unarchiverDidFinish:")
    default void unarchiverDidFinish(NSKeyedUnarchiver unarchiver) {
        throw new java.lang.UnsupportedOperationException();
    }

    /**
     * Informs the delegate that the newObject is being substituted for the
     * object. This is also called when the delegate itself is doing/has done
     * the substitution. The delegate may use this method if it is keeping track
     * of the encoded or decoded objects.
     */
    @Generated
    @IsOptional
    @Selector("unarchiverWillFinish:")
    default void unarchiverWillFinish(NSKeyedUnarchiver unarchiver) {
        throw new java.lang.UnsupportedOperationException();
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>DefaultRepositorySelector.AliasRepository Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

DefaultRepositorySelector.AliasRepository Method

 Aliases a repository to an existing repository.

        [Visual Basic]

Public Sub AliasRepository( _
   ByVal repositoryAlias As String, _
   ByVal repositoryTarget As ILoggerRepository _
)

        [C#]

public void AliasRepository(
   string repositoryAlias,
   ILoggerRepository repositoryTarget
);

Parameters

          repositoryAlias

The repository to alias.

          repositoryTarget

The repository that the repository is aliased to.

Remarks

 The repository specified will be aliased to the repository when created. The repository must not already exist.

 When the repository is created it must utilize the same repository type as the repository it is aliased to, otherwise the aliasing will fail.

Exceptions

Exception Type	Condition

ArgumentNullException

repositoryAlias is a null reference
				  (Nothing in Visual Basic).

-or-

repositoryTarget is a null reference
				  (Nothing in Visual Basic).

See Also

DefaultRepositorySelector Class | log4net.Core Namespace
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="AliasRepository method"></param><param name="Keyword" value="AliasRepository method, DefaultRepositorySelector class"></param><param name="Keyword" value="DefaultRepositorySelector.AliasRepository method"></param></object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
Function.RegisterNamespace("Test.Scroller");
[Import("NeededMocks.js")]

[Fixture]
Test.Scroller.PullToRefreshTests=function(){

	var windowMock=Test.Scroller.NeededMocks.getWindowMock();
	windowMock(function(){
		window.__S.plugins={};
		Import("/Users/ndandekar/scroller/src/pull-to-refresh.js");
	});

	[Fixture]
	function initPTR(){

		function mock(plugin,_scroller){
			return Mocks.GetMocks(plugin,{
				"_mergeConfigOptions": function(config){return config;},
				"on": function(event,action){
					action.call(plugin);
				},
				scroller: _scroller,
				ptrIcon: null,
				ptrLabel: null,
				_ptrThreshold: null,
				_ptrSnapTime: null
			});
		}

		[Fact]
		function AppendsPTRcontainerAsFirstChild(){
			var PTRplugin,
				neededMocks,
				actual;

			windowMock(function(){
				PTRplugin = new window.__S.plugins.PullToRefresh();
				PTRplugin.opts = {};

				neededMocks=mock(PTRplugin, Test.Scroller.Dom.GetNode({id:'scroller'},null,
					[Test.Scroller.Dom.GetNode({id:'first-child'})]));

				neededMocks(function(){
					PTRplugin.init();
					actual = PTRplugin.scroller.firstChild.className;
				});
			});

			Assert.Equal('pullToRefresh',actual);
		}

		[Fact]
		function AppendsPTRcontainerAsChild(){
			var PTRplugin,
				neededMocks,
				actual;

			windowMock(function(){
				PTRplugin = new window.__S.plugins.PullToRefresh();
				PTRplugin.opts = {};

				neededMocks=mock(PTRplugin, Test.Scroller.Dom.GetNode({id:'scroller'}));

				neededMocks(function(){
					PTRplugin.init();
					actual = PTRplugin.scroller.firstChild.className;
				});
			});

			Assert.Equal('pullToRefresh',actual);
		}
	}

	[Fixture]
	function TriggerPTR(){

		function mock(plugin){
			return Mocks.GetMocks(plugin,{
				ptrDOM: {classList:{add:function(_class){},remove:function(_class){}}},
				_resetPosition: function(snapTime){},
				ptrLabel: {textContent:''},
				_ptrTriggered: null,
				_ptrLoading: null
			});
		}

		[Fact]
		function ExecutesPTRtrigger(){
			var PTRplugin,
				neededMocks,
				actual=false;

			windowMock(function(){
				PTRplugin = new window.__S.plugins.PullToRefresh();
				PTRplugin.opts = {
					pullToRefreshConfig:{labelUpdate:''},
					onPullToRefresh: function(a,b){
						actual = true;
					}
				};
			});
			neededMocks=mock(PTRplugin);

			neededMocks(function(){
				PTRplugin._triggerPTR();
			});

			Assert.True(actual);
		}

		[Fact]
		function ExecutesPTRtriggerCallback(){
			var PTRplugin,
				neededMocks,
				callback,
				prependMock,
				itemsLength=0,
				expectedPTRloading;

			windowMock(function(){
				PTRplugin = new window.__S.plugins.PullToRefresh();
				PTRplugin.opts = {
					pullToRefreshConfig:{labelUpdate:''},
					onPullToRefresh: function(a,b){
						callback = arguments[0];
					}
				};

				neededMocks=mock(PTRplugin);

				neededMocks(function(){
					PTRplugin._triggerPTR();
					prependMock=Mocks.GetMock(PTRplugin,"prependItems",function(items){
						itemsLength=items.length;
					});
					prependMock(function(){
						callback(0,[1,2]);
					});
					expectedPTRloading = PTRplugin._ptrLoading;
				});
			});

			Assert.True(itemsLength===2 && !expectedPTRloading);
		}

		[Fact]
		function NoPrependIfNoDataProvider(){
			var PTRplugin,
				neededMocks,
				callback,
				prependMock,
				prependNotCalled=true;

			windowMock(function(){
				PTRplugin = new window.__S.plugins.PullToRefresh();
				PTRplugin.opts = {
					pullToRefreshConfig:{labelUpdate:''},
					onPullToRefresh: undefined
				};
				neededMocks=mock(PTRplugin);

				neededMocks(function(){
					prependMock=Mocks.GetMock(PTRplugin,"prependItems",function(items){
						prependNotCalled = false;
					});
					prependMock(function(){
						PTRplugin._triggerPTR();
					});
				});
			});

			Assert.True(prependNotCalled && !PTRplugin._ptrLoading);
		}

	}
}