text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

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
STANFORD UNIVERSITY 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.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.util;

import java.net.*;
import java.io.*;
import java.util.*;
import junit.framework.TestCase;
import org.lockss.test.*;
import org.lockss.daemon.*;

public class TestSyslogTarget extends LockssTestCase {

  public TestSyslogTarget(String msg){
    super(msg);
  }

  private SyslogTarget newSyslogTarget() {
    SyslogTarget target = new SyslogTarget();
    target.init();
    return target;
  }

  public void testSeverityToFacility(){
    assertEquals(0,
		 SyslogTarget.loggerSeverityToSyslogSeverity(Logger.LEVEL_CRITICAL));
    assertEquals(2,
		 SyslogTarget.loggerSeverityToSyslogSeverity(Logger.LEVEL_ERROR));
    assertEquals(4,
		 SyslogTarget.loggerSeverityToSyslogSeverity(Logger.LEVEL_WARNING));
    assertEquals(5,
		 SyslogTarget.loggerSeverityToSyslogSeverity(Logger.LEVEL_INFO));
    assertEquals(6,
		 SyslogTarget.loggerSeverityToSyslogSeverity(Logger.LEVEL_DEBUG));
    assertEquals(7,
		 SyslogTarget.loggerSeverityToSyslogSeverity(Logger.LEVEL_DEBUG2));
    assertEquals(7,
		 SyslogTarget.loggerSeverityToSyslogSeverity(Logger.LEVEL_DEBUG3));
  }

  private void setConfig(String host, int port) throws Exception {
    ConfigurationUtil.addFromArgs(SyslogTarget.PARAM_HOST, host,
				  SyslogTarget.PARAM_PORT, ""+port);
  }

  public void testHandleMessageGetsMessageRight() throws Exception{
    int expectedPort = 1234;
    String expectedHost = "199.99.9.99";
    ConfigurationUtil.addFromArgs(SyslogTarget.PARAM_HOST, expectedHost,
				  SyslogTarget.PARAM_PORT, expectedPort+"",
				  SyslogTarget.PARAM_FACILITY, 8+"");

    String expectedDataStr = "<66>LOCKSS: TestMessage";
    byte[] expectedData = expectedDataStr.getBytes();

    SyslogTarget target = newSyslogTarget();
    MockDatagramSocket ds = new MockDatagramSocket();
    target.handleMessage(ds, Logger.LEVEL_ERROR, "TestMessage");
    Vector packets = ds.getSentPackets();
    assertEquals(1, packets.size());
    DatagramPacket packet = (DatagramPacket)packets.elementAt(0);
    assertEquals(expectedPort, packet.getPort());
    assertEquals(expectedHost, packet.getAddress().getHostAddress());

    byte[] data = packet.getData();
    assertEquals(new String(expectedData), new String(data));
    assertEquals(expectedData.length, packet.getLength());
  }

  public void testActualDatagramComm() throws Exception {
    int port = 9091;
    ConfigurationUtil.addFromArgs(SyslogTarget.PARAM_HOST, "127.0.0.1",
				  SyslogTarget.PARAM_PORT, ""+port);
    DatagramSocketListener dsl = new DatagramSocketListener(port, 1);
    try{
      dsl.beginListening();
    }
    catch (BindException e) {
      fail("Could not bind to port " + port + ": " + e);
    }
    String expectedMsg = "<146>LOCKSS: TestMessage";

    byte[] msgBytes = expectedMsg.getBytes();

    SyslogTarget target = newSyslogTarget();
    target.handleMessage((Logger)null, Logger.LEVEL_ERROR, "TestMessage");

    DatagramPacket recPacket = dsl.getPacket();
    assertTrue(recPacket != null);

    byte[] recData = recPacket.getData();

    assertEquals(msgBytes.length, recPacket.getLength());
    assertEquals(new String(expectedMsg),
		 new String(recData).substring(0, expectedMsg.length()));
  }
}

redpajama_set_name: RedPajamaGithub


text:
#include "sdb.h"
#include "ht_pp.h"
#include "ht.inc"

static HtName_(Ht)* internal_ht_default_new(ut32 size, ut32 prime_idx, HT_(DupValue) valdup, HT_(KvFreeFunc) pair_free, HT_(CalcSizeV) calcsizeV) {
	HT_(Options) opt = {
		.cmp = (HT_(ListComparator))strcmp,
		.hashfn = (HT_(HashFunction))sdb_hash,
		.dupkey = (HT_(DupKey))strdup,
		.dupvalue = valdup,
		.calcsizeK = (HT_(CalcSizeK))strlen,
		.calcsizeV = calcsizeV,
		.freefn = pair_free,
		.elem_size = sizeof (HT_(Kv)),
	};
	return internal_ht_new (size, prime_idx, &opt);
}

// creates a default HtPP that has strings as keys
SDB_API HtName_(Ht)* Ht_(new)(HT_(DupValue) valdup, HT_(KvFreeFunc) pair_free, HT_(CalcSizeV) calcsizeV) {
	return internal_ht_default_new (ht_primes_sizes[0], 0, valdup, pair_free, calcsizeV);
}

static void free_kv_key(HT_(Kv) *kv) {
	free (kv->key);
}

// creates a default HtPP that has strings as keys but does not dup, nor free the values
SDB_API HtName_(Ht)* Ht_(new0)(void) {
	return Ht_(new) (NULL, free_kv_key, NULL);
}

SDB_API HtName_(Ht)* Ht_(new_size)(ut32 initial_size, HT_(DupValue) valdup, HT_(KvFreeFunc) pair_free, HT_(CalcSizeV) calcsizeV) {
	ut32 i = 0;

	while (i < S_ARRAY_SIZE (ht_primes_sizes) &&
		ht_primes_sizes[i] * LOAD_FACTOR < initial_size) {
		i++;
	}
	if (i == S_ARRAY_SIZE (ht_primes_sizes)) {
		i = UT32_MAX;
	}

	ut32 sz = compute_size (i, (ut32)(initial_size * (2 - LOAD_FACTOR)));
	return internal_ht_default_new (sz, i, valdup, pair_free, calcsizeV);
}


text:
import BasePage from "../app-front-base";
import Editor from "../component/editor";
import "../lib/qrcode";

class ArticlePage extends BasePage {
    constructor() {
        super();
        this.editor = new Editor();
    }

    initQRCode() {
        $("#qr-address").qrcode({
            width: 196,
            height: 196,
            text: encodeURI(window.location.href)
        });

        $('.ui.qr.icon').popup({
            position: "bottom center",
            inline: true,
            on: "click"
        });
    }
}

$(document).ready(() => {
    var page = new ArticlePage();
    page.editor.loadAsReader();
    page.editor.loadContent($("#article-reader").data("id"), page.editor.initContent);
    page.initQRCode();
});


text:
static NSUInteger gcdInteger(NSUInteger a,NSUInteger b){
    if(a>=b){
        if(b==0){
            return b;
        }
        NSUInteger rem=a%b;
        if(rem==0){
            return b;
        }else{
            return gcdInteger(b,rem);
        }
    }else{
        return gcdInteger(b,a);
    }
}

@implementation FVGifAnimation
+ (BOOL)canAnimateImageSource:(CGImageSourceRef)imgSrc{
    if(imgSrc==NULL) return false;
    CFStringRef type= CGImageSourceGetType(imgSrc);
    if([(NSString*)type isEqual:@"com.compuserve.gif"]){
        return CGImageSourceGetCount(imgSrc)>1;
    }
    return false;

}

+ (BOOL)canAnimateImageData:(NSData*)data{
    if(data){
        CGImageSourceRef imgSrc= CGImageSourceCreateWithData((CFDataRef)data, NULL);
        if(imgSrc==NULL) return false;
        BOOL result=[self canAnimateImageSource:imgSrc];
        CFRelease(imgSrc);
        return result;
    }
    return false;
}
+ (BOOL)canAnimateImageURL:(NSURL*)url{
    if(url){
        CGImageSourceRef imgSrc= CGImageSourceCreateWithURL((CFURLRef)url, NULL);
        if(imgSrc==NULL) return false;
        BOOL result=[self canAnimateImageSource:imgSrc];
        CFRelease(imgSrc);
        return result;
    }
    return false;
}

- (NSArray*)delaysForImageSource:(CGImageSourceRef)iSrc{
    size_t imageCount=CGImageSourceGetCount(iSrc);
    NSMutableArray* delays=[NSMutableArray array];
    for(size_t i=0;i<imageCount;i++){
        CFDictionaryRef propI= CGImageSourceCopyPropertiesAtIndex(iSrc, i, NULL);
        double delay=0.1;
        if(propI){
            CFDictionaryRef gifProp=CFDictionaryGetValue(propI, kCGImagePropertyGIFDictionary);
            if(gifProp){
                CFNumberRef delayVal=CFDictionaryGetValue(gifProp, kCGImagePropertyGIFDelayTime);
                delay=[(NSNumber*)delayVal doubleValue];
            }
            CFRelease(propI);
        }
        [delays addObject:[NSNumber numberWithDouble:delay]];
    }
    return [NSArray arrayWithArray:delays];
}

- (double)totalDurationForDelays:(NSArray*)delays{
    double result=0.0;
    for(NSNumber* num in delays){
        result+=[num doubleValue];
    }
    return result;
}

- (NSUInteger)gcdInNumbers:(NSIndexSet*)set{
    NSMutableIndexSet* delays=[[set mutableCopy] autorelease];
    if([delays count]==0 ){return 0;}
    while([delays count]>1){
        NSUInteger twoDelays[2];
        [delays getIndexes:twoDelays maxCount:2 inIndexRange:nil];
        [delays removeIndex:twoDelays[0]];
        [delays removeIndex:twoDelays[1]];
        NSUInteger m= gcdInteger(twoDelays[0],twoDelays[1]);
        [delays addIndex:m];
    }
    return [delays firstIndex];
}

-(NSUInteger)timesliceForDelays:(NSArray*)delays{
    NSMutableIndexSet* delaySet=[NSMutableIndexSet indexSet];
    for(NSNumber* num in delays){
        [delaySet addIndex:round([num doubleValue]*100.0)];
    }
    return [self gcdInNumbers:delaySet];
}

- (NSArray*)animationImagesForImageSource:(CGImageSourceRef)iSrc withDelays:(NSArray*)delays{
    NSMutableArray* animationImages=[NSMutableArray array];
    NSUInteger timeslice=[self timesliceForDelays:delays];
    size_t images_count=CGImageSourceGetCount(iSrc);
    for(size_t i=0;i<images_count;i++){
        CGImageRef image=CGImageSourceCreateImageAtIndex(iSrc, i, NULL);
        if(image){
            UIImage* uiimage=[[UIImage alloc] initWithCGImage:image];
            NSUInteger times=round([[delays objectAtIndex:i] doubleValue]*100)/timeslice;
            for(NSUInteger j=0;j<times;j++){
                [animationImages addObject:uiimage];
            }
            [uiimage release];
            CGImageRelease(image);
        }
    }
    return [NSArray arrayWithArray:animationImages];
}

- (void)loadImagesFromImageSource:(CGImageSourceRef)imgSrc{
    if(imgSrc && [[self class] canAnimateImageSource:imgSrc]){
        CFStringRef type= CGImageSourceGetType(imgSrc);
        if([(NSString*)type isEqual:@"com.compuserve.gif"]){
            NSInteger loopCount=0;
            CFDictionaryRef prop=CGImageSourceCopyProperties(imgSrc, NULL);
            CFDictionaryRef gifProp=CFDictionaryGetValue(prop, kCGImagePropertyGIFDictionary);
            if(gifProp){
                CFNumberRef loopNum=CFDictionaryGetValue(gifProp, kCGImagePropertyGIFLoopCount);
                loopCount=[(NSNumber*)loopNum integerValue];
            }
            CFRelease(prop);
            NSArray* delays=[self delaysForImageSource:imgSrc];
            self->duration=[self totalDurationForDelays:delays];
            self->images=[[self animationImagesForImageSource:imgSrc withDelays:delays] retain];
            self->loops=loopCount;
        }
    }
}
- (id)initWithData:(NSData*)data{
    self=[self init];
    if(self){
        CGImageSourceRef imgSrc= CGImageSourceCreateWithData((CFDataRef)data, NULL);
        if(imgSrc){
            [self loadImagesFromImageSource:imgSrc];
            CFRelease(imgSrc);
        }
    }
    return self;
}
- (id)initWithURL:(NSURL*)url{
    self=[self init];
    if(self){
        CGImageSourceRef imgSrc= CGImageSourceCreateWithURL((CFURLRef)url, NULL);
        if(imgSrc){
            [self loadImagesFromImageSource:imgSrc];
            CFRelease(imgSrc);
        }
    }
    return self;
}

- (void)setAnimationToImageView:(UIImageView*)imageView{
    if(self->images!=nil){
        imageView.animationImages=self->images;
        imageView.animationDuration=self->duration;
        imageView.animationRepeatCount=self->loops;
    }
}

- (BOOL) canAnimate{
    return self->images!=nil;
}

-(void)dealloc{
    [images release];
    [super dealloc];
}
@end


text:
<?php

namespace Doctrine\ORM\Query\AST;

/**
 * ConditionalPrimary ::= SimpleConditionalExpression | "(" ConditionalExpression ")"
 *
 * @link    www.doctrine-project.org
 * @since   2.0
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class ConditionalPrimary extends Node
{
    /**
     * @var Node|null
     */
    public $simpleConditionalExpression;

    /**
     * @var ConditionalExpression|null
     */
    public $conditionalExpression;

    /**
     * @return bool
     */
    public function isSimpleConditionalExpression()
    {
        return (bool) $this->simpleConditionalExpression;
    }

    /**
     * @return bool
     */
    public function isConditionalExpression()
    {
        return (bool) $this->conditionalExpression;
    }

    /**
     * {@inheritdoc}
     */
    public function dispatch($sqlWalker)
    {
        return $sqlWalker->walkConditionalPrimary($this);
    }
}


text:
namespace Neolib {
template <typename T1, typename T2, typename T3> struct Triple {
  T1 first;
  T2 second;
  T3 third;
};
} // namespace Neolib


text:
'use strict'

import micro from 'micro'
import test from 'ava'
import listen from 'test-listen' // testear microservicios
import request from 'request-promise' // modulo para hacer http request haciendo promesas, cómo por ejemplo con fetch api pero en este caso, esto correrá en el servidor
import pictures from '../pictures'
import utils from '../lib/utils'
import fixtures from './fixtures'
import config from '../config'

test.beforeEach(async t => {
  let srv = micro(pictures)
  t.context.url = await listen(srv)
})

test('GET /list', async t => {
  let images = fixtures.getImages()
  let url = t.context.url
  let options = {
    method: 'GET',
    uri: `${url}/list`,
    json: true
  }

  let body = await request(options)
  t.deepEqual(body, images)
})

test('GET /:id', async t => {
  let image = fixtures.getImage()

  let url = t.context.url

  let body = await request({ uri: `${url}/${image.publicId}`, json: true })
  t.deepEqual(body, image)
})

/*
test('POST /', async t =>  {
  let image = fixtures.getImage()
  let url = t.context.url

  let options = {
    method: 'POST',
    uri: url,
    json: true,
    body:{
      description: image.description,
      src: image.src,
      userId: image.userId
    },
    resolveWithFullResponse: true
  }

  let response = await request(options)

  //el atributo resolveWithFullResponse nos permite tener acceso a todo el objeto de respuesta, ya q por defecto requesto promise solo devuelve el atributo body

  t.is(response.statusCode, 201)
  t.deepEqual(response.body, image)
})*/

test('POST /:id/like', async t => {
  let image = fixtures.getImage()
  let url = t.context.url

  let options = {
    method: 'POST',
    uri: `${url}/${image.id}/like`,
    json: true
  }

  let body = await request(options)
  let imageNew =  JSON.parse(JSON.stringify(image))
  imageNew.liked = true
  imageNew.likes = 1

  t.deepEqual(body, imageNew)
})

test('GET /tag/:tag', async t => {
  let images = fixtures.getImagesByTag()
  let url = t.context.url

  let options = {
    method: 'GET',
    uri: `${url}/tag/awesome`,
    json: true
  }

  let body = await request(options)
  t.deepEqual(body, images)
})

test('POST WITHOUT JWT /', async t =>  {
  let image = fixtures.getImage()
  let url = t.context.url

  let options = {
    method: 'POST',
    uri: url,
    json: true,
    body:{
      description: image.description,
      src: image.src,
      userId: image.userId
    },
    resolveWithFullResponse: true
  }

  await t.throws(request(options), /invalid token/)
})

test('POST WITH JWT /', async t =>  {
  let image = fixtures.getImage()
  let url = t.context.url
  let token = await utils.signToken({userId:image.userId}, config.secret)

  let options = {
    method: 'POST',
    uri: url,
    json: true,
    body:{
      description: image.description,
      src: image.src,
      userId: image.userId
    },
   headers: {
     'Authorization': `Bearer ${token}`
   },
    resolveWithFullResponse: true
  }

  let response = await request(options)

  t.is(response.statusCode, 201)
  t.deepEqual(response.body, image)
})


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

namespace Phan\Tests;

use Phan\CodeBase;

interface CodeBaseAwareTestInterface {

    /** @param CodeBase $codeBase */
    public function setCodeBase(CodeBase $codeBase = null);

}


text:
from .. import BaseApi, NamedEndpoint
from .urls import ChampionMasteryApiV4Urls

class ChampionMasteryApiV4(NamedEndpoint):
    """
    This class wraps the Champion-Mastery-v4 Api calls provided by the Riot API.

    See https://developer.riotgames.com/api-methods/#champion-mastery-v4/ for more
    detailed information
    """

    def __init__(self, base_api: BaseApi):
        """
        Initialize a new ChampionMasteryApiV4 which uses the provided base_api

        :param BaseApi base_api: the root API object to use for making all requests.
        """
        super().__init__(base_api, self.__class__.__name__)

    def by_summoner(self, region: str, encrypted_summoner_id: str):
        """
        Get all champion mastery entries.

        :param string region:                   the region to execute this request on
        :param string encrypted_summoner_id:    Summoner ID associated with the player

        :returns: List[ChampionMasteryDTO]: This object contains a list of Champion
                                            Mastery information for player and champion
                                            combination.
        """
        return self._request_endpoint(
            self.by_summoner.__name__,
            region,
            ChampionMasteryApiV4Urls.by_summoner,
            encrypted_summoner_id=encrypted_summoner_id,
        )

    def by_summoner_by_champion(
        self, region: str, encrypted_summoner_id: str, champion_id: int
    ):
        """
        Get a champion mastery by player ID and champion ID.

        :param string region:                   the region to execute this
                                                request on
        :param string encrypted_summoner_id:    Summoner ID associated with the player
        :param long champion_id:                Champion ID to retrieve Champion
                                                Mastery for

        :returns: ChampionMasteryDTO: This object contains single Champion Mastery
                                      information for player and champion combination.
        """
        return self._request_endpoint(
            self.by_summoner_by_champion.__name__,
            region,
            ChampionMasteryApiV4Urls.by_summoner_by_champion,
            encrypted_summoner_id=encrypted_summoner_id,
            champion_id=champion_id,
        )

    def scores_by_summoner(self, region: str, encrypted_summoner_id: str):
        """
        Get a player's total champion mastery score, which is the sum of individual
        champion mastery levels

        :param string region:                   the region to execute this request on
        :param string encrypted_summoner_id:    Summoner ID associated with the player

        :returns: int
        """
        return self._request_endpoint(
            self.scores_by_summoner.__name__,
            region,
            ChampionMasteryApiV4Urls.scores_by_summoner,
            encrypted_summoner_id=encrypted_summoner_id,
        )


text:
using System;
using System.CodeDom.Compiler;
using TobascoTest.IGenerateRepository;
using static Dapper.SqlMapper;
using Dapper;
using System.Linq;
using TobascoTest.GeneratedEntity;
using Tobasco;

namespace TobascoTest.IGenerateRepository
{
	[GeneratedCode("Tobasco", "1.0.0.0")]
	public partial interface ICPK10Repository
	{

		CPK10 Save(CPK10 cpk10);
CPK10 GetById(long id);
	}
}


text:
from CRABClient.UserUtilities import config, getUsernameFromSiteDB
config = config()

config.General.transferOutputs = True
config.General.transferLogs = True
config.JobType.allowUndistributedCMSSW = True

config.JobType.pluginName = 'Analysis'
config.JobType.psetName = 'ConfFile_cfg.py'
config.Data.inputDataset = '/HIMinimumBias2/HIRun2015-25Aug2016-v1/AOD'
config.Data.inputDBS = 'global'
config.Data.lumiMask = 'cert_263380_263614_PromptReco_HICollisions15_JSON_v2.txt'
config.Data.splitting = 'FileBased'
config.Data.unitsPerJob = 20
config.Data.outLFNDirBase = '/store/user/tuos/mixedHarmonics/v03Ana_5TevCentPar_sep25E'
config.Data.publication = False
config.Data.outputDatasetTag = 'pbpb2015_flowcorr_v03Ana_5TevCentPar_sep25E'

config.Site.storageSite = 'T2_US_Vanderbilt'

if __name__ == '__main__':
   from CRABAPI.RawCommand import crabCommand
   from CRABClient.ClientExceptions import ClientException
   from httplib import HTTPException

   config.General.workArea = 'pbpb2015_flowcorr_v03Ana_5TevCentPar_sep25E'

   def submit(config):
      try:
           crabCommand('submit', config = config)
      except HTTPException as hte:
           print "Failed submitting task: %s" % (hte.headers)
      except ClientException as cle:
          print "Failed submitting task: %s" % (cle)

   for num in range(0,1):

       print "Submitting Data Set %d " % (num+1)

       if num == 0:
           RequestName = 'pbpb2015_flowcorr_v03Ana_5TevCentPar_sep25E'
           DataSetName = '/HIMinimumBias2/HIRun2015-25Aug2016-v1/AOD'
           LumiMasks = 'cert_263380_263614_PromptReco_HICollisions15_JSON_v2.txt'
           OutDirBase = '/store/user/tuos/mixedHarmonics/v03Ana_5TevCentPar_sep25E'

       config.General.requestName = RequestName
       config.Data.inputDataset = DataSetName
       config.Data.lumiMask = LumiMasks
       config.Data.outLFNDirBase = OutDirBase
       submit(config)

# python crab3_multicrab_cfg.py to execute
# ./multicrab -c status -w crab_projects/ to check status


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Services.Exceptions
{
    class ClusterGroupNotFoundException : Exception
    {
    }
}


text:
package org.hibernate.id;
import org.hibernate.HibernateException;

/**
 * Thrown by <tt>IdentifierGenerator</tt> implementation class when
 * ID generation fails.
 *
 * @see IdentifierGenerator
 * @author Gavin King
 */

public class IdentifierGenerationException extends HibernateException {

	public IdentifierGenerationException(String msg) {
		super(msg);
	}

	public IdentifierGenerationException(String msg, Throwable t) {
		super(msg, t);
	}

}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("channels", "0020_remove_article_thumbnail")]

    operations = [
        migrations.AddField(
            model_name="post", name="preview_text", field=models.TextField(null=True)
        )
    ]


text:
package edu.uci.ics.hyracks.api.job;

import java.io.Serializable;
import java.util.Map;

import edu.uci.ics.hyracks.api.dataflow.OperatorDescriptorId;

public class JobInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    private final JobId jobId;

    private final JobStatus status;

    private final Map<OperatorDescriptorId, Map<Integer, String>> operatorLocations;

    public JobInfo(JobId jobId, JobStatus jobStatus, Map<OperatorDescriptorId, Map<Integer, String>> operatorLocations) {
        this.jobId = jobId;
        this.operatorLocations = operatorLocations;
        this.status = jobStatus;
    }

    public JobId getJobId() {
        return jobId;
    }

    public JobStatus getStatus() {
        return status;
    }

    public Map<OperatorDescriptorId, Map<Integer, String>> getOperatorLocations() {
        return operatorLocations;
    }

}


text:
.class public Landroid/webkit/WebView$PrivateAccess;
.super Ljava/lang/Object;
.source "WebView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/webkit/WebView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1
    name = "PrivateAccess"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/webkit/WebView;

# direct methods
.method public constructor <init>(Landroid/webkit/WebView;)V
    .locals 0

    .prologue
    .line 2158
    iput-object p1, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

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

    return-void
.end method

# virtual methods
.method public awakenScrollBars(I)V
    .locals 1
    .param p1, "duration"    # I

    .prologue
    .line 2215
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/webkit/WebView;->awakenScrollBars(I)Z
    invoke-static {v0, p1}, Landroid/webkit/WebView;->access$1300(Landroid/webkit/WebView;I)Z

    .line 2216
    return-void
.end method

.method public awakenScrollBars(IZ)V
    .locals 1
    .param p1, "duration"    # I
    .param p2, "invalidate"    # Z

    .prologue
    .line 2219
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/webkit/WebView;->awakenScrollBars(IZ)Z
    invoke-static {v0, p1, p2}, Landroid/webkit/WebView;->access$1400(Landroid/webkit/WebView;IZ)Z

    .line 2220
    return-void
.end method

.method public getHorizontalScrollFactor()F
    .locals 1

    .prologue
    .line 2227
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/webkit/WebView;->getHorizontalScrollFactor()F
    invoke-static {v0}, Landroid/webkit/WebView;->access$1600(Landroid/webkit/WebView;)F

    move-result v0

    return v0
.end method

.method public getHorizontalScrollbarHeight()I
    .locals 1

    .prologue
    .line 2239
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/webkit/WebView;->getHorizontalScrollbarHeight()I
    invoke-static {v0}, Landroid/webkit/WebView;->access$1800(Landroid/webkit/WebView;)I

    move-result v0

    return v0
.end method

.method public getVerticalScrollFactor()F
    .locals 1

    .prologue
    .line 2223
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/webkit/WebView;->getVerticalScrollFactor()F
    invoke-static {v0}, Landroid/webkit/WebView;->access$1500(Landroid/webkit/WebView;)F

    move-result v0

    return v0
.end method

.method public onScrollChanged(IIII)V
    .locals 1
    .param p1, "l"    # I
    .param p2, "t"    # I
    .param p3, "oldl"    # I
    .param p4, "oldt"    # I

    .prologue
    .line 2235
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    invoke-virtual {v0, p1, p2, p3, p4}, Landroid/webkit/WebView;->onScrollChanged(IIII)V

    .line 2236
    return-void
.end method

.method public overScrollBy(IIIIIIIIZ)V
    .locals 10
    .param p1, "deltaX"    # I
    .param p2, "deltaY"    # I
    .param p3, "scrollX"    # I
    .param p4, "scrollY"    # I
    .param p5, "scrollRangeX"    # I
    .param p6, "scrollRangeY"    # I
    .param p7, "maxOverScrollX"    # I
    .param p8, "maxOverScrollY"    # I
    .param p9, "isTouchEvent"    # Z

    .prologue
    .line 2210
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    move v1, p1

    move v2, p2

    move v3, p3

    move v4, p4

    move v5, p5

    move/from16 v6, p6

    move/from16 v7, p7

    move/from16 v8, p8

    move/from16 v9, p9

    # invokes: Landroid/webkit/WebView;->overScrollBy(IIIIIIIIZ)Z
    invoke-static/range {v0 .. v9}, Landroid/webkit/WebView;->access$1200(Landroid/webkit/WebView;IIIIIIIIZ)Z

    .line 2212
    return-void
.end method

.method public setMeasuredDimension(II)V
    .locals 1
    .param p1, "measuredWidth"    # I
    .param p2, "measuredHeight"    # I

    .prologue
    .line 2231
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/webkit/WebView;->setMeasuredDimension(II)V
    invoke-static {v0, p1, p2}, Landroid/webkit/WebView;->access$1700(Landroid/webkit/WebView;II)V

    .line 2232
    return-void
.end method

.method public setScrollXRaw(I)V
    .locals 1
    .param p1, "scrollX"    # I

    .prologue
    .line 2250
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # setter for: Landroid/webkit/WebView;->mScrollX:I
    invoke-static {v0, p1}, Landroid/webkit/WebView;->access$2002(Landroid/webkit/WebView;I)I

    .line 2251
    return-void
.end method

.method public setScrollYRaw(I)V
    .locals 1
    .param p1, "scrollY"    # I

    .prologue
    .line 2255
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # setter for: Landroid/webkit/WebView;->mScrollY:I
    invoke-static {v0, p1}, Landroid/webkit/WebView;->access$2102(Landroid/webkit/WebView;I)I

    .line 2256
    return-void
.end method

.method public super_computeScroll()V
    .locals 1

    .prologue
    .line 2169
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->computeScroll()V
    invoke-static {v0}, Landroid/webkit/WebView;->access$301(Landroid/webkit/WebView;)V

    .line 2170
    return-void
.end method

.method public super_dispatchKeyEvent(Landroid/view/KeyEvent;)Z
    .locals 1
    .param p1, "event"    # Landroid/view/KeyEvent;

    .prologue
    .line 2189
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/ViewGroup;->dispatchKeyEvent(Landroid/view/KeyEvent;)Z
    invoke-static {v0, p1}, Landroid/webkit/WebView;->access$801(Landroid/webkit/WebView;Landroid/view/KeyEvent;)Z

    move-result v0

    return v0
.end method

.method public super_getScrollBarStyle()I
    .locals 1

    .prologue
    .line 2161
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->getScrollBarStyle()I
    invoke-static {v0}, Landroid/webkit/WebView;->access$101(Landroid/webkit/WebView;)I

    move-result v0

    return v0
.end method

.method public super_onDrawVerticalScrollBar(Landroid/graphics/Canvas;Landroid/graphics/drawable/Drawable;IIII)V
    .locals 7
    .param p1, "canvas"    # Landroid/graphics/Canvas;
    .param p2, "scrollBar"    # Landroid/graphics/drawable/Drawable;
    .param p3, "l"    # I
    .param p4, "t"    # I
    .param p5, "r"    # I
    .param p6, "b"    # I

    .prologue
    .line 2244
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    move-object v1, p1

    move-object v2, p2

    move v3, p3

    move v4, p4

    move v5, p5

    move v6, p6

    # invokes: Landroid/view/View;->onDrawVerticalScrollBar(Landroid/graphics/Canvas;Landroid/graphics/drawable/Drawable;IIII)V
    invoke-static/range {v0 .. v6}, Landroid/webkit/WebView;->access$1901(Landroid/webkit/WebView;Landroid/graphics/Canvas;Landroid/graphics/drawable/Drawable;IIII)V

    .line 2245
    return-void
.end method

.method public super_onGenericMotionEvent(Landroid/view/MotionEvent;)Z
    .locals 1
    .param p1, "event"    # Landroid/view/MotionEvent;

    .prologue
    .line 2193
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->onGenericMotionEvent(Landroid/view/MotionEvent;)Z
    invoke-static {v0, p1}, Landroid/webkit/WebView;->access$901(Landroid/webkit/WebView;Landroid/view/MotionEvent;)Z

    move-result v0

    return v0
.end method

.method public super_onHoverEvent(Landroid/view/MotionEvent;)Z
    .locals 1
    .param p1, "event"    # Landroid/view/MotionEvent;

    .prologue
    .line 2173
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->onHoverEvent(Landroid/view/MotionEvent;)Z
    invoke-static {v0, p1}, Landroid/webkit/WebView;->access$401(Landroid/webkit/WebView;Landroid/view/MotionEvent;)Z

    move-result v0

    return v0
.end method

.method public super_performAccessibilityAction(ILandroid/os/Bundle;)Z
    .locals 1
    .param p1, "action"    # I
    .param p2, "arguments"    # Landroid/os/Bundle;

    .prologue
    .line 2177
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->performAccessibilityAction(ILandroid/os/Bundle;)Z
    invoke-static {v0, p1, p2}, Landroid/webkit/WebView;->access$501(Landroid/webkit/WebView;ILandroid/os/Bundle;)Z

    move-result v0

    return v0
.end method

.method public super_performLongClick()Z
    .locals 1

    .prologue
    .line 2181
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->performLongClick()Z
    invoke-static {v0}, Landroid/webkit/WebView;->access$601(Landroid/webkit/WebView;)Z

    move-result v0

    return v0
.end method

.method public super_requestFocus(ILandroid/graphics/Rect;)Z
    .locals 1
    .param p1, "direction"    # I
    .param p2, "previouslyFocusedRect"    # Landroid/graphics/Rect;

    .prologue
    .line 2197
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/ViewGroup;->requestFocus(ILandroid/graphics/Rect;)Z
    invoke-static {v0, p1, p2}, Landroid/webkit/WebView;->access$1001(Landroid/webkit/WebView;ILandroid/graphics/Rect;)Z

    move-result v0

    return v0
.end method

.method public super_scrollTo(II)V
    .locals 1
    .param p1, "scrollX"    # I
    .param p2, "scrollY"    # I

    .prologue
    .line 2165
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->scrollTo(II)V
    invoke-static {v0, p1, p2}, Landroid/webkit/WebView;->access$201(Landroid/webkit/WebView;II)V

    .line 2166
    return-void
.end method

.method public super_setFrame(IIII)Z
    .locals 1
    .param p1, "left"    # I
    .param p2, "top"    # I
    .param p3, "right"    # I
    .param p4, "bottom"    # I

    .prologue
    .line 2185
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->setFrame(IIII)Z
    invoke-static {v0, p1, p2, p3, p4}, Landroid/webkit/WebView;->access$701(Landroid/webkit/WebView;IIII)Z

    move-result v0

    return v0
.end method

.method public super_setLayoutParams(Landroid/view/ViewGroup$LayoutParams;)V
    .locals 1
    .param p1, "params"    # Landroid/view/ViewGroup$LayoutParams;

    .prologue
    .line 2201
    iget-object v0, p0, Landroid/webkit/WebView$PrivateAccess;->this$0:Landroid/webkit/WebView;

    # invokes: Landroid/view/View;->setLayoutParams(Landroid/view/ViewGroup$LayoutParams;)V
    invoke-static {v0, p1}, Landroid/webkit/WebView;->access$1101(Landroid/webkit/WebView;Landroid/view/ViewGroup$LayoutParams;)V

    .line 2202
    return-void
.end method


text:
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { classes, combineFunction, DomUtils } from '../Globals'
import * as PropTypes from "prop-types";
import { DropdownItemProps } from 'react-bootstrap/DropdownItem';

export interface ContextMenuPosition {
  left: number;
  top: number;
  width: number; //Necessary for RTL
  children: React.ReactElement<any>[]
}

export interface ContextMenuProps extends React.Props<ContextMenu>, React.HTMLAttributes<HTMLUListElement> {
  position: ContextMenuPosition;
  onHide: () => void;
}

export default class ContextMenu extends React.Component<ContextMenuProps> {
  handleToggle = () => {

  }

  getChildContext() {
    return { toggle: this.handleToggle };
  }

  static childContextTypes = { "toggle": PropTypes.func };

  static getPosition(e: React.MouseEvent<any>, container: HTMLElement): ContextMenuPosition {

    const op = DomUtils.offsetParent(container);

    const rec = op?.getBoundingClientRect();

    var result = ({
      left: e.pageX - (rec ? rec.left : 0),
      top: e.pageY - (rec ? rec.top : 0),
      width: (op ? op.offsetWidth : window.innerWidth)
    }) as ContextMenuPosition;

    return result;
  }

  render() {

    const { position, onHide, ref, ...props } = this.props;

    const style: React.CSSProperties = { zIndex: 9999, display: "block", position: "absolute" };

    style.top = position.top + "px";
    if (document.body.className.contains("rtl-mode"))
      style.right = (position.width - position.left) + "px";
    else
      style.left = position.left + "px";

    const childrens = React.Children.map(this.props.children,
      (rc) => {
        let c = rc as React.ReactElement<DropdownItemProps>;
        return c && React.cloneElement(c, { onClick: combineFunction(c.props.onClick, onHide) } as Partial<DropdownItemProps>);
      });

    const ul = (
      <div {...props as any} className={classes(props.className, "dropdown-menu sf-context-menu")} style={style}>
        {childrens}
      </div>
    );

    return ul;
    //return <RootCloseWrapper onRootClose={onHide}>{ul}</RootCloseWrapper>;
  }

  componentDidMount() {

    document.addEventListener('click', this.handleDocumentClick, true);
    document.addEventListener('touchstart', this.handleDocumentClick, true);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleDocumentClick, true);
    document.removeEventListener('touchstart', this.handleDocumentClick, true);
  }

  handleDocumentClick = (e: MouseEvent | TouchEvent) => {
    if ((e as MouseEvent).which === 3)
      return;

    const container = ReactDOM.findDOMNode(this) as HTMLElement;
    if (container.contains(e.target as Node) &&
      container !== e.target) {
      return;
    }

    this.props.onHide();
  }
}


text:
#ifndef __parserclass__
#define __parserclass__

#include <pelet/LexicalAnalyzerClass.h>
#include <pelet/TokenClass.h>
#include <pelet/ParserTypeClass.h>
#include <unicode/unistr.h>
#include <pelet/Api.h>

/**
\mainpage pelet: Php Easy LanguagE Toolkit. A C++ library for analyzing PHP source code
\section Overview
This doc briefly describes the major design of the pelet parser library.

pelet has the folowing major components:

- Parser
- Lexer
- Parser Implementation

\section Parser
The pelet::ParserClass, along with pelet::ClassObserverClass, pelet::ClassMemberObserverClass,
pelet::FunctionObserverClass, pelet::VariableObserverClass, and pelet::ExpressionObserverClass, make up
the "driver" (or main entry point) to pelet. ParserClass takes as input a string (or file) of PHP source code and
extracts artifacts from it (classes, functions, methods, etc..).

To use the parser, a user will create a class that defines the callbacks for each PHP artifact (class, function,
method, etc). The user will register these callbacks with the parser. When pelet::ParserClass::ScanFile is called,
the bison parser rules start looking for syntax rules. The parser will ask the lexer for tokens.  As soon as a
specific rule is hit, then the proper parser observer callback gets called. For example, when the parser hits
the "class" rule (ie "class MyClass {") then the class observer will get called; and the observer will get the
identifer ("MyClass") along with other info (signature, comment).

The important thing to note here is that the callbacks happen while ParserClass::ScanFile still has control.
ParserClass::ScanFile does not return control until the entire file has been parsed; multiple callbacks will have
been called before ParserClass::ScanFile returns.  For this reason, it is important that ParserClass::ScanFile
should not be called within any of the observers.

A word on concurrency: The pelet parser does not keep global state (it is a "pure" bison parser), but the pelet
parser is not thread-safe.  If pelet is used on a multi-threaded app, each thread should have its own instance
of pelet::ParserClass.

\section Lexer
The pelet::LexicalAnalyzerClass is used to tokenize the source code (turn strings into tokens). The
details of the implementation can be found in the \ref LexerDetailsPage page.

\section ParserImplementation Parser Implementation
This is a parser generated with the help of Bison. This used to follow the PHP rules;
for example after "function" comes the function name; after "if" comes a "(" and so on...)
When the syntax rules hit an artifact (for example a class) the syntax rules will call the proper observer.
The details of the implementation can be found in the \ref ParserImplementationDetailsPage page.
*/
namespace pelet {

/**
 * Holds the results of the lint check.  Currently lint check will stop when
 * the first error is encountered.
 */
class PELET_API LintResultsClass {
public:

	/**
	 * A short description of the error; this is generated by the bison parser and is
	 * not the most user-friendly but it is exactly what PHP displays; might as well
	 * keep it consistant.
	 */
	UnicodeString Error;

	/**
	 * Path to the file in which the error ocurred.
	 * This is what was given to the LintFile() method or ScanFile(std::string, LintResultsClass&) method.
	 * For LintString() results this will be the empty string.
	 */
	std::string File;

	/**
	 * Path to the file in which the error ocurred.
	 * This is what was given to the LintFile() or ScanFile(FILE*, UnicodeString, LintResultsClass&) method.
	 * For LintString() results this will be the empty string.
	 */
	UnicodeString UnicodeFilename;

	/**
	 * If the parser encountered a syntax error, then this object will be filled with
	 * the last known class/method/function where the error occurred.
	 */
	pelet::ScopeClass Scope;

	/**
	 * The line in which the error ocurred. This is 1-based.
	 */
	int LineNumber;

	/**
	 * The character offset in which the error ocurred (with regargs to the start of
	 * the file). This is 0-based.
	 */
	int CharacterPosition;

	LintResultsClass();

	/**
	 * copy the attributes from src to this object.
	 */
	void Copy(const LintResultsClass& src);

	/**
	 * remove any error string
	 */
	void Clear();
};

/**
 * The parser class is designed in a way that can utilized by different pieces of code.  The parser will analyze
 * given code and make calls to the different registered observers.  There are observers for classes, functions, and
 * methods. Not all observers have to be set; for example if a FunctionObserverClass is never registered then the
 * parser will not notify when a function has been found in a piece of code.
 *
 * @code
 *   class EchoAndObserverClass : public ClassObserverClass {
 *
 *     virtual void ClassFound(const UnicodeString& className, const UnicodeString& signature,
 *          const UnicodeString& comment) {
 *       printf("Found Class %s\n", (const char*)className.ToUTF8());
 *     }
 *   }
 *
 *   EchoAndObserverClass echoObserver;
 *   ParserClass parser;
 *   parser.SetClassObserver(&echoObserver);
 *   wxString someFileName = wxT("/some/file.php");
 *   if (!parser.ScanFile(someFileName)) {
 *     puts("Could not find file to parse!");
 *   }
 * @endcode
 *
 * Observers follow the PHP parsing rules to the letter.  If source code is not valid; then observers may not
 * get called.
 *
 * Lint functionality
 *
 * The parser class has the ability to check PHP code for syntax errors. This is done via the LintXXX() methods.
 *
 * @code
 *   ParserClass parser;
 *   std::string file = "/path/to/phpfile.php";
 *   LintResultsClass lintResults;
 *   if (parser.LintFile(file, parserResults)) {
 *     printf("No syntax errors in file %s", (const char*)file.c_str());
 *   }
 *   else {
 *     printf("%s. Error found in file %s on line %d.\n", parserResults.Error, file.c_str(), parserResults.LineNumber);
 *   }
 * @endcode
 */
class PELET_API ParserClass {

public:

	ParserClass();

	/**
	 * Opens and scans the given file; This function will return once the entire
	 * file has been parsed; it will call the proper observers when it encounters
	 * a class, function, or variable declaration. This means that this
	 * parser should not be modified in the observer calls.
	 *
	 * This is a convenience method, it does no handle unicode file names. For that,
	 * see ScanFile(FILE*, UnicodeString, LintResultsClass)
	 *
	 * @param file the file to parse.  Must be a full path.
	 * @param LintResultsClass& results any error message will be populated here
	 * @return bool if file was found and could be parsed successfully
	 */
	bool ScanFile(const std::string& file, LintResultsClass& results);

	/**
	 * Opens and scans the given file; This function will return once the entire
	 * file has been parsed; it will call the proper observers when it encounters
	 * a class, function, or variable declaration. This means that this
	 * parser should not be modified in the observer calls.
	 * This method is given a file pointer, it is useful for example when a file
	 * with a unicode filename is opened by the caller.
	 *
	 * @param file the file to parse, this class will NOT own the file pointer
	 * @param fileName this is the name that will be set in  results.UnicodeFilename when an error happens
	 * @param LintResultsClass& results any error message will be populated here
	 * @return bool if file was found and could be parsed successfully
	 */
	bool ScanFile(FILE* file, const UnicodeString& fileName, LintResultsClass& results);

	/**
	 * Scans the given string. This function will return once the entire
	 * string has been parsed; it will call the proper observers when it encounters
	 * a class, function, or variable declaration. This means that this
	 * parser should not be modified in the observer calls.
	 *
	 * @param const UnicodeString& code the code to parse.
	 * @param LintResultsClass& results any error message will be populated here
	 * @return bool if string could be parsed successfully
	 */
	bool ScanString(const UnicodeString& code, LintResultsClass& results);

	/**
	 * Change the version that this parser can handle. This needs to be called BEFORE ScanFile() or
	 * ScanString()
	 */
	void SetVersion(Versions version);

	/**
	 * Set the class observer.  The observer will get notified when a class is encountered.
	 * Memory management of this pointer should be done by the caller.
	 *
	 * @param ClassObserverClass* observer the object to sent notifications to
	 */
	void SetClassObserver(ClassObserverClass* observer);

	/**
	 * Set the class member observer.  The observer will get notified when a class member is encountered.
	 * Memory management of this pointer should be done by the caller.
	 *
	 * @param ClassMemberObserverClass* observer the object to sent notifications to
	 */
	void SetClassMemberObserver(ClassMemberObserverClass* observer);

	/**
	 * Set the function observer.  The observer will get notified when a function is encountered.
	 * Memory management of this pointer should be done by the caller.
	 *
	 * @param FunctionObserverClass* observer the object to sent notifications to
	 */
	void SetFunctionObserver(FunctionObserverClass* observer);

	/**
	 * Set the variable observer.  The observer will get notified when a new variable has been created.
	 * Memory management of this pointer should be done by the caller.
	 *
	 * There are performance implications if you call this method; if you want to be notified
	 * of variables then the full PHP parser is used; and parsing a file can be memory intensive.
	 *
	 * @param VariableObserverClass* observer the object to sent notifications to
	 */
	void SetVariableObserver(VariableObserverClass* observer);

	/**
	 * Set the expression observer.  The observer will get notified when a new expression has been created.
	 * Memory management of this pointer should be done by the caller.
	 *
	 * There are performance implications if you call this method; if you want to be notified
	 * of expressions then the full PHP parser is used; and parsing a file can be memory intensive.
	 *
	 * @param ExpressionObserverClass* observer the object to sent notifications to
	 */
	void SetExpressionObserver(ExpressionObserverClass* expressionObserver);

	/**
	 * Perform a TRUE PHP syntax check on the entire file. This syntax check is based on PHP 5.3
	 * or PHP 5.4 depending on whether SetVersion() was called.
	 *
	 * Note that this is not entirely the same as 'php -l' command; the PHP lint command detects
	 * duplicate function  / class names where as this lint check method does not.
	 *
	 * Returns true if the file had no syntax errors. Note that a file that does not have
	 * any PHP code will be considered a good file (a PHP file that has only HTML is
	 * considered good and true will be returned).
	 *
	 * This is a convenience method; unicode filenames are not handled.
	 *
	 * @param file the file to parse.  Must be a full path.
	 * @param LintResultsClass& results any error message will be populated here
	 * @return bool true if file was found and had no syntax errors.
	 */
	bool LintFile(const std::string& file, LintResultsClass& results);

	/**
	 * Perform a TRUE PHP syntax check on the entire file. This syntax check is based on PHP 5.3
	 * or PHP 5.4 depending on whether SetVersion() was called.
	 *
	 * Note that this is not entirely the same as 'php -l' command; the PHP lint command detects
	 * duplicate function  / class names where as this lint check method does not.
	 *
	 * Returns true if the file had no syntax errors. Note that a file that does not have
	 * any PHP code will be considered a good file (a PHP file that has only HTML is
	 * considered good and true will be returned).
	 *
	 * @param FILE* file the file to parse.  Must be an opened file pointer, this class will NOT own the file pointer
	 * @param fileName this is the name that will be set in  results.UnicodeFilename when an error happens
	 * @param LintResultsClass& results any error message will be populated here
	 * @return bool true if file was found and had no syntax errors.
	 */
	bool LintFile(FILE* file, const UnicodeString& filename, LintResultsClass& results);

	/**
	 * Perform a syntax check on the given source code. Source code is assumed to be
	 * all code (HTML will not be skipped, and will result in syntax errors). The PHP
	 * open tag is optional.
	 * Returns true if the code had no syntax errors.
	 *
	 * @param const UnicodeString& code the actual code to parse.
	 * @param LintResultsClass& results any error message will be populated here
	 * @return bool true if the code has no syntax errors.
	 */
	bool LintString(const UnicodeString& code, LintResultsClass& results);

	/**
	 * @return the character position where the parser is currently parsing. This can be called
	 * inside an observer callback; in which case the character position is right PAST the
	 * current token.
	 */
	int GetCharacterPosition() const;

	/**
	 * Parses a given PHP expression.  This method will parse the given expression into a list of
	 * of "chained" calls.
	 *
	 * A PHP expression is
	 *  - a variable  ($obj)
	 *  - a function call (myFunc())
	 *  - an object operation ("$obj->prop")
	 *  - a static object operation ("MyClass::Prop")
	 *
	 * Object operations can be chained; like "$obj->prop->anotherFunc()". While indirect variables are allowed
	 * in PHP (ie $this->$prop)  this method will not handle them as it is nearly impossible to resolve them at parse time.
	 *
	 * The most extreme example is this expression: "$obj->prop->anotherFunc()"
	 * This method will parse the expression into
	 * $obj
	 * ->prop
	 * ->anotherFunc()

	 * For example, if sourceCode represented this string:
	 *
	 *   @code
	 *     UnicodeString sourceCode = UNICODE_STRING_SIMPLE("
	 *       class UserClass {
	 *         private $name;
	 *
	 *         function getName() {
	 *           return $this->
	 *     ");
	 *   @endcode
	 *  then the following C++ code can be used to find a variable's type
	 *
	 *   @code
	 *     ParserClass parser;
	 *     UnicodeString expression = UNICODE_STRING_SIMPLE("$this->");
	 *     pelet::SymbolClass exprResult;
	 *     if (parser.ParseExpression(expression, exprResult)) {
	 *     	// if successful, symbol.Lexeme will be set to "$this"
	 *     }
	 *   @endcode
	 *
	 *
	 * @param expression the code string of the expression to resolve. This must be the code for a single expression.
	 *        Examples:
	 *        $anObject
	 *        $this->prop
	 *        $this->work()->another
	 *        $this->
	 *		  work()->another
	 *		  work()
	 *        self::prop
	 *        self::prop::
	 *        self::func()->prop
	 *        parent::prop
	 *        parent::fun()->prop
	 *        aFunction
	 *        An expression can have whitespace like this
	 *        $anObject
	 *			->method1()
	 *			->method2()
	 *			->method3()
	 *
	 * A special case that happens when the given expression ends with the object operator:
	 *        $this->
	 *        MyClass::
	 * In this case, the operator will be added the chain list; this way the client code can determine that
	 * the variable name actually ended.
	 * @param expression the expression's name and "chain" list. The  properties of this object will be reset every call.
	 */
	void ParseExpression(UnicodeString expressionString, pelet::VariableClass& variable);

private:

	/**
	 * Clean up any resources after parsing a file. This is also very important if the
	 * parser opens a string; without closing the string will not be released (if it's a
	 * long string).
	 */
	void Close();

	/**
	 * Used to tokenize code
	 */
	LexicalAnalyzerClass Lexer;

	/**
	 * Notify the ClassObserver when a class has been found. Memory management of this pointer should be
	 * done by the caller.
	 */
	ClassObserverClass* ClassObserver;

	/**
	 * Notify the ClassMemberObserver when a class member has been found. Memory management of this pointer should be
	 * done by the caller.
	 */
	ClassMemberObserverClass* ClassMemberObserver;

	/**
	 * Notify the FunctionObserver when a function has been found. Memory management of this pointer should be
	 * done by the caller.
	 */
	FunctionObserverClass* FunctionObserver;

	/**
	 * Notify the VariableObserver when a variable has been created. Memory management of this pointer should be
	 * done by the caller.
	 */
	VariableObserverClass* VariableObserver;

	/**
	 * Notify the ExpressionObserver when an expressionhas been found. Memory management of this pointer should be
	 * done by the caller.
	 */
	ExpressionObserverClass* ExpressionObserver;

	/**
	 * The PHP version to handle
	 */
	Versions Version;
};

}
#endif // __parserclass__


text:
import test from 'ava';
import React from 'react';
import { mount } from 'enzyme';
import { Component } from '../../public/js/containers/posts';
import { spy } from 'sinon';

test('Should be able to render layout;', t => {

    const props = {
        catalogue: [
            { slug: 'first-post', title: 'First' },
            { slug: 'second-post', title: 'Second' },
            { slug: 'third-post', title: 'Third' }
        ],
        params: {
            pageNumber: 1
        },
        fetchData: spy()
    };

    const wrapper = mount(<Component {...props} />);
    t.is(props.fetchData.callCount, 1);
    t.is(wrapper.find('label').text(), '(3 Posts)');
    wrapper.setProps({ catalogue: [{ slug: 'first-post', title: 'First' }] });
    t.is(wrapper.find('label').text(), '(1 Post)');

});