text:
#ifndef _ASM_TILE_PGALLOC_H
#define _ASM_TILE_PGALLOC_H

#include <linux/threads.h>
#include <linux/mm.h>
#include <linux/mmzone.h>
#include <asm/fixmap.h>
#include <asm/page.h>
#include <hv/hypervisor.h>

/* Bits for the size of the second-level page table. */
#define L2_KERNEL_PGTABLE_SHIFT _HV_LOG2_L2_SIZE(HPAGE_SHIFT, PAGE_SHIFT)

/* How big is a kernel L2 page table? */
#define L2_KERNEL_PGTABLE_SIZE (1UL << L2_KERNEL_PGTABLE_SHIFT)

/* We currently allocate user L2 page tables by page (unlike kernel L2s). */
#if L2_KERNEL_PGTABLE_SHIFT < PAGE_SHIFT
#define L2_USER_PGTABLE_SHIFT PAGE_SHIFT
#else
#define L2_USER_PGTABLE_SHIFT L2_KERNEL_PGTABLE_SHIFT
#endif

/* How many pages do we need, as an "order", for a user L2 page table? */
#define L2_USER_PGTABLE_ORDER (L2_USER_PGTABLE_SHIFT - PAGE_SHIFT)

static inline void set_pmd(pmd_t *pmdp, pmd_t pmd)
{
#ifdef CONFIG_64BIT
	set_pte(pmdp, pmd);
#else
	set_pte(&pmdp->pud.pgd, pmd.pud.pgd);
#endif
}

static inline void pmd_populate_kernel(struct mm_struct *mm,
				       pmd_t *pmd, pte_t *ptep)
{
	set_pmd(pmd, ptfn_pmd(HV_CPA_TO_PTFN(__pa(ptep)),
			      __pgprot(_PAGE_PRESENT)));
}

static inline void pmd_populate(struct mm_struct *mm, pmd_t *pmd,
				pgtable_t page)
{
	set_pmd(pmd, ptfn_pmd(HV_CPA_TO_PTFN(PFN_PHYS(page_to_pfn(page))),
			      __pgprot(_PAGE_PRESENT)));
}

/*
 * Allocate and free page tables.
 */

extern pgd_t *pgd_alloc(struct mm_struct *mm);
extern void pgd_free(struct mm_struct *mm, pgd_t *pgd);

extern pgtable_t pgtable_alloc_one(struct mm_struct *mm, unsigned long address,
				   int order);
extern void pgtable_free(struct mm_struct *mm, struct page *pte, int order);

static inline pgtable_t pte_alloc_one(struct mm_struct *mm,
				      unsigned long address)
{
	return pgtable_alloc_one(mm, address, L2_USER_PGTABLE_ORDER);
}

static inline void pte_free(struct mm_struct *mm, struct page *pte)
{
	pgtable_free(mm, pte, L2_USER_PGTABLE_ORDER);
}

#define pmd_pgtable(pmd) pmd_page(pmd)

static inline pte_t *
pte_alloc_one_kernel(struct mm_struct *mm, unsigned long address)
{
	return pfn_to_kaddr(page_to_pfn(pte_alloc_one(mm, address)));
}

static inline void pte_free_kernel(struct mm_struct *mm, pte_t *pte)
{
	BUG_ON((unsigned long)pte & (PAGE_SIZE-1));
	pte_free(mm, virt_to_page(pte));
}

extern void __pgtable_free_tlb(struct mmu_gather *tlb, struct page *pte,
			       unsigned long address, int order);
static inline void __pte_free_tlb(struct mmu_gather *tlb, struct page *pte,
				  unsigned long address)
{
	__pgtable_free_tlb(tlb, pte, address, L2_USER_PGTABLE_ORDER);
}

#define check_pgt_cache()	do { } while (0)

/*
 * Get the small-page pte_t lowmem entry for a given pfn.
 * This may or may not be in use, depending on whether the initial
 * huge-page entry for the page has already been shattered.
 */
pte_t *get_prealloc_pte(unsigned long pfn);

/* During init, we can shatter kernel huge pages if needed. */
void shatter_pmd(pmd_t *pmd);

/* After init, a more complex technique is required. */
void shatter_huge_page(unsigned long addr);

#ifdef __tilegx__

#define pud_populate(mm, pud, pmd) \
  pmd_populate_kernel((mm), (pmd_t *)(pud), (pte_t *)(pmd))

/* Bits for the size of the L1 (intermediate) page table. */
#define L1_KERNEL_PGTABLE_SHIFT _HV_LOG2_L1_SIZE(HPAGE_SHIFT)

/* How big is a kernel L2 page table? */
#define L1_KERNEL_PGTABLE_SIZE (1UL << L1_KERNEL_PGTABLE_SHIFT)

/* We currently allocate L1 page tables by page. */
#if L1_KERNEL_PGTABLE_SHIFT < PAGE_SHIFT
#define L1_USER_PGTABLE_SHIFT PAGE_SHIFT
#else
#define L1_USER_PGTABLE_SHIFT L1_KERNEL_PGTABLE_SHIFT
#endif

/* How many pages do we need, as an "order", for an L1 page table? */
#define L1_USER_PGTABLE_ORDER (L1_USER_PGTABLE_SHIFT - PAGE_SHIFT)

static inline pmd_t *pmd_alloc_one(struct mm_struct *mm, unsigned long address)
{
	struct page *p = pgtable_alloc_one(mm, address, L1_USER_PGTABLE_ORDER);
	return (pmd_t *)page_to_virt(p);
}

static inline void pmd_free(struct mm_struct *mm, pmd_t *pmdp)
{
	pgtable_free(mm, virt_to_page(pmdp), L1_USER_PGTABLE_ORDER);
}

static inline void __pmd_free_tlb(struct mmu_gather *tlb, pmd_t *pmdp,
				  unsigned long address)
{
	__pgtable_free_tlb(tlb, virt_to_page(pmdp), address,
			   L1_USER_PGTABLE_ORDER);
}

#endif /* __tilegx__ */

#endif /* _ASM_TILE_PGALLOC_H */


text:
using org.xmlvm;
namespace org.w3c.dom.html2 {
public abstract class _iHTMLAnchorElement {

} // end of abstract class: _iHTMLAnchorElement

public interface HTMLAnchorElement: global::org.w3c.dom.html2.HTMLElement {
 global::System.Object getAccessKey();

 void setAccessKey(global::java.lang.String n1);

 global::System.Object getCharset();

 void setCharset(global::java.lang.String n1);

 global::System.Object getCoords();

 void setCoords(global::java.lang.String n1);

 global::System.Object getHref();

 void setHref(global::java.lang.String n1);

 global::System.Object getHreflang();

 void setHreflang(global::java.lang.String n1);

 global::System.Object getName();

 void setName(global::java.lang.String n1);

 global::System.Object getRel();

 void setRel(global::java.lang.String n1);

 global::System.Object getRev();

 void setRev(global::java.lang.String n1);

 global::System.Object getShape();

 void setShape(global::java.lang.String n1);

 int getTabIndex();

 void setTabIndex(int n1);

 global::System.Object getTarget();

 void setTarget(global::java.lang.String n1);

 global::System.Object getType();

 void setType(global::java.lang.String n1);

 void blur();

 void focus();

new  global::System.Object appendChild(global::org.w3c.dom.Node n1);

new  global::System.Object cloneNode(bool n1);

new  short compareDocumentPosition(global::org.w3c.dom.Node n1);

new  global::System.Object getAttributeNS(global::java.lang.String n1, global::java.lang.String n2);

new  global::System.Object getAttributeNodeNS(global::java.lang.String n1, global::java.lang.String n2);

new  global::System.Object getAttributeNode(global::java.lang.String n1);

new  global::System.Object getAttribute(global::java.lang.String n1);

new  global::System.Object getAttributes();

new  global::System.Object getBaseURI();

new  global::System.Object getChildNodes();

new  global::System.Object getClassName();

new  global::System.Object getDir();

new  global::System.Object getElementsByTagNameNS(global::java.lang.String n1, global::java.lang.String n2);

new  global::System.Object getElementsByTagName(global::java.lang.String n1);

new  global::System.Object getFeature(global::java.lang.String n1, global::java.lang.String n2);

new  global::System.Object getFirstChild();

new  global::System.Object getId();

new  global::System.Object getLang();

new  global::System.Object getLastChild();

new  global::System.Object getLocalName();

new  global::System.Object getNamespaceURI();

new  global::System.Object getNextSibling();

new  global::System.Object getNodeName();

new  short getNodeType();

new  global::System.Object getNodeValue();

new  global::System.Object getOwnerDocument();

new  global::System.Object getParentNode();

new  global::System.Object getPrefix();

new  global::System.Object getPreviousSibling();

new  global::System.Object getSchemaTypeInfo();

new  global::System.Object getTagName();

new  global::System.Object getTextContent();

new  global::System.Object getTitle();

new  global::System.Object getUserData(global::java.lang.String n1);

new  bool hasAttributeNS(global::java.lang.String n1, global::java.lang.String n2);

new  bool hasAttribute(global::java.lang.String n1);

new  bool hasAttributes();

new  bool hasChildNodes();

new  global::System.Object insertBefore(global::org.w3c.dom.Node n1, global::org.w3c.dom.Node n2);

new  bool isDefaultNamespace(global::java.lang.String n1);

new  bool isEqualNode(global::org.w3c.dom.Node n1);

new  bool isSameNode(global::org.w3c.dom.Node n1);

new  bool isSupported(global::java.lang.String n1, global::java.lang.String n2);

new  global::System.Object lookupNamespaceURI(global::java.lang.String n1);

new  global::System.Object lookupPrefix(global::java.lang.String n1);

new  void normalize();

new  void removeAttributeNS(global::java.lang.String n1, global::java.lang.String n2);

new  global::System.Object removeAttributeNode(global::org.w3c.dom.Attr n1);

new  void removeAttribute(global::java.lang.String n1);

new  global::System.Object removeChild(global::org.w3c.dom.Node n1);

new  global::System.Object replaceChild(global::org.w3c.dom.Node n1, global::org.w3c.dom.Node n2);

new  void setAttributeNS(global::java.lang.String n1, global::java.lang.String n2, global::java.lang.String n3);

new  global::System.Object setAttributeNodeNS(global::org.w3c.dom.Attr n1);

new  global::System.Object setAttributeNode(global::org.w3c.dom.Attr n1);

new  void setAttribute(global::java.lang.String n1, global::java.lang.String n2);

new  void setClassName(global::java.lang.String n1);

new  void setDir(global::java.lang.String n1);

new  void setIdAttributeNS(global::java.lang.String n1, global::java.lang.String n2, bool n3);

new  void setIdAttributeNode(global::org.w3c.dom.Attr n1, bool n2);

new  void setIdAttribute(global::java.lang.String n1, bool n2);

new  void setId(global::java.lang.String n1);

new  void setLang(global::java.lang.String n1);

new  void setNodeValue(global::java.lang.String n1);

new  void setPrefix(global::java.lang.String n1);

new  void setTextContent(global::java.lang.String n1);

new  void setTitle(global::java.lang.String n1);

new  global::System.Object setUserData(global::java.lang.String n1, global::java.lang.Object n2, global::org.w3c.dom.UserDataHandler n3);

//XMLVM_BEGIN_WRAPPER[org.w3c.dom.html2.HTMLAnchorElement]
//XMLVM_END_WRAPPER[org.w3c.dom.html2.HTMLAnchorElement]

} // end of interface: HTMLAnchorElement

} // end of namespace: org.w3c.dom.html2

redpajama_set_name: RedPajamaGithub


text:
package sendowl

import (
	"fmt"

	"golang.org/x/net/context"
)

// ListProductsRequest is an API representation of a list products request.
type ListProductsRequest struct {
	PerPage int
	Page    int
}

// ListProductsResponse is an API representation of a list products response.
type ListProductsResponse []ListProductsResponseItem

func (r *ListProductsResponse) Items() []ListProductsResponseItem {
	return []ListProductsResponseItem(*r)
}

type ListProductsResponseItem struct {
	Product `json:"product"`
}

// ListProducts uses req to list a products, returning a
// ListProductsResponse and non-nil error if there was a problem.
func (c Client) ListProducts(ctx context.Context, req ListProductsRequest) (*ListProductsResponse, error) {
	u := "./products"
	if req.PerPage > 0 || req.Page > 0 {
		u = fmt.Sprintf("%s?per_page=%d&page=%d", u, req.PerPage, req.Page)
	}
	r, err := c.newRequest("GET", u, nil)
	if err != nil {
		return nil, err
	}
	var resp ListProductsResponse
	if err := c.do(ctx, r, &resp); err != nil {
		return nil, err
	}
	return &resp, nil
}


text:
import {SuiteModuleBuilder} from 'ember-runtime/tests/suites/suite';
import {Freezable} from 'ember-runtime/mixins/freezable';
import {get} from 'ember-metal/property_get';

var suite = SuiteModuleBuilder.create();

suite.module('frozenCopy');

suite.test('frozen objects should return same instance', function() {
  var obj, copy;

  obj = this.newObject();
  if (get(this, 'shouldBeFreezable')) {
    expectDeprecation('`frozenCopy` is deprecated, use Object.freeze instead.');

    ok(!Freezable || Freezable.detect(obj), 'object should be freezable');

    copy = obj.frozenCopy();
    ok(this.isEqual(obj, copy), 'new copy should be equal');
    ok(get(copy, 'isFrozen'), 'returned value should be frozen');

    copy = obj.freeze().frozenCopy();
    equal(copy, obj, 'returns frozen object should be same');
    ok(get(copy, 'isFrozen'), 'returned object should be frozen');
  } else {
    ok(!Freezable || !Freezable.detect(obj), 'object should not be freezable');
  }
});

export default suite;


text:
#include "sys.h"
#include "log.h"

/*
 The rpi requires you to translate requests between _bus_ and _physical_
 locations in memory
 */
volatile uint phys_to_bus(uint p) {
    return (uint)(p + ARM_BUS_LOCATION);
}

volatile uint bus_to_phys(uint p) {
    if(p > ARM_BUS_LOCATION) {
        return (uint)(p - ARM_BUS_LOCATION);
    }
    return (uint)p;
}

/*
 Put up a memory "barrier" in order to properly function with some
 of the hardware */
void mem_barrier() {
    asm volatile("mcr p15, 0, ip, c7, c5, 0");
    asm volatile("mcr p15, 0, ip, c7, c5, 6");
    asm volatile("mcr p15, 0, ip, c7, c5, 4");
    asm volatile("mcr p15, 0, ip, c7, c5, 4");
}

/*
 Return the mailbox status */
uint MailboxStatus() {
    volatile uint *p = (volatile uint*)(ARM_MAIL_BASE + ARM_MAIL_STATUS);
    return (uint)(*p);
}

/*
 Write 'data' to the mailbox on a specific channel */
void MailboxWrite(char channel, uint data) {
    // We can not write if the mailbox is full
    while(MailboxStatus() & MAIL_FULL);

    mem_barrier();
    *(volatile uint*)(ARM_MAIL_BASE + ARM_MAIL_WRITE) = channel | (data & 0xFFFFFFF0);
    mem_barrier();
}

/*
 Read data from the mailbox in a specific channel */
uint MailboxRead(char channel) {
    uint ret = 0, i;
    for(i = 0;;) {
        // Can not read from an empty mailbox now, can we?
        while(MailboxStatus() & MAIL_EMPTY) {
            if(++i >= (1 << 20)) {
                //TODO: Add properly error handling
                return 0xFFFFFFFF;
            }
        }

        mem_barrier();
        ret = *(volatile uint*)(ARM_MAIL_BASE);
        mem_barrier();

        // Check if it's the correct channel
        if((ret & 0x0000000F) == channel) {
            break;
        }
    }

    /* Note how we strip of the last 4 bits, which actually
       is the channel */
    return (ret & 0xFFFFFFF0);
}

/*
  Request a framebuffer from the GPU */
gpu_t *RequestFramebuffer(uint w, uint h) {
    // Create our request structure
    gpu_t *req = (gpu_t*)KERNEL_FB_LOC;
    req->width = w;
    req->height = h;
    req->virtual_width = w;
    req->virtual_height = h;
    req->pitch = 0; //Returned by GPU
    req->depth = 24;
    req->x_offset = req->y_offset = 0;
    req->pointer = 0;
    req->size = 0;

    // Convert to bus-addr
    uint reqAddr = phys_to_bus((uint)req);
    // Write the address to the GPU through the mailbox
    MailboxWrite(1, reqAddr);

    // Read the response, properly ...
    uint response = 0xFF, t = 10000;
    while(response != 0 && --t > 0) {
        response = MailboxRead(1);
    }

    // Did the GPU response all to slow?
    if(t <= 0) {
        log_write(LOG_ERR, "GPU: Could not acquire framebuffer, returning false-positive. Hardware were too slow to answer.\n");
        return req;
    }

    // Is the pointer returned actually valid?
    if(!req->pointer || !req->pitch) {
        log_write(LOG_ERR, "GPU: Could not acquire framebuffer, returning false-positive. Hardware did not seem to deliver an answer to framebuffer request.\n");
        return req;
    }

    // Convert the GPU bus address into a proper physical one
    req->pointer = bus_to_phys(req->pointer);

    /* Return the request, properly filled out and accepted
       by the GPU */
    return req;
}


text:
pub use foo2::Bar2;
mod foo {
    pub struct Bar; //~ ERROR: code is never used
}

mod foo2 {
    pub struct Bar2;
}

pub static pub_static: int = 0;
static priv_static: int = 0; //~ ERROR: code is never used
static used_static: int = 0;
pub static used_static2: int = used_static;

pub fn pub_fn() {
    used_fn();
    let used_struct1 = UsedStruct1 { x: 1 };
    let used_struct2 = UsedStruct2(1);
    let used_struct3 = UsedStruct3;
    let e = foo3;
    SemiUsedStruct::la_la_la();

}
fn priv_fn() { //~ ERROR: code is never used
    let unused_struct = PrivStruct;
}
fn used_fn() {}

pub type typ = ~UsedStruct4;
pub struct PubStruct();
struct PrivStruct; //~ ERROR: code is never used
struct UsedStruct1 { x: int }
struct UsedStruct2(int);
struct UsedStruct3;
struct UsedStruct4;
// this struct is never used directly, but its method is, so we don't want
// to warn it
struct SemiUsedStruct;
impl SemiUsedStruct {
    fn la_la_la() {}
}

pub enum pub_enum { foo1, bar1 }
enum priv_enum { foo2, bar2 } //~ ERROR: code is never used
enum used_enum { foo3, bar3 }

fn foo() { //~ ERROR: code is never used
    bar();
    let unused_enum = foo2;
}

fn bar() { //~ ERROR: code is never used
    foo();
}


text:
package noop

import (
	"context"
	"net"

	"v2ray.com/core/common"
)

type NoOpHeader struct{}

func (NoOpHeader) Size() int32 {
	return 0
}

// Serialize implements PacketHeader.
func (NoOpHeader) Serialize([]byte) {}

func NewNoOpHeader(context.Context, interface{}) (interface{}, error) {
	return NoOpHeader{}, nil
}

type NoOpConnectionHeader struct{}

func (NoOpConnectionHeader) Client(conn net.Conn) net.Conn {
	return conn
}

func (NoOpConnectionHeader) Server(conn net.Conn) net.Conn {
	return conn
}

func NewNoOpConnectionHeader(context.Context, interface{}) (interface{}, error) {
	return NoOpConnectionHeader{}, nil
}

func init() {
	common.Must(common.RegisterConfig((*Config)(nil), NewNoOpHeader))
	common.Must(common.RegisterConfig((*ConnectionConfig)(nil), NewNoOpConnectionHeader))
}


text:
from .connected import *
from .strongly_connected import *
from .weakly_connected import *
from .attracting import *
from .biconnected import *
from .semiconnected import *


text:
// The MIT License
//
// Copyright (c) 2017 TruRating Ltd. https://www.trurating.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TruRating.Dto.TruService.V220;
using TruRating.TruModule.Device;
using TruRating.TruModule.Messages;

namespace TruRating.TruModule.Tests.Unit.Messages
{
    [TestClass]
    public class TruServiceMessageFactoryTests :MsTestsContext<TruServiceMessageFactory>
    {
        [TestMethod]
        public void ItShouldAssembleRequestRating()
        {
            Assert.IsNotNull(Sut.AssembleRequestRating(MockOf<RequestParams>(), new RequestRating()));
        }
        [TestMethod]
        public void ItShouldAssembleRequestQuery()
        {
            Assert.IsNotNull(Sut.AssemblyRequestQuery(MockOf<RequestParams>(), MockOf<IDevice>(), MockOf<IReceiptManager>(), true));
        }

        [TestMethod]
        public void ItShouldAssembleRequestQuestion()
        {
            Assert.IsNotNull(Sut.AssembleRequestQuestion(MockOf<RequestParams>(), MockOf<IDevice>(), MockOf<IReceiptManager>(),Trigger.CARDINSERTION));
        }

        [TestMethod]
        public void ItShouldAssembleRequestTransaction()
        {
            Assert.IsNotNull(Sut.AssembleRequestTransaction(MockOf<RequestParams>(), new RequestTransaction()));
        }

        [TestMethod]
        public void ItShouldAssembleRequestPosEvent()
        {
            Assert.IsNotNull(Sut.AssembleRequestPosEvent(new PosParams(), new RequestPosEvent()));
        }

        [TestMethod]
        public void ItShouldAssembleRequestPosEventList()
        {
            Assert.IsNotNull(Sut.AssembleRequestPosEventList(MockOf<RequestParams>(), new RequestPosEventList()));
        }

        [TestMethod]
        public void ItShouldAssembleRequestLookup()
        {
            Assert.IsNotNull(Sut.AssembleRequestLookup(MockOf<RequestParams>(), MockOf<IDevice>(), MockOf<IReceiptManager>(), LookupName.SECTORNODE));
        }

        [TestMethod]
        public void ItShouldAssembleRequestActivateForm()
        {
            Assert.IsNotNull(Sut.AssembleRequestActivate(MockOf<RequestParams>(), MockOf<IDevice>(), MockOf<IReceiptManager>(),0,"",PaymentInstant.PAYBEFORE,"","","","","",""));
        }

        [TestMethod]
        public void ItShouldAssembleRequestActivateCode()
        {
            Assert.IsNotNull(Sut.AssembleRequestActivate(MockOf<RequestParams>(), MockOf<IDevice>(), MockOf<IReceiptManager>(),""));
        }
    }
}


text:
package com.base.game.entity.staticEntity;

import java.awt.Graphics;

import com.base.game.Animation;
import com.base.game.Assets;
import com.base.game.Handler;
import com.base.game.entity.Creature;
import com.base.game.entity.eventEntity.Energy;
import com.base.game.tiles.Tile;

public class Boulder extends Breakables
{
	public Boulder(Handler handler, float x, float y, int layer, int level) {
		super(handler, x, y, layer, Tile.TILE_WIDTH, Tile.TILE_HEIGHT, level);
		bounds.x = 18;
		bounds.y = 30;
		bounds.width = 30;
		bounds.height = 22;

		currentAnimation = new Animation(150, Assets.boulder, 1);
	}

	@Override
	public void render(Graphics g) {
		g.drawImage(currentAnimation.getCurrentFrame(), (int) (x - handler.getCamera().getxOffset()),(int) (y - handler.getCamera().getyOffset()), width, height, null);
	}
}


text:
/**
 * This code is generated using [[https://www.scala-sbt.org/contraband/ sbt-contraband]].
 */

// DO NOT EDIT MANUALLY
package sbt.protocol.codec
import _root_.sjsonnew.{ Unbuilder, Builder, JsonFormat, deserializationError }
trait AttachFormats { self: sjsonnew.BasicJsonProtocol =>
implicit lazy val AttachFormat: JsonFormat[sbt.protocol.Attach] = new JsonFormat[sbt.protocol.Attach] {
  override def read[J](__jsOpt: Option[J], unbuilder: Unbuilder[J]): sbt.protocol.Attach = {
    __jsOpt match {
      case Some(__js) =>
      unbuilder.beginObject(__js)
      val interactive = unbuilder.readField[Boolean]("interactive")
      unbuilder.endObject()
      sbt.protocol.Attach(interactive)
      case None =>
      deserializationError("Expected JsObject but found None")
    }
  }
  override def write[J](obj: sbt.protocol.Attach, builder: Builder[J]): Unit = {
    builder.beginObject()
    builder.addField("interactive", obj.interactive)
    builder.endObject()
  }
}
}


text:
<?php

namespace MailModuleTest\Mail\Transport;

use MailModule\Mail\Transport\MandrillOptions;

/**
 * Class MandrillOptionsTest
 *
 * @author Lorenzo Fontana <fontanalorenzo@me.com>
 */
class MandrillOptionsTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var MandrillOptions
     */
    protected $mandrillOptions;

    protected function setUp()
    {
        $config = [
            'apikey'      => 'MYSECRETMANDRILLKEY',
            'sub_account' => 'my-optional-subaccount-if-any'
        ];
        $this->mandrillOptions = new MandrillOptions($config);
    }

    public function testGetApikey()
    {
        $this->assertEquals('MYSECRETMANDRILLKEY', $this->mandrillOptions->getApikey());
    }

    public function testSetApikey()
    {
        $this->mandrillOptions->setApikey('ANOTHERMANDRILLKEY');
        $this->assertEquals('ANOTHERMANDRILLKEY', $this->mandrillOptions->getApikey());
    }

    public function testGetSubAccount()
    {
        $this->assertEquals('my-optional-subaccount-if-any', $this->mandrillOptions->getSubAccount());
    }

    public function testSetSubAccount()
    {
        $this->mandrillOptions->setSubAccount('another-subaccount');
        $this->assertEquals('another-subaccount', $this->mandrillOptions->getSubAccount());
    }
}


text:
ChaseState::ChaseState(Zombie* _ownerZombie) : ZombieState(_ownerZombie)
{
}

ChaseState::~ChaseState()
{
}

void ChaseState::Update(float _deltaTime)
{
		//chase the player by just going in its direction
		glm::vec2 directionToPlayer = glm::normalize(m_zombie->m_player.lock()->GetCenterPos() - m_zombie->GetCenterPos());
		m_zombie->m_direction = directionToPlayer;
		m_zombie->m_worldPos += directionToPlayer * m_zombie->m_movementSpeed * _deltaTime;

		if (!m_zombie->CollideWithAgent(m_zombie->m_player.lock().get()))
		{
				//collision handle
		}

		if (!CheckForPlayer())
		{
				m_zombie->m_stateManager.SetState(new AlertState(m_zombie));
		}
}


text:
import { Component, ViewChild } from "@angular/core";
import { ReCaptchaComponent } from 'angular2-recaptcha';
import { constGlobals } from "../../../shared/globals";

import { SeoService } from "../../../shared/seo.service";
import { NewPatientService} from "./new-patient.service";

// Enables jQuery
declare var $:any;

@Component({
    selector: "tmj-new-patient",
    templateUrl: "new-patient.html",
    styles: [`
        h2 { font-size: 24px; }

        #section5 #s5columns label {
            padding-top: 6px;
            font-weight: normal;
        }

        .control-label { vertical-align: middle; }
    `],
    providers: [NewPatientService, SeoService]
})
export class NewPatientComponent {
    @ViewChild(ReCaptchaComponent) captcha: ReCaptchaComponent;
    bower_components = constGlobals.bower_components;
    objUser; // holds user contents

    constructor(public newPatientService: NewPatientService, private seoService: SeoService) {
        this.objUser = newPatientService.objUser;

        // SEO settings.
        seoService.setTitle("Patient Health Questionnaire | TMJ & Sleep Therapy Centre of San Francisco");
        seoService.setMetaDescription("Patient Health Questionnaire for TMJ & Sleep Therapy Centre of San Francisco.");
    } // constructor()

    // Send to REST endpoint.
    mdSend() {
        // Disable submit button and indicate "Please wait...".
        document.getElementById("btnSubmit").textContent = "Please Wait...";
        document.getElementById("btnSubmit").classList.remove("btn-primary");
        document.getElementById("btnSubmit").classList.add("btn-info");
        (<HTMLInputElement> document.getElementById("btnSubmit")).disabled = true;

        // Attempt to send email.
        this.newPatientService.mdSendData(this.objUser)
            .subscribe(data => {
                if (data.sent === "yes") {
                    // Success
                    document.getElementById("btnSubmit").textContent = "Email Sent!";
                    document.getElementById("btnSubmit").classList.remove("btn-info");
                    document.getElementById("btnSubmit").classList.add("btn-success");
                    (<HTMLInputElement> document.getElementById("btnSubmit")).disabled = true;
                } else {
                    // Something went wrong.
                    document.getElementById("btnSubmit").textContent = "Please try again.";
                    document.getElementById("btnSubmit").classList.remove("btn-info");
                    document.getElementById("btnSubmit").classList.add("btn-danger");
                    (<HTMLInputElement> document.getElementById("btnSubmit")).disabled = false;

                    // Reset captcha.
                    this.objUser.googleResponse = null;
                    this.captcha.reset();
                } // else
            }) // subscribe()
        ; // sendEmailService.mdSendData()
    } // mdSend()

    // Handle the captcha response and save to objUserDetails.captchaResponse
    mdCaptchaHandle(strResponse: string): void {
        this.objUser.googleResponse = strResponse;
    } // mdCaptchaHandle(response)

    // Handles expired captchas.
    mdCaptchaExpired(): void {
        this.objUser.googleResponse = null;
        this.captcha.reset();
    }
} // NewPatientComponent


text:
<?php

/**
 * @namespace
 */

namespace Solarium\QueryType\Select\Result\MoreLikeThis;

use Solarium\QueryType\Select\Result\DocumentInterface;

/**
 * Select component morelikethis result item.
 */
class Result implements \IteratorAggregate, \Countable
{
    /**
     * Document instances array.
     *
     * @var array
     */
    protected $documents;

    /**
     * Solr numFound.
     *
     * This is NOT the number of MLT documents fetched from Solr!
     *
     * @var int
     */
    protected $numFound;

    /**
     * Maximum score in this MLT set.
     *
     * @var float
     */
    protected $maximumScore;

    /**
     * Constructor.
     *
     * @param int        $numFound
     * @param float|null $maxScore
     * @param array      $documents
     */
    public function __construct($numFound, $maxScore, $documents)
    {
        $this->numFound = $numFound;
        $this->maximumScore = $maxScore;
        $this->documents = $documents;
    }

    /**
     * get Solr numFound.
     *
     * Returns the number of MLT documents found by Solr (this is NOT the
     * number of documents fetched from Solr!)
     *
     * @return int
     */
    public function getNumFound()
    {
        return $this->numFound;
    }

    /**
     * Get maximum score in the MLT document set.
     *
     * @return float
     */
    public function getMaximumScore()
    {
        return $this->maximumScore;
    }

    /**
     * Get all documents.
     *
     * @return DocumentInterface[]
     */
    public function getDocuments()
    {
        return $this->documents;
    }

    /**
     * IteratorAggregate implementation.
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->documents);
    }

    /**
     * Countable implementation.
     *
     * @return int
     */
    public function count()
    {
        return count($this->documents);
    }
}


text:
 - Reset
 - Bootstrap
 - Responsive
 - CSS, SASS, LESS


text:
namespace base {
class MessageLoop;
}

namespace printing {

class PrintJobWorker;
class PrintSettings;

class PrintJobWorkerOwner
    : public base::RefCountedThreadSafe<PrintJobWorkerOwner> {
 public:
  // Finishes the initialization began by PrintJobWorker::GetSettings().
  // Creates a new PrintedDocument if necessary. Solely meant to be called by
  // PrintJobWorker.
  virtual void GetSettingsDone(const PrintSettings& new_settings,
                               PrintingContext::Result result) = 0;

  // Detach the PrintJobWorker associated to this object.
  virtual PrintJobWorker* DetachWorker(PrintJobWorkerOwner* new_owner) = 0;

  // Retrieves the message loop that is expected to process GetSettingsDone.
  virtual base::MessageLoop* message_loop() = 0;

  // Access the current settings.
  virtual const PrintSettings& settings() const = 0;

  // Cookie uniquely identifying the PrintedDocument and/or loaded settings.
  virtual int cookie() const = 0;

 protected:
  friend class base::RefCountedThreadSafe<PrintJobWorkerOwner>;

  virtual ~PrintJobWorkerOwner() {}
};

}  // namespace printing

#endif  // CHROME_BROWSER_PRINTING_PRINT_JOB_WORKER_OWNER_H__


text:
module HttpState
  class Base
    def initialize
      @actions = {}
      yield self if block_given?
    end

    def on(action, &block)
      @actions[action] = [] unless @actions.has_key?(action)
      @actions[action] << block
    end

    def add_next_state(state_class, parameters = {})
      @actions[:new_state_added].each do |action|
        action.call(state_class, parameters)
      end
    end

    def save_next_state(state_class)
      @actions[:next_state_saved].each do |action|
        action.call(state_class)
      end
    end

    def handle

    end

    def cleanup

    end
  end

end


text:
using System.Collections.Generic;
using System.Linq;
using OpenRasta.Sina;
using Should;

namespace Tests
{
    public static class TestExtensions
    {
        public static void ShouldAllEqual<T>(this IEnumerable<T> sources, T expectedValue)
        {
            foreach (var value in sources)
                value.ShouldEqual(expectedValue);
        }

        public static void ShouldMatch<T>(this Match<T> match, T expectedValue, int? expectedPosition = null, int? expectedLength = null)
        {
            match.IsMatch.ShouldBeTrue("Rule should have matched but did not.");
            match.Value.ShouldEqual(expectedValue);
            if (expectedPosition.HasValue)
                match.Position.ShouldEqual((int)expectedPosition);
            if (expectedLength.HasValue)
                match.Length.ShouldEqual((int)expectedLength);
        }

        public static void ShouldMatch<T>(this Match<IEnumerable<T>> match, int? expectedPosition = null, int? expectedLength = null, params T[] expectedValue)
        {
            match.IsMatch.ShouldBeTrue("Rule should have matched but did not.");
            match.Value.SequenceEqual(expectedValue).ShouldBeTrue();
            if (expectedPosition.HasValue)
                match.Position.ShouldEqual((int)expectedPosition);
            if (expectedLength.HasValue)
                match.Length.ShouldEqual((int)expectedLength);
        }

        public static void ShouldNotMatch<T>(this Match<T> match)
        {
            match.IsMatch.ShouldBeFalse("Rule should not have matched.");
        }
    }
}


text:
package org.apache.nutch.service.resources;

import java.util.Map;
import java.util.Set;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.nutch.service.model.request.NutchConfig;
import com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures;
import com.fasterxml.jackson.databind.SerializationFeature;

@Path("/config")
public class ConfigResource extends AbstractResource{

  public static final String DEFAULT = "default";

  @GET
  @Path("/")
	@JacksonFeatures(serializationEnable =  { SerializationFeature.INDENT_OUTPUT })
  public Set<String> getConfigs() {
    return configManager.list();
  }

  @GET
  @Path("/{configId}")
	@JacksonFeatures(serializationEnable =  { SerializationFeature.INDENT_OUTPUT })
  public Map<String, String> getConfig(@PathParam("configId") String configId) {
    return configManager.getAsMap(configId);
  }

  @GET
  @Path("/{configId}/{propertyId}")
	@JacksonFeatures(serializationEnable =  { SerializationFeature.INDENT_OUTPUT })
  public String getProperty(@PathParam("configId") String configId,
      @PathParam("propertyId") String propertyId) {
    return configManager.getAsMap(configId).get(propertyId);
  }

  @DELETE
  @Path("/{configId}")
  public void deleteConfig(@PathParam("configId") String configId) {
    configManager.delete(configId);
  }

  @POST
  @Path("/{configId}")
  @Consumes(MediaType.APPLICATION_JSON)
  public String createConfig(NutchConfig newConfig) {
    if (newConfig == null) {
      throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
          .entity("Nutch configuration cannot be empty!").build());
    }
    return configManager.create(newConfig);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;

namespace BeOpen.Devices.ItLineScoreboards.NetworkCommunication.Packets
{
    internal class GetRstrData : Data
    {
        private readonly byte[] _indexes = new byte[8];

        public GetRstrData([NotNull] IEnumerable<byte> indexes)
        {
            if (indexes == null)
            {
                throw new ArgumentNullException(nameof(indexes));
            }
            var enumerable = indexes as byte[] ?? indexes.ToArray();
            if (enumerable.Length > 8)
            {
                throw new ArgumentException($"{nameof(indexes)} count is greater than 8.");
            }
            enumerable.CopyTo(_indexes, 0);
            for (int index = enumerable.Length; index < 8; index++)
            {
                _indexes[index] = 255;
            }
        }

        public override byte[] ToByteArray()
        {
            return _indexes;
        }
    }
}


text:
<?php

namespace Plugin\Example;
use Oculus\Engine\Container;
use Oculus\Engine\Plugin;
use Oculus\Service\PluginServiceModel;

class Register extends Plugin {

    public function __construct(Container $app) {
        parent::__construct($app);
        parent::setPlugin('example');
    }

    public function add() {
        $model = new PluginServiceModel($this->app);

        // set all event handlers
        $model->setEventHandler('admin_edit_product', array(
            'plugin' => 'example',
            'file'   => 'admin/events/adminevent',
            'method' => 'editProduct'
        ));

        // set all hooks handlers
        $model->setHookHandler('admin_controller', array(
            'class'    => 'tool/test',
            'method'   => 'index',
            'type'     => 'post',
            'plugin'   => 'example',
            'file'     => 'admin/hooks/controllerhooks',
            'callback' => 'exampleHook',
            'args'     => array(
                'heading_title' => 'Example Test Page',
                'item_title'    => 'Item title'
            )
        ));

        $model->setHookHandler('admin_controller', array(
            'class'    => 'tool/test',
            'method'   => 'index',
            'type'     => 'pre',
            'plugin'   => 'example',
            'file'     => 'admin/hooks/controllerhooks',
            'callback' => 'preHook'
        ));
    }

    public function remove() {
        $model = new PluginServiceModel($this->app);

        // remove all event handlers
        $model->removeEventHandler('admin_edit_product', array(
            'plugin' => 'example',
            'file'   => 'admin/events/adminevent',
            'method' => 'editProduct'
        ));

        // remove all hook handlers
        $model->removeHookHandler('admin_controller', array(
            'class'    => 'tool/test',
            'method'   => 'index',
            'type'     => 'post',
            'plugin'   => 'example',
            'file'     => 'admin/hooks/controllerhooks',
            'callback' => 'exampleHook',
            'args'     => array(
                'heading_title' => 'Example Test Page',
                'item_title'    => 'Item title'
            )
        ));

        $model->removeHookHandler('admin_controller', array(
            'class'    => 'tool/test',
            'method'   => 'index',
            'type'     => 'pre',
            'plugin'   => 'example',
            'file'     => 'admin/hooks/controllerhooks',
            'callback' => 'preHook'
        ));
    }
}


text:
from TemplateParameterParser import *
from WrappedMethodCreator import *
from helper_classes import FertilizedClass, InstantiationTypes, RstDocProvider
import CppHeaderParser
import sys
import os
from DoxygenTypeExtractor import DoxygenTypeExtractor

class SingleFileParser(object):
    r"""
    Parses a cpp header file containng a fetilized class and wraps it into
    intermediate objects which can be used to automatically generate code for
    matlab wrapper classes etc.
    """
    def __init__(self, filename, package):
        self.Package = package
        self.Filename = filename
        try:
            CppHeaderParser.ignoreSymbols.append("BOOST_SERIALIZATION_SPLIT_MEMBER()")
            CppHeaderParser.ignoreSymbols.append("VIRTUAL()")
            self.CppHeader = CppHeaderParser.CppHeader(filename)
        except CppHeaderParser.CppParseError as e:
            print(e)
            sys.exit(1)

    def ParseToIntermediateObject(self):
        print(("[started  parsing] " + self.Filename))
        classes = []
        functions = []
        for clsName in list(self.CppHeader.classes.keys()):
            if clsName.startswith('_'):
              continue
            cls = self.CppHeader.classes[clsName]
            intermediateObject = self.ParseClass(cls)
            if not intermediateObject is None:
              classes.append(intermediateObject)
        for func in self.CppHeader.functions:
            intermediateObject = self.ParseFunction(func)
            functions.append(intermediateObject)
        included_obj_strings = []
        for include_stmt in self.CppHeader.includes:
          if not include_stmt.startswith('".') or \
             include_stmt[include_stmt.rindex("/")+1] == '_':
            continue
          if include_stmt.endswith('global.h"') or \
             include_stmt.endswith('util.h"') or \
             include_stmt.endswith('ndarray.h"') or \
             include_stmt.endswith('types.h"') or \
             include_stmt.endswith('serialization.h"') or \
             include_stmt.endswith('gil.hpp"') or \
             include_stmt.endswith('fertilized_fwd.h"') or \
             include_stmt.endswith('sampling.h"') or \
             include_stmt.endswith('mat.h"') or \
             include_stmt.endswith('checks.h"') or \
             include_stmt.endswith('exponentials.h"') or \
             include_stmt.endswith('argsort.h"') or \
             include_stmt.endswith('feature_value_selection.h"') or \
             include_stmt.endswith('caffe.hpp"') or \
             include_stmt.endswith('default_values.h"'):
            continue
          included_obj_strings.append(include_stmt[include_stmt.rindex("/")+1:-3])
        using_rel_str = []
        for obj_str in included_obj_strings:
          for cls in classes:
            using_rel_str.append((cls.ClassName.lower(), obj_str))
        return classes, functions, using_rel_str

    def ParseClass(self, cls):
        # get class constructor for the standard get method
        constructors = [m for m in cls["methods"]["public"] if m["constructor"] == True]
        other_methods = [m for m in cls["methods"]["public"] if m["constructor"] != True]
        wrappedMethods = []

        # Parse inheritance.
        # CPPHeaderParser fails sometimes to parse correctly, so jump in.
        inherits = None
        if len(cls['inherits']) > 0:
          with open(self.Filename, 'r') as def_file:
            lines = [line for line in def_file]
          inheritstr = ''
          linenr = cls['line_number']-1
          while not ':' in lines[linenr]:
            linenr += 1
          fromstart = lines[linenr].index(":")
          lines[linenr] = lines[linenr][fromstart+1:]
          while lines[linenr].strip() == '':
            linenr += 1
          if lines[linenr].strip().startswith("public"):
            lines[linenr] = lines[linenr][lines[linenr].index("public")+7:]
            completed = False
            while linenr < len(lines) and not completed:
              if "public " in lines[linenr]:
                raise Exception("Multiple inheritance not supported.")
              if "{" in lines[linenr]:
                endpos = lines[linenr].index("{")
                completed = True
              else:
                endpos = len(lines[linenr])
              inheritstr += lines[linenr][:endpos]
              linenr += 1
            inherits = inheritstr
        # extract types from doxygen comment
        dte = DoxygenTypeExtractor(cls.get("doxygen"))
        availableIn, types, soilUsage, serialization_generation = dte.Extract()
        # print("serialization generation: %d" % (serialization_generation))
        if types == None:
            print("[WARNING]    no type comment for class " +  cls["name"])
        # get classes template params
        classDefLineNumber = cls["line_number"]
        tpp = TemplateParameterParser(self.Filename, classDefLineNumber)
        # Determine whether split_member is used.
        used_split_member = False
        with open(self.Filename, 'r') as f:
          for line in f:
            if 'BOOST_SERIALIZATION_SPLIT_MEMBER()' in line:
              used_split_member = True
              break
        typenames, templateParamStr = tpp.RetrieveTemplateParameters()
        parsed_constructors = []
        for constructor in constructors:
            constructorParams = constructor["parameters"]
            # Retrieve parameters of the constructor and wrap them into the intermediate structure

            # change signature of constructor method in c api
            # if more than one constructor is available,
            # because c doesn't support overloading of methods
            nameFormat = "{0}{1}"

            dne = DoxygenTypeExtractor(constructor.get("doxygen"))
            methodAvailableIn, exportedName = dne.ExtractExportedName()

            if not exportedName == None:
                nameFormat = exportedName + "{1}"

            wmc = WrappedMethodCreator(constructor,
                                       "get",
                                       nameFormat,
                                       types,
                                       "get_method.jinja",
                                       methodAvailableIn,
                                       self.Filename)
            method = wmc.CreateWrappedMethod(typenames, cls)
            method.ExportedName = exportedName
            method.IsConstructor = True
            wrappedMethods.append(method)
            parsed_constructors.append(method)
        # This is more reliable for this library than the CppHeaderParser ["abstract"]
        isAbstract = cls["name"].startswith('I') and \
                     cls["name"][1].upper() == cls["name"][1]
        for method in other_methods:
            if '~' in method['debug']:
              # Destructor
              continue
            wrappedMethods.append(self.ParseFunction(method, typenames, cls, isAbstract, used_split_member))
        if wrappedMethods.count == 0 or wrappedMethods == [] and not isAbstract:
            print("[WARNING]    no constructor found for class " +  cls["name"])
            return None
        cppdoc = cls['doxygen'] if 'doxygen' in cls else ''
        wrappedClass = FertilizedClass(CppType(cls["name"], True, typenames),
                                        types,
                                        wrappedMethods,
                                        self.Package,
                                        specialConstructor = None,
                                        dummyClass = False,
                                        isAbstract=isAbstract,
                                        declarationMethod=cls["declaration_method"],
                                        templatingString=templateParamStr,
                                        exclusiveSoilUsage=soilUsage,
                                        documentations={'C++':cppdoc,
                                                        'Python': RstDocProvider(cppdoc),
                                                        'Matlab': RstDocProvider(cppdoc)},
                                        inherits = inherits,
                                        constructors = parsed_constructors,
                                        defining_header=self.Filename,
                                        serialization_generation=serialization_generation)
        for method in wrappedMethods:
          method.ParentClass = wrappedClass
        wrappedClass.AvailableIn = availableIn
        return wrappedClass

    def ParseFunction(self, func, clstypenames=None, cls=None, isAbstract=False, used_split_member=False):
        # get classes template params
        classDefLineNumber = func["line_number"]
        tpp = TemplateParameterParser(self.Filename, classDefLineNumber)
        typenames, templateParamStr = tpp.RetrieveTemplateParameters()
        # extract types from doxygen comment
        dte = DoxygenTypeExtractor(func.get("doxygen"))
        try:
          availableIn, types, soilUsage, _ = dte.Extract()
        except:
          availableIn, types, soilUsage, _ = dte.Extract()
          pass
        methodAvailableIn, exportedName = dte.ExtractExportedName()
        if types == None and \
           not func['name'] == 'serialize' and \
           not isAbstract and \
           not (func['name'] in ['save', 'load'] and used_split_member):
            print("[WARNING]    no type comment for function " +  func["name"])

        nameFormat = "{0}{1}"

        if not exportedName == None:
            nameFormat = exportedName + "{1}"

        # Retrieve parameters of the constructor and wrap them into the intermediate structure
        wmc = WrappedMethodCreator(func,
                                   func["name"],
                                   nameFormat,
                                   types,
                                   "standard_method.jinja",
                                   availableIn,
                                   self.Filename)
        method = wmc.CreateWrappedMethod(clstypenames, cls)
        method.ExportedName = exportedName

        if not func.get('parent') == None:
            # get parent type (because it is a instance method, which can't be called instant-wise in the c api :(
            parent = func['parent'] # is now a cppheaderparser class obj

            # get classes template params
            classDefLineNumber = parent["line_number"]
            tpp = TemplateParameterParser(self.Filename, classDefLineNumber)
            typenames, templateParamStr = tpp.RetrieveTemplateParameters()

            if typenames == None:
                typestr = parent['name']
            else:
                typestr = parent['name'] + '<' + ', '.join(typenames) + '>'
            type = CppType(typestr, True)
            firstParam = Argument(type, parent['name'].lower(), None, typestr)
            method.ParentClassParam = firstParam
        if clstypenames is None:
          method.TemplateArguments = typenames
          method.TemplateString = templateParamStr
        return method


text:
/* Test program that performs producer-consumer style communication through
 * a circular buffer. This test program is a slightly modified version of the
 * test program made available by Miguel Ojeda
 * -- see also http://article.gmane.org/gmane.comp.debugging.valgrind/8782.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include "../../config.h"

/** gcc versions 4.1.0 and later have support for atomic builtins. */

#ifndef HAVE_BUILTIN_ATOMIC
#error Sorry, but this test program can only be compiled by a compiler that\
has built-in functions for atomic memory access.
#endif

#define BUFFER_MAX (2)
#define DATA_SEMAPHORE_NAME "cb-data-semaphore"
#define FREE_SEMAPHORE_NAME "cb-free-semaphore"

typedef int data_t;

typedef struct {
  /* Counting semaphore representing the number of data items in the buffer. */
  sem_t* data;
  /* Counting semaphore representing the number of free elements. */
  sem_t* free;
  /* Position where a new elements should be written. */
  int in;
  /* Position from where an element can be removed. */
  int out;
  /* Mutex that protects 'in'. */
  pthread_mutex_t mutex_in;
  /* Mutex that protects 'out'. */
  pthread_mutex_t mutex_out;
  /* Data buffer. */
  data_t buffer[BUFFER_MAX];
} buffer_t;

static int quiet = 0;
static int use_locking = 1;

static __inline__
int fetch_and_add(int* p, int i)
{
  return __sync_fetch_and_add(p, i);
}

static sem_t* create_semaphore(const char* const name, const int value)
{
#ifdef VGO_darwin
  char name_and_pid[32];
  snprintf(name_and_pid, sizeof(name_and_pid), "%s-%d", name, getpid());
  sem_t* p = sem_open(name_and_pid, O_CREAT | O_EXCL, 0600, value);
  if (p == SEM_FAILED) {
    perror("sem_open");
    return NULL;
  }
  return p;
#else
  sem_t* p = malloc(sizeof(*p));
  if (p)
    sem_init(p, 0, value);
  return p;
#endif
}

static void destroy_semaphore(const char* const name, sem_t* p)
{
#ifdef VGO_darwin
  sem_close(p);
  sem_unlink(name);
#else
  sem_destroy(p);
  free(p);
#endif
}

static void buffer_init(buffer_t * b)
{
  b->data = create_semaphore(DATA_SEMAPHORE_NAME, 0);
  b->free = create_semaphore(FREE_SEMAPHORE_NAME, BUFFER_MAX);

  pthread_mutex_init(&b->mutex_in, NULL);
  pthread_mutex_init(&b->mutex_out, NULL);

  b->in = 0;
  b->out = 0;
}

static void buffer_recv(buffer_t* b, data_t* d)
{
  int out;
  sem_wait(b->data);
  if (use_locking)
    pthread_mutex_lock(&b->mutex_out);
  out = fetch_and_add(&b->out, 1);
  if (out >= BUFFER_MAX)
  {
    fetch_and_add(&b->out, -BUFFER_MAX);
    out -= BUFFER_MAX;
  }
  *d = b->buffer[out];
  if (use_locking)
    pthread_mutex_unlock(&b->mutex_out);
  if (! quiet)
  {
    printf("received %d from buffer[%d]\n", *d, out);
    fflush(stdout);
  }
  sem_post(b->free);
}

static void buffer_send(buffer_t* b, data_t* d)
{
  int in;
  sem_wait(b->free);
  if (use_locking)
    pthread_mutex_lock(&b->mutex_in);
  in = fetch_and_add(&b->in, 1);
  if (in >= BUFFER_MAX)
  {
    fetch_and_add(&b->in, -BUFFER_MAX);
    in -= BUFFER_MAX;
  }
  b->buffer[in] = *d;
  if (use_locking)
    pthread_mutex_unlock(&b->mutex_in);
  if (! quiet)
  {
    printf("sent %d to buffer[%d]\n", *d, in);
    fflush(stdout);
  }
  sem_post(b->data);
}

static void buffer_destroy(buffer_t* b)
{
  destroy_semaphore(DATA_SEMAPHORE_NAME, b->data);
  destroy_semaphore(FREE_SEMAPHORE_NAME, b->free);

  pthread_mutex_destroy(&b->mutex_in);
  pthread_mutex_destroy(&b->mutex_out);
}

static buffer_t b;

static void producer(int* id)
{
  buffer_send(&b, id);
  pthread_exit(NULL);
}

#define MAXSLEEP (100 * 1000)

static void consumer(int* id)
{
  int d;
  usleep(rand() % MAXSLEEP);
  buffer_recv(&b, &d);
  if (! quiet)
  {
    printf("%i: %i\n", *id, d);
    fflush(stdout);
  }
  pthread_exit(NULL);
}

#define THREADS (10)

int main(int argc, char** argv)
{
  pthread_t producers[THREADS];
  pthread_t consumers[THREADS];
  int thread_arg[THREADS];
  int i;
  int optchar;

  while ((optchar = getopt(argc, argv, "nq")) != EOF)
  {
    switch (optchar)
    {
    case 'n':
      use_locking = 0;
      break;
    case 'q':
      quiet = 1;
      break;
    }
  }

  srand(time(NULL));

  buffer_init(&b);

  for (i = 0; i < THREADS; ++i)
  {
    thread_arg[i] = i;
    pthread_create(producers + i, NULL,
                   (void * (*)(void *)) producer, &thread_arg[i]);
  }

  for (i = 0; i < THREADS; ++i)
    pthread_create(consumers + i, NULL,
                   (void * (*)(void *)) consumer, &thread_arg[i]);

  for (i = 0; i < THREADS; ++i)
  {
    pthread_join(producers[i], NULL);
    pthread_join(consumers[i], NULL);
  }

  buffer_destroy(&b);

  return 0;
}


text:
package cn.visualing.demo;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import com.squareup.picasso.Picasso;

import cn.visualing.JZVideoPlayer;
import cn.visualing.JZVideoPlayerStandard;

/**
 * Created by Nathen on 2016/12/30.
 */
public class OrientationActivity extends AppCompatActivity {
    JZVideoPlayerStandard mJzVideoPlayerStandard;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(false);
        getSupportActionBar().setTitle("Orientation");
        setContentView(R.layout.activity_orientation);
        mJzVideoPlayerStandard = (JZVideoPlayerStandard) findViewById(R.id.jz_video);
        mJzVideoPlayerStandard.setUp(VideoConstant.videoUrlList[0]
                , JZVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "嫂子不信");
        Picasso.with(this)
                .load(VideoConstant.videoThumbList[0])
                .into(mJzVideoPlayerStandard.thumbImageView);

        JZVideoPlayer.FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        JZVideoPlayer.NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;

    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
package com.example.yesgxy520.jasontest;

import android.app.Activity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

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

public class MainActivity extends Activity implements OnClickListener{
    AlertDialog.Builder dialog;
    List<City> cityList;
    HefengWeatherDB hefengWeatherDB;
    SQLiteDatabase db;
    final String NO_CITY="nocity";
    String cityId;
    String weather1_txt;
    String weather2_txt;
    String temp1_txt;
    String temp2_txt;
    LinearLayout weatherLayout;
    LinearLayout tempLayout;
    Button queryButton;
    EditText editText;
    TextView weather1_tv;
    TextView weather2_tv;
    TextView temp1_tv;
    TextView temp2_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queryButton = (Button) findViewById(R.id.queryButton);
        editText = (EditText) findViewById(R.id.editText);
        weather1_tv=(TextView)findViewById(R.id.weather1_tv);
        weather2_tv=(TextView)findViewById(R.id.weather2_tv);
        temp1_tv=(TextView)findViewById(R.id.temp1_tv);
        temp2_tv=(TextView)findViewById(R.id.temp2_tv);
        weatherLayout=(LinearLayout)findViewById(R.id.weatherLayout);
        weatherLayout.setVisibility(View.INVISIBLE);
        tempLayout=(LinearLayout)findViewById(R.id.tempLayout);
        tempLayout.setVisibility(View.INVISIBLE);
        queryButton.setOnClickListener(this);
        hefengWeatherDB = HefengWeatherDB.getInstance(this);
        cityList=hefengWeatherDB.loadCities();
        db = hefengWeatherDB.db;
        if(cityList.size()==0) {
            HttpUtil.sendHttpRequest("https://api.heweather.com/x3/citylist?search=allchina&key=d06f6064818d4048a2670d839246f4fd",
                    new HttpCallbackListener() {
                        @Override
                        public void onFinish(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                JSONArray jsonArray = jsonObject.getJSONArray("city_info");
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                                    City city = new City();
                                    city.setCityName(jsonObject1.getString("city"));
                                    city.setCityId(jsonObject1.getString("id"));
                                    hefengWeatherDB.saveCity(city);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        public void onError(Exception e) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    });
        }

    }
    public void onClick(View view) {
        weatherLayout.setVisibility(View.INVISIBLE);
        tempLayout.setVisibility(View.INVISIBLE);
        Cursor cursor = db.query("City", null, "city_name=?", new String[]{editText.getText().toString()}, null, null, null);
        if (cursor.moveToFirst()) {
            do {

                cityId = cursor.getString(cursor.getColumnIndex("city_id"));
            } while (cursor.moveToNext());
        }
        if (cursor.getCount()==0) {
            dialog = new AlertDialog.Builder(MainActivity.this);
            dialog.setTitle("警告");
            dialog.setMessage("没有这个城市");
            dialog.setCancelable(false);
            dialog.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            dialog.show();
            cursor.close();
        } else {
            cursor.close();
            queryWeather("https://api.heweather.com/x3/weather?cityid=" + cityId + "&key=d06f6064818d4048a2670d839246f4fd");
        }
    }

    public void queryWeather(String address) {
        HttpUtil.sendHttpRequest(address,
                new HttpCallbackListener() {
                    @Override
                    public void onFinish(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather data service 3.0");
                            JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                            JSONArray jsonArray1 = jsonObject1.getJSONArray("daily_forecast");
                            JSONObject jsonObject2 = jsonArray1.getJSONObject(0);
                            JSONObject jsonObject3 = jsonObject2.getJSONObject("cond");
                            JSONObject jsonObject4=jsonObject2.getJSONObject("tmp");
                            weather1_txt = jsonObject3.getString("txt_d");
                            weather2_txt = jsonObject3.getString("txt_n");
                            temp1_txt=jsonObject4.getString("min");
                            temp2_txt=jsonObject4.getString("max");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    weatherLayout.setVisibility(View.VISIBLE);
                                    tempLayout.setVisibility(View.VISIBLE);
                                    weather1_tv.setText(weather1_txt);
                                    weather2_tv.setText(weather2_txt);
                                    temp1_tv.setText(temp1_txt+"度");
                                    temp2_tv.setText(temp2_txt+"度");
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void onError(Exception e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
    }

}

  //                      textView = (TextView) findViewById(R.id.textview);
//        HttpUtil.sendHttpRequest("https://api.heweather.com/x3/citylist?search=allchina&key=d06f6064818d4048a2670d839246f4fd",
//                new HttpCallbackListener() {
//                    @Override
//                    public void onFinish(String response) {
//                        try {
//                            JSONArray jsonArray=new JSONArray("city info");
//                            for(int i=0;i<jsonArray.length();i++){
//                                JSONObject jsonObject=jsonArray.getJSONObject(i);
//
//                            }
//                            JSONObject jsonObject = new JSONObject(response);
//                            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather data service 3.0");
//                            JSONObject jsonObject1 = jsonArray.getJSONObject(0);
//                            JSONObject jsonObject2 = jsonObject1.getJSONObject("basic");
//                            JSONObject jsonObject3 = jsonObject2.getJSONObject("update");
//                            abc = jsonObject3.getString("loc");
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    textView.setText(abc);
//                                }
//                            });
//
//
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//
//
//                    }
//
//                    @Override
//                    public void onError(Exception e) {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(MainActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
//                            }
//                        });
//
//                    }
//                });
//    }


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Data.SqlClient;
using System.Reflection;
using System.Data.SQLite;

namespace WFA_psychometric_chart
{
    public partial class Form4_insert_data : Form
    {
        private Form3_WeatherService form3;
        public Form4_insert_data(Form3_WeatherService form3)
        {
            this.form3 = form3;
            InitializeComponent();
          this.Disposed += new System.EventHandler ( this.Form4_insert_data_Disposed );
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(tb_building_name.Text == "")
            {
                MessageBox.Show("Please enter building name!");       //MLHIDE
            }

            else if (tb_country.Text == "")
            {
                MessageBox.Show(WFA_psychometric_chart.Properties.Resources.Enter_country_name);

            }
            else if (tb_city.Text == "")
            {
                MessageBox.Show(WFA_psychometric_chart.Properties.Resources.Enter_city_name);
            }
            else if (tb_ZIP.Text == "")
            {
                MessageBox.Show(WFA_psychometric_chart.Properties.Resources.enter_ZIP_number);

            }
            else
            {
                string buildingName = tb_building_name.Text;
                string country = tb_country.Text;
                string city = tb_city.Text;
                string state = tb_state.Text;
                string street = tb_street.Text;
                string zip = tb_ZIP.Text;
                string lng = tb_longitude.Text;
                string lat = tb_latitude.Text;
                string elevation = tb_elevation.Text;
                //now lets update the values in database...

                try
                {
                     //lets pull the vales offline values stored in db...
                   // string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    //string connString =@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\nischal\documents\visual studio 2013\Projects\WFA_psychometric_chart\WFA_psychometric_chart\T3000.mdb;Persist Security Info=True";
                    //string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + @"\T3000.mdb;Persist Security Info=True";
                 //   string connString = @"Data Source=GREENBIRD;Initial Catalog=db_psychrometric_project;Integrated Security=True";

                    //--changing all the database to the sqlite database...
                    string databasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    string databaseFile = databasePath + @"\db_psychrometric_project.s3db";

                    string connString = @"Data Source=" + databaseFile + ";Version=3;";

                    using (SQLiteConnection connection = new SQLiteConnection(connString))
                    {

                        connection.Open();
                        //string sql_string = "update tbl_building_location set   country=@country_value,state=@state_value,city=@city_value,street=@street_value,ZIP=@zip_value where ID = 1;";
                        string sql_query = "INSERT INTO tbl_building_location(country,state,city,street,zip,longitude,latitude,elevation,BuildingName) VALUES(@country_value,@state_value,@city_value,@street_value,@zip_value,@long_value,@lat_value,@elevation_value,@building_name)";
                         SQLiteCommand command = new SQLiteCommand(sql_query, connection);
                        command.CommandType = CommandType.Text;
                        command.Parameters.AddWithValue("@country_value", country);
                        command.Parameters.AddWithValue("@state_value", state);
                        command.Parameters.AddWithValue("@city_value", city);
                        command.Parameters.AddWithValue("@street_value", street);
                        command.Parameters.AddWithValue("@zip_value", zip);
                        command.Parameters.AddWithValue("@long_value", lng);
                        command.Parameters.AddWithValue("@lat_value", lat);
                        command.Parameters.AddWithValue("@elevation_value", elevation);
                        command.Parameters.AddWithValue("@building_name", buildingName);
                        command.ExecuteNonQuery();
                        //MessageBox.Show("sql string = " + sql_string);
                        MessageBox.Show(WFA_psychometric_chart.Properties.Resources.value_inserted_successfully);
                        btn_insert_data.Enabled = false;
                        tb_country.Text = "";
                        tb_city.Text = "";
                        tb_state.Text = "";
                        tb_street.Text = "";
                        tb_ZIP.Text = "";
                        tb_latitude.Text = "";
                        tb_longitude.Text = "";
                        tb_elevation.Text = "";

                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }//close of else..

           //lets refresh the list....
            form3.fill_combobox();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public double getElevation(double lat, double lng)
        {
            //https://developers.google.com/maps/documentation/elevation/intro
            var request = (HttpWebRequest)WebRequest.Create(string.Format("https://maps.googleapis.com/maps/api/elevation/json?locations={0},{1}&key=AIzaSyB27paQGkpwaVGAd7wp0N6rcFkq5JEKeiQ", lat, lng));
            var response = (HttpWebResponse)request.GetResponse();
            var sr = new StreamReader(response.GetResponseStream() ?? new MemoryStream()).ReadToEnd();

            var json = JObject.Parse(sr);
            return (double)json.SelectToken("results[0].elevation");
        }

        private void pull_data_online()
        {
            //this function pulls the data from online devices...

            /*
            1.country,state,city,street,latitude,longitude,elev,zip
            */
            string country = tb_country.Text;
            string state = tb_state.Text;
            string city = tb_city.Text;
            string street = tb_street.Text;
            string zip =tb_ZIP.Text;
            int value;
            if (int.TryParse(zip,out value))
            {

                if (country != "" && city != "")
                {
                    string join_string = "";
                    if (state != "" && street != "")
                    {
                        join_string = country + "," + state + "," + city + "," + street;
                    }
                    else
                    {
                        join_string = country + "," + city;
                    }

                    //geo location code goes here..
                    try
                    {

                        var address = join_string;
                        var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));

                        var request = WebRequest.Create(requestUri);
                        var response = request.GetResponse();

                        var xdoc = XDocument.Load(response.GetResponseStream());

                        var result = xdoc.Element("GeocodeResponse").Element("result");
                        //MessageBox.Show("result = " + result);
                        var locationElement = result.Element("geometry").Element("location");
                        var lat = locationElement.Element("lat");
                        var lng = locationElement.Element("lng");

                        double lat2 = Double.Parse(lat.Value);
                        double lng2 = Double.Parse(lng.Value);
                        tb_latitude.Text = lat2.ToString();
                        tb_longitude.Text = lng2.ToString();

                        //now lets go for the elevation calculation

                        //var latlng = lat2 + "," + lng2;
                        //var reqUri = string.Format("https://maps.googleapis.com/maps/api/elevation/xml?locations='"+latlng+"'&key=AIzaSyB27paQGkpwaVGAd7wp0N6rcFkq5JEKeiQ");
                        //MessageBox.Show("requrl= " + reqUri);
                        //var req = WebRequest.Create(reqUri);
                        //var resp = req.GetResponse();

                        //var xdoc1 = XDocument.Load(resp.GetResponseStream());
                        //MessageBox.Show("xdoc1= " + xdoc1);
                        //var result1 = xdoc1.Element("elevation").Value;
                        //MessageBox.Show("result1 = " + result1);
                        double elevation = getElevation(lat2, lng2);
                        //MessageBox.Show("elev= " + elevation);
                        tb_elevation.Text = elevation.ToString();
                        btn_insert_data.Enabled = true;

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        btn_insert_data.Enabled = false;
                        tb_country.Text = "";
                        tb_city.Text = "";
                        tb_state.Text = "";
                        tb_street.Text = "";
                        tb_ZIP.Text = "";

                    }

                }//close of if...
            }//close of if int try parse.
            else
            {
                MessageBox.Show(WFA_psychometric_chart.Properties.Resources.Please_enter_a_valid_zip_numbe);
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //this is where online elevation and other facotrs are pulled..
            //pull_data_online();

        }

        private void tb_country_text_change_event(object sender, EventArgs e)
        {
            string a = tb_country.Text;

            if(a.Length<0){
                //if the length is < 2 do nothing

            }
            else if(a.Length>=0 && a.Length <= 2){
                  tb_state.Enabled = false;
                tb_city.Enabled = false;
            }
            else {
                //otherwise activate other textbox..

                tb_state.Enabled = true;
                tb_city.Enabled = true;

            }

        }

        private void tb_city_text_change_event(object sender, EventArgs e)
        {
            string a = tb_city.Text;

            if (a.Length < 0)
            {
                //if the length is < 2 do nothing

            }
            else if (a.Length >= 0 && a.Length <= 2)
            {
                tb_street.Enabled = false;
                tb_ZIP.Enabled = false;
            }
            else
            {
                //otherwise activate other textbox..

                tb_street.Enabled = true;
                tb_ZIP.Enabled = true;

            }

        }

        private void tb_zip_textChange_event(object sender, EventArgs e)
        {
            //here we actually call the pulling function..
            pull_data_online();

        }

      public void Form4_insert_data_Disposed ( object sender, System.EventArgs e )
      {
      }

        private void Form4_insert_data_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
MultiTableBulkIdStrategy.DeleteHandler (Hibernate JavaDocs)
</TITLE>

<META NAME="date" CONTENT="2013-10-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.hibernate.hql.spi

Interface MultiTableBulkIdStrategy.DeleteHandler

All Known Implementing Classes:
TableBasedDeleteHandlerImpl

Enclosing interface:
MultiTableBulkIdStrategy

public static interface MultiTableBulkIdStrategy.DeleteHandler

Handler for dealing with multi-table HQL bulk delete statements.

Method Summary

 int
execute(SessionImplementor session,
        QueryParameters queryParameters)

 String[]
getSqlStatements()

 Queryable
getTargetedQueryable()

Method Detail

getTargetedQueryable

Queryable getTargetedQueryable()

getSqlStatements

String[] getSqlStatements()

execute

int execute(SessionImplementor session,
            QueryParameters queryParameters)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2001-2013 Red Hat, Inc.  All Rights Reserved.


text:
from __future__ import with_statement

import sys
import tempfile
import datetime

from mock import Mock

from libcloud import __version__
from libcloud.test import unittest
from libcloud.dns.base import DNSDriver, Zone, Record
from libcloud.dns.types import RecordType

from libcloud.utils.py3 import assertRegex

MOCK_RECORDS_VALUES = [
    {'id': 1, 'name': 'www', 'type': RecordType.A, 'data': '127.0.0.1'},
    {'id': 2, 'name': 'www', 'type': RecordType.AAAA,
     'data': '2a01:4f8:121:3121::2'},

    # Custom TTL
    {'id': 3, 'name': 'www', 'type': RecordType.A, 'data': '127.0.0.1',
     'extra': {'ttl': 123}},

    # Record without a name
    {'id': 4, 'name': '', 'type': RecordType.A,
     'data': '127.0.0.1'},

    {'id': 5, 'name': 'test1', 'type': RecordType.TXT,
     'data': 'test foo bar'},

    # TXT record with quotes
    {'id': 5, 'name': 'test2', 'type': RecordType.TXT,
     'data': 'test "foo" "bar"'},

    # Records with priority
    {'id': 5, 'name': '', 'type': RecordType.MX,
     'data': 'mx.example.com', 'extra': {'priority': 10}},
    {'id': 5, 'name': '', 'type': RecordType.SRV,
     'data': '10 3333 example.com', 'extra': {'priority': 20}},
]

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        self.driver = DNSDriver('none', 'none')
        self.tmp_file = tempfile.mkstemp()
        self.tmp_path = self.tmp_file[1]

    def test_export_zone_to_bind_format_slave_should_throw(self):
        zone = Zone(id=1, domain='example.com', type='slave', ttl=900,
                    driver=self.driver)
        self.assertRaises(ValueError, zone.export_to_bind_format)

    def test_export_zone_to_bind_format_success(self):
        zone = Zone(id=1, domain='example.com', type='master', ttl=900,
                    driver=self.driver)

        mock_records = []

        for values in MOCK_RECORDS_VALUES:
            values = values.copy()
            values['driver'] = self.driver
            values['zone'] = zone
            record = Record(**values)
            mock_records.append(record)

        self.driver.list_records = Mock()
        self.driver.list_records.return_value = mock_records

        result = self.driver.export_zone_to_bind_format(zone=zone)
        self.driver.export_zone_to_bind_zone_file(zone=zone,
                                                  file_path=self.tmp_path)

        with open(self.tmp_path, 'r') as fp:
            content = fp.read()

        lines1 = result.split('\n')
        lines2 = content.split('\n')

        now = datetime.datetime.utcnow()
        date_str = "%s-%s-%s %s:%s:%s" % (now.year, zero_pad(now.month),
                                          zero_pad(now.day),
                                          zero_pad(now.hour),
                                          zero_pad(now.minute),
                                          zero_pad(now.second))
        expected_header = "; Generated by Libcloud v%s on %s UTC" % (__version__, date_str)

        self.assertEqual(lines1[0], expected_header)
        self.assertEqual(lines2[0], expected_header)

        for lines in [lines1, lines2]:
            self.assertEqual(len(lines), 2 + 1 + 9)
            assertRegex(self, lines[1], r'\$ORIGIN example\.com\.')
            assertRegex(self, lines[2], r'\$TTL 900')

            assertRegex(self, lines[4], r'www.example.com\.\s+900\s+IN\s+A\s+127\.0\.0\.1')
            assertRegex(self, lines[5], r'www.example.com\.\s+900\s+IN\s+AAAA\s+2a01:4f8:121:3121::2')
            assertRegex(self, lines[6], r'www.example.com\.\s+123\s+IN\s+A\s+127\.0\.0\.1')
            assertRegex(self, lines[7], r'example.com\.\s+900\s+IN\s+A\s+127\.0\.0\.1')
            assertRegex(self, lines[8], r'test1.example.com\.\s+900\s+IN\s+TXT\s+"test foo bar"')
            assertRegex(self, lines[9], r'test2.example.com\.\s+900\s+IN\s+TXT\s+"test \\"foo\\" \\"bar\\""')
            assertRegex(self, lines[10], r'example.com\.\s+900\s+IN\s+MX\s+10\s+mx.example.com')
            assertRegex(self, lines[11], r'example.com\.\s+900\s+IN\s+SRV\s+20\s+10 3333 example.com')

    def test_get_numeric_id(self):
        values = MOCK_RECORDS_VALUES[0].copy()
        values['driver'] = self.driver
        values['zone'] = None
        record = Record(**values)

        record.id = 'abcd'
        result = record._get_numeric_id()
        self.assertEqual(result, 'abcd')

        record.id = '1'
        result = record._get_numeric_id()
        self.assertEqual(result, 1)

        record.id = '12345'
        result = record._get_numeric_id()
        self.assertEqual(result, 12345)

        record.id = ''
        result = record._get_numeric_id()
        self.assertEqual(result, '')

        record.id = None
        result = record._get_numeric_id()
        self.assertEqual(result, '')

def zero_pad(value: int) -> str:
    if value < 10:
        return "0" + str(value)

    return str(value)

if __name__ == '__main__':
    sys.exit(unittest.main())


text:
__version__ = '0.0.1'
default_app_config = 'myshop.apps.MyShopConfig'


text:
#include "tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.h"

#include <string>

#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"

using xla::llvm_ir::IrArray;

namespace xla {
namespace cpu {

StatusOr<llvm::Value*> CpuElementalIrEmitter::EmitAtan2(PrimitiveType prim_type,
                                                        llvm::Value* lhs,
                                                        llvm::Value* rhs) {
  string function_name;
  bool cast_result_to_fp16 = false;
  switch (prim_type) {
    case F16:
      cast_result_to_fp16 = true;
      lhs = FPCast(lhs, b_->getFloatTy());
      rhs = FPCast(rhs, b_->getFloatTy());
      TF_FALLTHROUGH_INTENDED;
    case F32:
      function_name = "atan2f";
      break;
    case F64:
      function_name = "atan2";
      break;
    default:
      return Unimplemented("atan2");
  }
  // Create a function declaration.
  llvm::Function* function = llvm::dyn_cast<llvm::Function>(
      module_
          ->getOrInsertFunction(function_name, lhs->getType(), lhs->getType(),
                                rhs->getType())
          .getCallee());
  function->setCallingConv(llvm::CallingConv::C);
  function->setDoesNotThrow();
  function->setDoesNotAccessMemory();
  // Create an instruction to call the function.
  llvm::Value* result = Call(function, {lhs, rhs});
  if (cast_result_to_fp16) {
    result = FPCast(result, b_->getHalfTy());
  }
  return result;
}

StatusOr<llvm::Value*> CpuElementalIrEmitter::EmitTanh(PrimitiveType prim_type,
                                                       llvm::Value* value) {
  bool cast_result_to_fp16 = false;
  string function_name;
  switch (prim_type) {
    case F16:
      cast_result_to_fp16 = true;
      value = FPCast(value, b_->getFloatTy());
      TF_FALLTHROUGH_INTENDED;
    case F32:
      function_name = "tanhf";
      break;
    case F64:
      function_name = "tanh";
      break;
    default:
      return Unimplemented("tanh");
  }
  // Create a function declaration.
  llvm::Function* function = llvm::dyn_cast<llvm::Function>(
      module_
          ->getOrInsertFunction(function_name, value->getType(),
                                value->getType())
          .getCallee());
  function->setCallingConv(llvm::CallingConv::C);
  function->setDoesNotThrow();
  function->setDoesNotAccessMemory();
  // Create an instruction to call the function.
  llvm::Value* result = Call(function, value);
  if (cast_result_to_fp16) {
    result = FPCast(result, b_->getHalfTy());
  }
  return result;
}

llvm_ir::ElementGenerator CpuElementalIrEmitter::MakeElementGenerator(
    const HloInstruction* hlo,
    const HloToElementGeneratorMap& operand_to_generator) {
  switch (hlo->opcode()) {
    case HloOpcode::kMap:
      return [this, hlo, &operand_to_generator](
                 const IrArray::Index& index) -> StatusOr<llvm::Value*> {
        std::vector<llvm::Value*> operands;
        for (int i = 0; i < hlo->operand_count(); i++) {
          TF_ASSIGN_OR_RETURN(llvm::Value * operand_value,
                              operand_to_generator.at(hlo->operand(i))(index));
          operands.push_back(operand_value);
        }
        return ir_emitter_->EmitElementalMap(*Cast<HloMapInstruction>(hlo),
                                             operands, llvm_ir::IrName(hlo));
      };
    case HloOpcode::kReduceWindow:
      return [this, hlo, &operand_to_generator](const IrArray::Index& index) {
        return ir_emitter_->EmitElementalReduceWindow(
            Cast<HloReduceWindowInstruction>(hlo),
            operand_to_generator.at(hlo->operand(0)), index);
      };
    case HloOpcode::kConvolution:
      return [this, hlo, &operand_to_generator](const IrArray::Index& index) {
        return ir_emitter_->EmitElementalConvolution(
            Cast<HloConvolutionInstruction>(hlo),
            operand_to_generator.at(hlo->operand(0)),
            operand_to_generator.at(hlo->operand(1)), index);
      };
    case HloOpcode::kReduce:
      return [this, hlo, &operand_to_generator](const IrArray::Index& index) {
        return ir_emitter_->EmitElementalReduce(
            Cast<HloReduceInstruction>(hlo),
            operand_to_generator.at(hlo->operand(0)),
            operand_to_generator.at(hlo->operand(1)), index);
      };
    default:
      return ElementalIrEmitter::MakeElementGenerator(hlo,
                                                      operand_to_generator);
  }
}
}  // namespace cpu
}  // namespace xla


text:
# ng-i18next - use i18next with [AngularJS](https://www.angularjs.org/) [![Build Status](https://travis-ci.org/i18next/ng-i18next.svg?branch=master)](https://travis-ci.org/i18next/ng-i18next) #

Project goal is to provide an easy way to use [i18next](http://i18next.com/) with [AngularJS](http://angularjs.org/):

- `ng-i18next` directive
- `i18next` filter

First check out the [documentation](http://i18next.com) by Jan Mühlemann.

# Features #
- AngularJS provider, directive and filter
- variable binding (translates again when variable changes)
- nested translations (`$t('hello')`; see [i18next documentation](http://i18next.com/pages/doc_features.html))
- scope variables in translations (if the translation contains directives of variables like `{{hello}}`, they'll get compiled)
- sprintf support (directive and provider)
- support for default values to be displayed before i18next engine is initialized

# Installation #
You can install `ng-i18next` as a bower dependency:

	bower install ng-i18next

# Usage #
First add

- `AngularJS`
- `i18next`
- `ng-i18next`

to your HTML file. `AngularJS` and `i18next` have to be loaded **before** `ng-i18next`!

Make sure you require `jm.i18next` as a dependency of your AngularJS module. Also configurate the provider first:

```js
angular.module('jm.i18next').config(['$i18nextProvider', function ($i18nextProvider) {
	$i18nextProvider.options = {
		lng: 'de',
		useCookie: false,
		useLocalStorage: false,
		fallbackLng: 'dev',
		resGetPath: '../locales/__lng__/__ns__.json',
		defaultLoadingValue: '' // ng-i18next option, *NOT* directly supported by i18next
	};
}]);
```

For testing purposes set up a server. Don't open your files directly because `i18next` then fails to load the language files!

For more options visit the [i18next documentation](http://i18next.com/pages/doc_init.html).

There are two ways to use `ng-i18next`:

## filter ##

```html
<p>{{'hello' | i18next}}</p>
```

=> translates `hello`
```html
<p>{{hello | i18next}}</p>
```

=> translates `$scope.hello`

## directive ##

### Basics ###

```html
<p ng-i18next="hello"></p>
```
=> translates `hello`

```html
<p ng-i18next="{{hello}}"></p>
```
=> translates `$scope.hello`

```html
<p ng-i18next>hello</p>
```
=> translates `hello` (uses the content of the p-tag)

```html
<p ng-i18next>{{hello}}</p>
```
=> translates `$scope.hello` (uses the content of the p-tag)

Note, that HTML isn't compiled!

### HTML ###

```html
<p ng-i18next="[html]hello"></p>
```

=> translates `hello` and compiles HTML

```html
<p ng-i18next="[html]{{hello}}"></p>
```

=> translates `$scope.hello` and compiles HTML

### Attributes ###

```html
<a href="#" ng-i18next="[title]hello">This is a link.</a>
```

=> translates `hello` and sets it as the title

```html
<a href="#" ng-i18next="[title]{{hello}}">This is a link.</a>
```

=> translates `$scope.hello` and sets it as the title

You can combine both, too!

### Attributes + text content ###

```html
<a href="#" ng-i18next="[title]hello;content"></a>
```

=> translates `hello` and sets it as the title
=> translates `content` and sets it as the text of the link.

```html
<a href="#" ng-i18next="[title]{{hello}};{{content}}"></a>
```
=> translates `$scope.hello` and sets it as the title
=> translates `$scope.content` and sets it as the text of the link.

### Attributes + HTML content ###

```html
<a href="#" ng-i18next="[title]hello;[html]content"></a>
```
=> translates `hello` and sets it as the title
=> translates `content` and compiles the HTML as the content of the link.

```html
<a href="#" ng-i18next="[title]{{hello}};[html]{{content}}"></a>
```
=> translates `$scope.hello` and sets it as the title
=> translates `$scope.content` and compiles the HTML as the content of the link.

### Passing Options ###
You can also pass options:

```html
<p ng-i18next="[i18next]({lng:'de'})hello"></p>
```
=> translates `hello` in German (`de`)

### Passing Options + HTML ###
Also options work perfectly together with html:

```html
<p ng-i18next="[html:i18next]({lng:'de'})hello"></p>
```
=> translates `hello` in German (`de`) and compiles it to HTML code.

### Passing Options - sprintf
You can use i18next sprintf feature:

```html
<p ng-i18next="[i18next]({sprintf:['a','b','c','d']})sprintfString">
```

where `sprintfString` could be `The first 4 letters of the english alphabet are: %s, %s, %s and %s` in your translation file.

Using the directive, `postProcess:'sprintf'` isn't neccassary. The directive will add it automatically when using `sprintf` in the options.

---------

For more, see examples.

There are two ways to run the examples:

```sh
gulp serve
```

Run this inside your `ng-i18next` directory.
(This requires you to have NodeJS and gulp to be installed.)

```js
python -m SimpleHTTPServer 8000
```

Create a simple pyhton HTTP server. Run this inside the `ng-i18next` folder.
You must have python installed, of course.

Then go to [`http://localhost:8000`](http://localhost:8000).

---------

# Default values while i18next is initializing #

`i18next` supports providing a `defaultValue` when requesting any translation. But what happens when i18next hasn't been fully initialized yet?

`ng-i18next` adds a `defaultLoadingValue` option, which can be provided either in `$i18nextProvider.options` or with any individual
translation request just like you would `defaultValue`. If i18n strings need to be rendered before i18next is initialized,
these special loading values will be used instead.

## Default values - Examples ##
```js
$i18nextProvider.options = {
	/* ... */
	defaultLoadingValue: ''
};
```

(in template)

```html
<p>{{'hello' | i18next}}</p>
```

=> displays an empty string (visually nothing) until i18next is initialized, then translates `hello`

```html
<p>{{'hello' | i18next:{'defaultLoadingValue':'Loading...'} }}</p>
```

=> displays "Loading..." until i18next is loaded, then translates `hello`

```html
<p>{{'not-translated-welcome-key' | i18next:{'defaultLoadingValue':'Loading...', 'defaultValue':'Welcome!'} }}</p>
```

=> displays "Loading..." until i18next is loaded, then translates `not-translated-welcome-key` with default of "Welcome!"
if the key is not defined in your i18n file

---------

# Contribute #

To contribute, you must have:

- [Node.js](http://nodejs.org/)
- [bower](http://bower.io/)
- [Gulp](http://gulpjs.com/)

installed.

Load all dependencies using [`npm`](https://npmjs.org/) and [`bower`](http://bower.io/):

	npm install
	bower install

Build `ng-i18next.js` using Gulp:

	gulp build

Test `ng-i18next.js` using Gulp:

	gulp test

---------

# Examples #

You can run the examples using:

	gulp serve

_(note that you have to be in the root directory of this project)_

Do not just open the HTML files. That won't work.

---------

# Supported browsers #

`ng-i18next` is tested with these browsers:

 - latest Firefox
 - latest Chrome
 - IE9 and above

IE8 isn't supported.
`ng-i18next` should work with every browser that is supported by AngularJS.

However, last time we checked, just adding polyfills do the job on IE8.

---------

# Changelog #

For changelog file please see CHANGELOG.md

---------

# License #

[MIT License](https://github.com/i18next/ng-i18next/blob/master/LICENSE)


text:
using DarkSoulsII.DebugView.Core;

namespace DarkSoulsII.DebugView.Model.Resources.Param.Character
{
    public class RelatePhysStatToLevelStat : IReadable<RelatePhysStatToLevelStat>
    {
        public RelatePhysStatToLevelStat Read(IPointerFactory pointerFactory, IReader reader, int address, bool relative = false)
        {
            return this;
        }
    }
}