text:
<?xml version="1.0" encoding="UTF-8"?>
<monster name="Earth Elemental" nameDescription="an earth elemental" race="undead" experience="450" speed="220" manacost="0">
	<health now="650" max="650"/>
	<look type="301" corpse="8933"/>
	<targetchange interval="4000" chance="10"/>
	<flags>
		<flag summonable="0"/>
		<flag attackable="1"/>
		<flag hostile="1"/>
		<flag illusionable="0"/>
		<flag convinceable="0"/>
		<flag pushable="0"/>
		<flag canpushitems="1"/>
		<flag staticattack="80"/>
		<flag lightlevel="0"/>
		<flag lightcolor="0"/>
		<flag targetdistance="1"/>
		<flag runonhealth="80"/>
	</flags>
	<attacks>
		<attack name="melee" interval="2000" skill="45" attack="40"/>
		<attack name="earth" interval="2000" chance="10" range="7" target="1" min="-72" max="-105">
			<attribute key="shootEffect" value="smallearth"/>
			<attribute key="areaEffect" value="greenbubble"/>
		</attack>
		<attack name="physical" interval="2000" chance="10" range="7" radius="2" target="1" min="-0" max="-100">
			<attribute key="shootEffect" value="largerock"/>
			<attribute key="areaEffect" value="poff"/>
		</attack>
		<attack name="poisoncondition" interval="2000" chance="20" length="6" spread="0" min="-200" max="-260">
			<attribute key="areaEffect" value="bigplants"/>
		</attack>
		<attack name="poisoncondition" interval="2000" chance="10" target="0" radius="5" min="-100" max="-140">
			<attribute key="shootEffect" value="poison"/>
			<attribute key="areaEffect" value="poison"/>
		</attack>
		<attack name="speed" interval="2000" chance="10" range="5" target="1" speedchange="-330" duration="5000">
			<attribute key="areaEffect" value="smallplants"/>
		</attack>
	</attacks>
	<defenses armor="25" defense="25">
		<defense name="healing" interval="2000" chance="5" min="60" max="80">
			<attribute key="areaEffect" value="blueshimmer"/>
		</defense>
	</defenses>
	<elements>
		<element deathPercent="50"/>
		<element icePercent="85"/>
		<element physicalPercent="50"/>
		<element holyPercent="50"/>
		<element firePercent="-25"/>
	</elements>
	<immunities>
		<immunity paralyze="1"/>
		<immunity invisible="1"/>
		<immunity earth="1"/>
		<immunity energy="1"/>
	</immunities>
	<loot>
		<item id="2148" countmax="100" chance="43000" /><!-- gold coin -->
		<item id="2148" countmax="30" chance="50000" /><!-- gold coin -->
		<item id="11222" chance="20460" /><!-- lump of earth -->
		<item id="7850" countmax="30" chance="20160" /><!-- earth arrow -->
		<item id="2260" chance="10000" /><!-- blank rune -->
		<item id="7589" chance="1910" /><!-- strong mana potion -->
		<item id="11339" chance="570" /><!-- clay lump -->
		<item id="13757" chance="470" /><!-- coal -->
		<item id="9808" chance="350" /><!-- rusty armor -->
		<item id="1294" countmax="10" chance="10000" /><!-- small stone -->
		<item id="9970" chance="620" /><!-- small topaz -->
	</loot>
</monster>


text:
package org.springframework.aop.aspectj;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.testfixture.beans.CountingTestBean;
import org.springframework.beans.testfixture.beans.IOther;
import org.springframework.beans.testfixture.beans.ITestBean;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.beans.testfixture.beans.subpkg.DeepBean;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;

/**
 * Unit tests for the {@link TypePatternClassFilter} class.
 *
 * @author Rod Johnson
 * @author Rick Evans
 * @author Chris Beams
 * @author Sam Brannen
 */
class TypePatternClassFilterTests {

	@Test
	void nullPattern() {
		assertThatIllegalArgumentException().isThrownBy(() -> new TypePatternClassFilter(null));
	}

	@Test
	void invalidPattern() {
		assertThatIllegalArgumentException().isThrownBy(() -> new TypePatternClassFilter("-"));
	}

	@Test
	void invocationOfMatchesMethodBlowsUpWhenNoTypePatternHasBeenSet() throws Exception {
		assertThatIllegalStateException().isThrownBy(() -> new TypePatternClassFilter().matches(String.class));
	}

	@Test
	void validPatternMatching() {
		TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.beans.testfixture.beans.*");

		assertThat(tpcf.matches(TestBean.class)).as("Must match: in package").isTrue();
		assertThat(tpcf.matches(ITestBean.class)).as("Must match: in package").isTrue();
		assertThat(tpcf.matches(IOther.class)).as("Must match: in package").isTrue();

		assertThat(tpcf.matches(DeepBean.class)).as("Must be excluded: in wrong package").isFalse();
		assertThat(tpcf.matches(BeanFactory.class)).as("Must be excluded: in wrong package").isFalse();
		assertThat(tpcf.matches(DefaultListableBeanFactory.class)).as("Must be excluded: in wrong package").isFalse();
	}

	@Test
	void subclassMatching() {
		TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.beans.testfixture.beans.ITestBean+");

		assertThat(tpcf.matches(TestBean.class)).as("Must match: in package").isTrue();
		assertThat(tpcf.matches(ITestBean.class)).as("Must match: in package").isTrue();
		assertThat(tpcf.matches(CountingTestBean.class)).as("Must match: in package").isTrue();

		assertThat(tpcf.matches(IOther.class)).as("Must be excluded: not subclass").isFalse();
		assertThat(tpcf.matches(DefaultListableBeanFactory.class)).as("Must be excluded: not subclass").isFalse();
	}

	@Test
	void andOrNotReplacement() {
		TypePatternClassFilter tpcf = new TypePatternClassFilter("java.lang.Object or java.lang.String");
		assertThat(tpcf.matches(Number.class)).as("matches Number").isFalse();
		assertThat(tpcf.matches(Object.class)).as("matches Object").isTrue();
		assertThat(tpcf.matches(String.class)).as("matchesString").isTrue();

		tpcf = new TypePatternClassFilter("java.lang.Number+ and java.lang.Float");
		assertThat(tpcf.matches(Float.class)).as("matches Float").isTrue();
		assertThat(tpcf.matches(Double.class)).as("matches Double").isFalse();

		tpcf = new TypePatternClassFilter("java.lang.Number+ and not java.lang.Float");
		assertThat(tpcf.matches(Float.class)).as("matches Float").isFalse();
		assertThat(tpcf.matches(Double.class)).as("matches Double").isTrue();
	}

	@Test
	void testEquals() {
		TypePatternClassFilter filter1 = new TypePatternClassFilter("org.springframework.beans.testfixture.beans.*");
		TypePatternClassFilter filter2 = new TypePatternClassFilter("org.springframework.beans.testfixture.beans.*");
		TypePatternClassFilter filter3 = new TypePatternClassFilter("org.springframework.tests.*");

		assertThat(filter1).isEqualTo(filter2);
		assertThat(filter1).isNotEqualTo(filter3);
	}

	@Test
	void testHashCode() {
		TypePatternClassFilter filter1 = new TypePatternClassFilter("org.springframework.beans.testfixture.beans.*");
		TypePatternClassFilter filter2 = new TypePatternClassFilter("org.springframework.beans.testfixture.beans.*");
		TypePatternClassFilter filter3 = new TypePatternClassFilter("org.springframework.tests.*");

		assertThat(filter1.hashCode()).isEqualTo(filter2.hashCode());
		assertThat(filter1.hashCode()).isNotEqualTo(filter3.hashCode());
	}

	@Test
	void testToString() {
		TypePatternClassFilter filter1 = new TypePatternClassFilter("org.springframework.beans.testfixture.beans.*");
		TypePatternClassFilter filter2 = new TypePatternClassFilter("org.springframework.beans.testfixture.beans.*");

		assertThat(filter1.toString())
			.isEqualTo("org.springframework.aop.aspectj.TypePatternClassFilter: org.springframework.beans.testfixture.beans.*");
		assertThat(filter1.toString()).isEqualTo(filter2.toString());
	}

}

redpajama_set_name: RedPajamaGithub


text:
from django.db import migrations

from corehq.sql_db.operations import RawSQLMigration

migrator = RawSQLMigration(('corehq', 'apps', 'domain', 'migrations', 'sql_templates'))

class Migration(migrations.Migration):

    dependencies = [
        ('domain', '0002_auto_20171020_1428'),
    ]

    operations = [
        migrator.get_migration('update_tables1.sql'),
    ]


text:
<select name="teacherid" id="teacherid" class="form-control">
    <?php
    foreach ($allteacher as $singleTid):
        ?>
        <option value="<?php echo $singleTid->teacher_id; ?>">
            <?php echo $singleTid->teacher_name; ?>
        </option>
        <?php
    endforeach;
    ?>
</select>


text:
<?php

namespace RandomLib\Mixer;

use SecurityLib\Strength;

class McryptRijndael128Test extends \PHPUnit_Framework_TestCase
{
    public static function provideMix()
    {
        $data = array(
            array(array(), ''),
            array(array('', ''), ''),
            array(array('a'), '61'),
            array(array('a', 'b'), '6a'),
            array(array('aa', 'ba'), '688d'),
            array(array('ab', 'bb'), 'f8bc'),
            array(array('aa', 'bb'), 'a0f3'),
            array(array('aa', 'bb', 'cc'), '87c3'),
            array(array('aabbcc', 'bbccdd', 'ccddee'), '7cf2273e46c7'),
        );

        return $data;
    }

    protected function setUp()
    {
        if (!extension_loaded('mcrypt')) {
            $this->markTestSkipped('mcrypt extension is not available');
        }
    }

    public function testConstructWithoutArgument()
    {
        $hash = new McryptRijndael128();
        $this->assertTrue($hash instanceof \RandomLib\Mixer);
    }

    public function testGetStrength()
    {
        $strength = new Strength(Strength::HIGH);
        $actual = McryptRijndael128::getStrength();
        $this->assertEquals($actual, $strength);
    }

    public function testTest()
    {
        $actual = McryptRijndael128::test();
        $this->assertTrue($actual);
    }

    /**
     * @dataProvider provideMix
     */
    public function testMix($parts, $result)
    {
        $mixer = new McryptRijndael128();
        $actual = $mixer->mix($parts);
        $this->assertEquals($result, bin2hex($actual));
    }
}


text:
#include "VideoBrowser.h"
#include "GlTexture.h"
#include "Kernel/OVR_String_Utils.h"
#include "VrCommon.h"
#include "PackageFiles.h"
#include "ImageData.h"
#include "Oculus360Videos.h"
#include "VrLocale.h"
#include "BitmapFont.h"
#include <OVR_TurboJpeg.h>
#include "linux/stat.h"
#include <unistd.h>

namespace OVR
{

VideoBrowser * VideoBrowser::Create(
		App * app,
		OvrVideosMetaData & metaData,
		unsigned thumbWidth,
		float horizontalPadding,
		unsigned thumbHeight,
		float verticalPadding,
		unsigned 	numSwipePanels,
		float SwipeRadius )
{
	return new VideoBrowser( app, metaData,
		thumbWidth + horizontalPadding, thumbHeight + verticalPadding, SwipeRadius, numSwipePanels, thumbWidth, thumbHeight );
}

void VideoBrowser::OnPanelActivated( const OvrMetaDatum * panelData )
{
	Oculus360Videos * videos = ( Oculus360Videos * )AppPtr->GetAppInterface();
	OVR_ASSERT( videos );
	videos->OnVideoActivated( panelData );
}

unsigned char * VideoBrowser::CreateAndCacheThumbnail( const char * soureFile, const char * cacheDestinationFile, int & outW, int & outH )
{
	// TODO
	return NULL;
}

unsigned char * VideoBrowser::LoadThumbnail( const char * filename, int & width, int & height )
{
	LOG( "VideoBrowser::LoadThumbnail loading on %s", filename );
	unsigned char * orig = NULL;

	if ( strstr( filename, "assets/" ) )
	{
		void * buffer = NULL;
		int length = 0;
		ovr_ReadFileFromApplicationPackage( filename, length, buffer );

		if ( buffer )
		{
			orig = TurboJpegLoadFromMemory( reinterpret_cast< const unsigned char * >( buffer ), length, &width, &height );
			free( buffer );
		}
	}
	else if ( strstr( filename, ".pvr" ) )
	{
		orig = LoadPVRBuffer( filename, width, height );
	}
	else
	{
		orig = TurboJpegLoadFromFile( filename, &width, &height );
	}

	if ( orig )
	{
		const int ThumbWidth = GetThumbWidth();
		const int ThumbHeight = GetThumbHeight();

		if ( ThumbWidth == width && ThumbHeight == height )
		{
			LOG( "VideoBrowser::LoadThumbnail skip resize on %s", filename );
			return orig;
		}

		LOG( "VideoBrowser::LoadThumbnail resizing %s to %ix%i", filename, ThumbWidth, ThumbHeight );
		unsigned char * outBuffer = ScaleImageRGBA( ( const unsigned char * )orig, width, height, ThumbWidth, ThumbHeight, IMAGE_FILTER_CUBIC );
		free( orig );

		if ( outBuffer )
		{
			width = ThumbWidth;
			height = ThumbHeight;

			return outBuffer;
		}
	}
	else
	{
		LOG( "Error: VideoBrowser::LoadThumbnail failed to load %s", filename );
	}
	return NULL;
}

String VideoBrowser::ThumbName( const String & s )
{
	String	ts( s );
	ts = OVR::StringUtils::SetFileExtensionString( ts, ".pvr" );
	return ts;
}

String VideoBrowser::AlternateThumbName( const String & s )
{
	String	ts( s );
	ts = OVR::StringUtils::SetFileExtensionString( ts, ".thm" );
	return ts;
}

void VideoBrowser::OnMediaNotFound( App * app, String & title, String & imageFile, String & message )
{
	VrLocale::GetString( app->GetVrJni(), app->GetJavaObject(), "@string/app_name", "@string/app_name", title );
	imageFile = "assets/sdcard.png";
	VrLocale::GetString( app->GetVrJni(), app->GetJavaObject(), "@string/media_not_found", "@string/media_not_found", message );
	BitmapFont & font = app->GetDefaultFont();
	OVR::Array< OVR::String > wholeStrs;
	wholeStrs.PushBack( "Gear VR" );
	font.WordWrapText( message, 1.4f, wholeStrs );
}

String VideoBrowser::GetCategoryTitle( char const * key, char const * defaultStr ) const
{
	String outStr;
	VrLocale::GetString( AppPtr->GetVrJni(), AppPtr->GetJavaObject(), key, defaultStr, outStr );
	return outStr;
}

String VideoBrowser::GetPanelTitle( const OvrMetaDatum & panelData ) const
{
	const OvrVideosMetaDatum * const videosDatum = static_cast< const OvrVideosMetaDatum * const >( &panelData );
	if ( videosDatum != NULL )
	{
		return videosDatum->Title;
	}
	return String();
}

}


text:
package dsg.buffering.graph;

import java.util.function.Predicate;

import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.Triple;
import org.apache.jena.rdf.model.impl.Util;
import org.apache.jena.util.iterator.ExtendedIterator;

public class G3 {
    // Migrate to G. and NodeUtils?
    //And fix GraphPlain

    /** Contains by "same term", regardless of whether the graph implements "same value" or "same term". */
    public static boolean containsByEquals(Graph graph, Triple triple) {
        return containsByEquals(graph, triple.getSubject(), triple.getPredicate(), triple.getObject());
    }

    /** Contains by "same term", regardless of whether the graph implements "same value" or "same term". */
    public static boolean containsByEquals(Graph graph, Node s, Node p, Node o) {
        // Do direct for efficiency.
        if ( ! graph.contains(s,p,o) )
            return false;
        // May have matched by value.  Do a term test find to restrict to RDF terms.
        ExtendedIterator<Triple> iter = graph.find(s, p, o);
        // Unless generalized RDF, only need to test object.
        Predicate<Triple> predicate = (dataTriple) -> sameTermMatch(s, p, o, dataTriple);
        iter = iter.filterKeep(predicate);
        try {
            return iter.hasNext();
        } finally { iter.close(); }

//    // For reference - just object
//    if ( !o.isConcrete() || o.isLiteral() ) {
//        Predicate<Triple> predicate = (t) -> sameTermMatch(o, t.getObject()) ;
//        iter = iter.filterKeep(predicate) ;
//    }

    }

    /**
     * Match a ground triple (even ANY and variables are considered ground terms in the
     * data triple) with S/P/O which can be wildcards (ANY or null).
     */
    public static boolean sameTermMatch(Node matchSubj, Node matchPred, Node matchObj, Triple dataTriple) {
        return
            sameTermMatch(matchSubj, dataTriple.getSubject()) &&
            sameTermMatch(matchPred, dataTriple.getPredicate()) &&
            sameTermMatch(matchObj,  dataTriple.getObject());
    }

    /**
     * Match a ground RDF Term (ANY and variables are considered ground terms in the
     * data term) with a node which can be a wildcard (ANY or null).
     * Language tags compare case-insensitively.
     */
    public static boolean sameTermMatch(Node match, Node data) {
        if ( false ) {
            if ( match==null || Node.ANY.equals(match) )
                return true;
            // If lang tags are compared case-insensitively.
            return match.equals(data);
        }

        // Allow for case-insensitive language tag comparison.
        // Two literals.
        if ( ! Util.isLangString(data) || ! Util.isLangString(match) )
            // Not both strings with lang tags.
            return (match==null) || (match == Node.ANY) || match.equals(data) ;

        // Language tags compare case insensitively.
        String lex1 = data.getLiteralLexicalForm();
        String lex2 = data.getLiteralLexicalForm();
        String lang1 = data.getLiteralLanguage();
        String lang2 = data.getLiteralLanguage();
        return lex1.equals(lex2) && lang1.equalsIgnoreCase(lang2);
    }
}


text:
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
if RUBY_VERSION == "1.9.2"
  require 'ruby-debug'
end

Rails.backtrace_cleaner.remove_silencers!

# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

RSpec.configure do |config|
  config.use_transactional_fixtures = true
  config.mock_with :rspec
  config.infer_base_class_for_anonymous_controllers = false
  config.backtrace_clean_patterns = []
end

def should_raise(exception)
  lambda{ yield }.should raise_error(exception)
  flash[:error].should_not be_empty
end

module LoginSpecHelper
  def do_login
    @user = Factory(:user)
    sign_in @user
  end

  def do_login_as_admin
    @user = Factory(:user)
    @user.update_attribute(:is_admin, true)
    sign_in @user
  end

  def log_off
    sign_out @user
  end
end
include LoginSpecHelper
include Warden::Test::Helpers


text:
import {Component, ViewChild, OnInit} from '@angular/core';
import {MonthYearPicker} from "../../../shared/components/month_year_picker/month_year_picker.component";
import {CrudService} from "../../../services/crud.service";
import {Router} from "@angular/router";
import { IMultiSelectTexts, IMultiSelectSettings, IMultiSelectOption } from 'angular-2-dropdown-multiselect/src/multiselect-dropdown';
declare let jsPDF : any;

@Component({
  selector: 'isem-tipstuba',
  // encapsulation: ViewEncapsulation.None,
  templateUrl: 'uk_pot_ene_obj.component.html',
  styleUrls: ['../../styles/table.component.scss']
})

export class IzvUkPotEneObj implements OnInit {

  @ViewChild(MonthYearPicker)
  private m: MonthYearPicker;

  podaci:Array<any>;
  eneTipData: IMultiSelectOption[];
  objId: any[];
  period: String;

  mySettingsTipEne: IMultiSelectSettings = {
    pullRight: true,
    enableSearch: true,
    checkedStyle: 'checkboxes',
    buttonClasses: 'btn btn-default',
    selectionLimit: 0,
    closeOnSelect: false,
    showCheckAll: true,
    showUncheckAll: true,
    dynamicTitleMaxItems: 10,
    maxHeight: '300px',
  };

  myTextsTipEne: IMultiSelectTexts = {
    checkAll: 'Uključi sve',
    uncheckAll: 'Isključi sve',
    checked: 'odabrano',
    checkedPlural: 'odabrano',
    searchPlaceholder: 'Pretraga...',
    defaultTitle: 'Izaberite energente',
  };

  private isPodaciLoaded: boolean = false;
  private isEneTipLoaded: boolean = false;

  private eneTipIzbor: number[] = [];

  constructor(private crudService: CrudService, private router: Router) {
  }

  ngOnInit() {
    this.getEnergentTip();
  }

  upisiObjekte(objId: any[]) {
    this.objId = objId;
  }

  formirajIzvestaj(){
    this.crudService.getData("izvestaj/uk_pot_ene_obj?obj_id="+this.objId+"&ene_tip_id="+this.eneTipIzbor+"&datum_od="+'15'+'.'+this.m.mesOd+'.'+this.m.godOd+"&datum_do="+'15'+'.'+this.m.mesDo+'.'+this.m.godDo).subscribe(
      data => {this.podaci = data;
        this.period = this.m.mesOd + "." + this.m.godOd + "--" + this.m.mesDo + "." + this.m.godDo;
      console.log(data); this.isPodaciLoaded = true},
      error => {console.log(error);}
    );
  }

  getEnergentTip() {
    this.crudService.getData("energent_tip/lov").subscribe(
      data => {
        this.eneTipData = data;
        console.log(data);

        this.isEneTipLoaded = true;
      },
      error => {console.log(error); this.router.navigate(['/login']);}
    );
  }

  onChangeEneTip() {
    console.log(this.eneTipIzbor);
  }

  convert(){

    var doc = new jsPDF('l', 'mm', [297, 210]);
    var col = ["Grupa", "Energent", "Objekat", "Kolicina", "Kolicina [kWh]", "Emisija CO2", "Iznos [din]" ];
    var rows = [];
    var styles = {halign: 'right'};

    console.log(this.podaci);
    for(var key in this.podaci){
      // ovo sam uradio da mi ne prikazuje null-ove u tabeli
      if(this.podaci[key].grupa== null){
        this.podaci[key].grupa = "";
      }
      if(this.podaci[key].energent== null){
        this.podaci[key].energent = "";
      }
      if(this.podaci[key].objekat== null){
        this.podaci[key].objekat = "";
      }if(this.podaci[key].kolicina== null){
        this.podaci[key].kolicina = "";
      }
      if(this.podaci[key].kolicinaKwh== null){
        this.podaci[key].kolicinaKwh = "";
      }
      if(this.podaci[key].emisijaCo2== null){
        this.podaci[key].emisijaCo2 = "";
      }
      if(this.podaci[key].iznos== null){
        this.podaci[key].iznos = "";
      }
      var temp = [this.podaci[key].grupa, this.podaci[key].energent, this.podaci[key].objekat, this.podaci[key].kolicina, this.podaci[key].kolicinaKwh, this.podaci[key].emisijaCo2, this.podaci[key].iznos];
      rows.push(temp);
    }
    doc.text(40, 10, "Ukupna potrošnja energenata po objektima" + "\nza period: "+ this.period);
    doc.autoTable(col, rows, {
      startY: 25,
      // margin: {horizontal: 7},
      // bodyStyles: {valign: 'top'},
      // styles: {overflow: 'linebreak', columnWidth: 'wrap'},
      // columnStyles: {text: {columnWidth: 'auto'}}
      //styles: {overflow: 'linebreak', columnWidth: 'wrap'}
      //  styles: {cellPadding: 0.5, fontSize: 4, halign: 'left'}
    });

    doc.save('Uk_pot_en_obj.pdf');
  }

  //funkcija za formiranje excela iz izvestaja 7
  htmlTableToExcel(table) {
    var uri = 'data:application/vnd.ms-excel;base64,'
      , template = '
{table}
'
      , base64 = function(s) {return btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g, function(match, p1) {
      return String.fromCharCode(parseInt("0x" + p1));
    })); }
      , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); };

    if (!table.nodeType) table = document.getElementById(table);
    var ctx = { worksheet: "aps-mes-pot" || 'Worksheet', table: table.innerHTML };
//
    var anchor = document.createElement('a');
    anchor.href = uri + base64(format(template, ctx));
    anchor.download = "ukupna_potrosnja_energenata_po_objektima.xls";
    anchor.click();

  }
}


text:
var classtesting_1_1internal_1_1_default_per_thread_test_part_result_reporter =
[
    [ "DefaultPerThreadTestPartResultReporter", "classtesting_1_1internal_1_1_default_per_thread_test_part_result_reporter.html#a968a846e5a90d2ffea8b2ce2746099bd", null ],
    [ "ReportTestPartResult", "classtesting_1_1internal_1_1_default_per_thread_test_part_result_reporter.html#ac6dc08eadc4e5a2a64a91d0b6c6b3aad", null ]
];


text:
Copyright (c) 2013 crosslife <hustgeziyang@gmail.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.
]]

GIconNormalType = 1
GIconCryType = 2
GIconMatchType = 3
GIconSelectType = 4

--¼ÓÔØÓÎϷͼ±ê×ÊÔ´
function loadGameIcon()
	CCSpriteFrameCache:getInstance():addSpriteFramesWithFile("imgs/GameIcon.plist")
end

--»ñȡij¸öÆå×Ó
function getGameIconSprite(type, index)
	local iconFrame = CCSpriteFrameCache:getInstance():getSpriteFrameByName("icon"..type..index..".png")
	if iconFrame == nil then
		print("icon"..type..index..".png")
		print("iconFrame nil")
		return
	end
	local iconSprite = CCSprite:createWithSpriteFrame(iconFrame)
	return iconSprite
end

--´´½¨Ëæ»ú±ä»»µÄÆå×Ó
function createBlinkIconSprite()
	local animFrames = CCArray:create()

	for i=1, GGameIconCount do
		local iconFrame = CCSpriteFrameCache:getInstance():getSpriteFrameByName("icon4"..i..".png")
		animFrames:addObject(iconFrame)
	end

	local iconSprite = getGameIconSprite(4, 1)

    local animation = CCAnimation:createWithSpriteFrames(animFrames, 0.1)
	local animate = CCAnimate:create(animation);

    iconSprite:runAction(CCRepeatForever:create(animate))

	return iconSprite
end


text:
const inspector = require('schema-inspector');

/**
  @name OnError
  @function
  @param {Object[]} errors A list of error objects
*/

/**
 * queryValidator - Creates query validator middleware
 *
 * @param  {object}     rules   The validation rules
 * @param  {OnError}   onError  The function to call if a validation error is found
 * @param  {boolean}    strict  Whether to throw if extra fields are found
 * @return {function*}          The validation middleware
 */
module.exports = function queryValidator(rules, onError = throwValidationError, { strict = false, field = 'parameters' } = {}) {
  let validationRules = {
    type: 'object',
    strict: strict || false,
    properties: rules
  };

  /**
   * anonymous function - description
   *
   * @param  {type} next description
   * @return {type}      description
   */
  return async (ctx, next) => {
    let validation = inspector.validate(validationRules, ctx[field]);

    if (!validation.valid) {
      return onError(validation.error, ctx);
    }

    return next();
  };
};

/**
 * throwValidationError - Throws a generic validation error
 *
 * @param  {object[]}  errors A list of validation errors to throw
 * @return {undefined}
 */
function throwValidationError(errors, ctx) {
  ctx.throw(400, 'Invalid query parameters', errors);
}


text:
<?php

namespace Cake\Test\TestCase\Cache;

use Cake\Cache\Cache;
use Cake\Cache\CacheRegistry;
use Cake\Cache\Engine\FileEngine;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\TestSuite\TestCase;

/**
 * CacheTest class
 *
 */
class CacheTest extends TestCase
{

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        Cache::enable();
    }

    /**
     * tearDown method
     *
     * @return void
     */
    public function tearDown()
    {
        parent::tearDown();
        Cache::drop('tests');
        Cache::drop('test_trigger');
    }

    /**
     * Configure cache settings for test
     *
     * @return void
     */
    protected function _configCache()
    {
        Cache::config('tests', [
            'engine' => 'File',
            'path' => TMP,
            'prefix' => 'test_'
        ]);
    }

    /**
     * Check that no fatal errors are issued doing normal things when Cache.disable is true.
     *
     * @return void
     */
    public function testNonFatalErrorsWithCacheDisable()
    {
        Cache::disable();
        $this->_configCache();

        $this->assertNull(Cache::write('no_save', 'Noooo!', 'tests'));
        $this->assertFalse(Cache::read('no_save', 'tests'));
        $this->assertNull(Cache::delete('no_save', 'tests'));
    }

    /**
     * Check that a null instance is returned from engine() when caching is disabled.
     *
     * @return void
     */
    public function testNullEngineWhenCacheDisable()
    {
        $this->_configCache();
        Cache::disable();

        $result = Cache::engine('tests');
        $this->assertInstanceOf('Cake\Cache\Engine\NullEngine', $result);
    }

    /**
     * Test configuring an invalid class fails
     *
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Cache engines must use Cake\Cache\CacheEngine
     * @return void
     */
    public function testConfigInvalidClassType()
    {
        Cache::config('tests', [
            'className' => '\StdClass'
        ]);
        Cache::engine('tests');
    }

    /**
     * Test engine init failing causes an error
     *
     * @expectedException \RuntimeException
     * @expectedExceptionMessage not properly configured
     * @return void
     */
    public function testConfigFailedInit()
    {
        $mock = $this->getMockForAbstractClass('Cake\Cache\CacheEngine', [], '', true, true, true, ['init']);
        $mock->method('init')->will($this->returnValue(false));
        Cache::config('tests', [
            'engine' => $mock
        ]);
        Cache::engine('tests');
    }

    /**
     * test configuring CacheEngines in App/libs
     *
     * @return void
     */
    public function testConfigWithLibAndPluginEngines()
    {
        Configure::write('App.namespace', 'TestApp');
        Plugin::load('TestPlugin');

        $config = ['engine' => 'TestAppCache', 'path' => TMP, 'prefix' => 'cake_test_'];
        Cache::config('libEngine', $config);
        $engine = Cache::engine('libEngine');
        $this->assertInstanceOf('TestApp\Cache\Engine\TestAppCacheEngine', $engine);

        $config = ['engine' => 'TestPlugin.TestPluginCache', 'path' => TMP, 'prefix' => 'cake_test_'];
        $result = Cache::config('pluginLibEngine', $config);
        $engine = Cache::engine('pluginLibEngine');
        $this->assertInstanceOf('TestPlugin\Cache\Engine\TestPluginCacheEngine', $engine);

        Cache::drop('libEngine');
        Cache::drop('pluginLibEngine');

        Plugin::unload();
    }

    /**
     * Test write from a config that is undefined.
     *
     * @expectedException \InvalidArgumentException
     * @return void
     */
    public function testWriteNonExistingConfig()
    {
        $this->assertFalse(Cache::write('key', 'value', 'totally fake'));
    }

    /**
     * Test write from a config that is undefined.
     *
     * @expectedException \InvalidArgumentException
     * @return void
     */
    public function testIncrementNonExistingConfig()
    {
        $this->assertFalse(Cache::increment('key', 1, 'totally fake'));
    }

    /**
     * Test write from a config that is undefined.
     *
     * @expectedException \InvalidArgumentException
     * @return void
     */
    public function testDecrementNonExistingConfig()
    {
        $this->assertFalse(Cache::decrement('key', 1, 'totally fake'));
    }

    /**
     * Data provider for valid config data sets.
     *
     * @return array
     */
    public static function configProvider()
    {
        return [
            'Array of data using engine key.' => [[
                'engine' => 'File',
                'path' => TMP . 'tests',
                'prefix' => 'cake_test_'
            ]],
            'Array of data using classname key.' => [[
                'className' => 'File',
                'path' => TMP . 'tests',
                'prefix' => 'cake_test_'
            ]],
            'Direct instance' => [new FileEngine()],
        ];
    }

    /**
     * testConfig method
     *
     * @dataProvider configProvider
     * @return void
     */
    public function testConfigVariants($config)
    {
        $this->assertNotContains('test', Cache::configured(), 'test config should not exist.');
        Cache::config('tests', $config);

        $engine = Cache::engine('tests');
        $this->assertInstanceOf('Cake\Cache\Engine\FileEngine', $engine);
        $this->assertContains('tests', Cache::configured());
    }

    /**
     * testConfigInvalidEngine method
     *
     * @expectedException \BadMethodCallException
     * @return void
     */
    public function testConfigInvalidEngine()
    {
        $config = ['engine' => 'Imaginary'];
        Cache::config('test', $config);
        Cache::engine('test');
    }

    /**
     * test that trying to configure classes that don't extend CacheEngine fail.
     *
     * @expectedException \BadMethodCallException
     * @return void
     */
    public function testConfigInvalidObject()
    {
        $this->getMockBuilder(\StdClass::class)
            ->setMockClassName('RubbishEngine')
            ->getMock();
        Cache::config('test', [
            'engine' => '\RubbishEngine'
        ]);
        Cache::engine('tests');
    }

    /**
     * Ensure you cannot reconfigure a cache adapter.
     *
     * @expectedException \BadMethodCallException
     * @return void
     */
    public function testConfigErrorOnReconfigure()
    {
        Cache::config('tests', ['engine' => 'File', 'path' => TMP]);
        Cache::config('tests', ['engine' => 'Apc']);
    }

    /**
     * Test reading configuration.
     *
     * @return void
     */
    public function testConfigRead()
    {
        $config = [
            'engine' => 'File',
            'path' => TMP,
            'prefix' => 'cake_'
        ];
        Cache::config('tests', $config);
        $expected = $config;
        $expected['className'] = $config['engine'];
        unset($expected['engine']);
        $this->assertEquals($expected, Cache::config('tests'));
    }

    /**
     * test config() with dotted name
     *
     * @return void
     */
    public function testConfigDottedAlias()
    {
        Cache::config('cache.dotted', [
            'className' => 'File',
            'path' => TMP,
            'prefix' => 'cache_value_'
        ]);

        $engine = Cache::engine('cache.dotted');
        $this->assertContains('cache.dotted', Cache::configured());
        $this->assertNotContains('dotted', Cache::configured());
        $this->assertInstanceOf('Cake\Cache\Engine\FileEngine', $engine);
        Cache::drop('cache.dotted');
    }

    /**
     * testGroupConfigs method
     */
    public function testGroupConfigs()
    {
        Cache::drop('test');
        Cache::config('latest', [
            'duration' => 300,
            'engine' => 'File',
            'groups' => ['posts', 'comments'],
        ]);

        $expected = [
            'posts' => ['latest'],
            'comments' => ['latest'],
        ];
        $result = Cache::groupConfigs();
        $this->assertEquals($expected, $result);

        $result = Cache::groupConfigs('posts');
        $this->assertEquals(['posts' => ['latest']], $result);

        Cache::config('page', [
            'duration' => 86400,
            'engine' => 'File',
            'groups' => ['posts', 'archive'],
        ]);

        $result = Cache::groupConfigs();
        $expected = [
            'posts' => ['latest', 'page'],
            'comments' => ['latest'],
            'archive' => ['page']
        ];
        $this->assertEquals($expected, $result);

        $result = Cache::groupConfigs('archive');
        $this->assertEquals(['archive' => ['page']], $result);

        Cache::config('archive', [
            'duration' => 86400 * 30,
            'engine' => 'File',
            'groups' => ['posts', 'archive', 'comments'],
        ]);

        $result = Cache::groupConfigs('archive');
        $this->assertEquals(['archive' => ['archive', 'page']], $result);
    }

    /**
     * testGroupConfigsWithCacheInstance method
     */
    public function testGroupConfigsWithCacheInstance()
    {
        Cache::drop('test');
        $cache = new FileEngine();
        $cache->init([
            'duration' => 300,
            'engine' => 'File',
            'groups' => ['users', 'comments'],
        ]);
        Cache::config('cached', $cache);

        $result = Cache::groupConfigs('users');
        $this->assertEquals(['users' => ['cached']], $result);
    }

    /**
     * testGroupConfigsThrowsException method
     * @expectedException \InvalidArgumentException
     */
    public function testGroupConfigsThrowsException()
    {
        Cache::groupConfigs('bogus');
    }

    /**
     * test that configured returns an array of the currently configured cache
     * config
     *
     * @return void
     */
    public function testConfigured()
    {
        Cache::drop('default');
        $result = Cache::configured();
        $this->assertContains('_cake_core_', $result);
        $this->assertNotContains('default', $result, 'Unconnected engines should not display.');
    }

    /**
     * test that drop removes cache configs, and that further attempts to use that config
     * do not work.
     *
     * @return void
     */
    public function testDrop()
    {
        Configure::write('App.namespace', 'TestApp');

        $result = Cache::drop('some_config_that_does_not_exist');
        $this->assertFalse($result, 'Drop should not succeed when config is missing.');

        Cache::config('unconfigTest', [
            'engine' => 'TestAppCache'
        ]);
        $this->assertInstanceOf(
            'TestApp\Cache\Engine\TestAppCacheEngine',
            Cache::engine('unconfigTest')
        );
        $this->assertTrue(Cache::drop('unconfigTest'));
    }

    /**
     * testWriteEmptyValues method
     *
     * @return void
     */
    public function testWriteEmptyValues()
    {
        $this->_configCache();
        Cache::write('App.falseTest', false, 'tests');
        $this->assertSame(Cache::read('App.falseTest', 'tests'), false);

        Cache::write('App.trueTest', true, 'tests');
        $this->assertSame(Cache::read('App.trueTest', 'tests'), true);

        Cache::write('App.nullTest', null, 'tests');
        $this->assertSame(Cache::read('App.nullTest', 'tests'), null);

        Cache::write('App.zeroTest', 0, 'tests');
        $this->assertSame(Cache::read('App.zeroTest', 'tests'), 0);

        Cache::write('App.zeroTest2', '0', 'tests');
        $this->assertSame(Cache::read('App.zeroTest2', 'tests'), '0');
    }

    /**
     * testWriteEmptyValues method
     *
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage An empty value is not valid as a cache key
     * @return void
     */
    public function testWriteEmptyKey()
    {
        $this->_configCache();
        Cache::write(null, 'not null', 'tests');
    }

    /**
     * testReadWriteMany method
     *
     * @return void
     */
    public function testReadWriteMany()
    {
        $this->_configCache();
        $data = [
            'App.falseTest' => false,
            'App.trueTest' => true,
            'App.nullTest' => null,
            'App.zeroTest' => 0,
            'App.zeroTest2' => '0'
        ];
        Cache::writeMany($data, 'tests');

        $read = Cache::readMany(array_keys($data), 'tests');

        $this->assertSame($read['App.falseTest'], false);
        $this->assertSame($read['App.trueTest'], true);
        $this->assertSame($read['App.nullTest'], null);
        $this->assertSame($read['App.zeroTest'], 0);
        $this->assertSame($read['App.zeroTest2'], '0');
    }

    /**
     * testDeleteMany method
     *
     * @return void
     */
    public function testDeleteMany()
    {
        $this->_configCache();
        $data = [
            'App.falseTest' => false,
            'App.trueTest' => true,
            'App.nullTest' => null,
            'App.zeroTest' => 0,
            'App.zeroTest2' => '0'
        ];
        Cache::writeMany(array_merge($data, ['App.keepTest' => 'keepMe']), 'tests');

        Cache::deleteMany(array_keys($data), 'tests');
        $read = Cache::readMany(array_merge(array_keys($data), ['App.keepTest']), 'tests');

        $this->assertSame($read['App.falseTest'], false);
        $this->assertSame($read['App.trueTest'], false);
        $this->assertSame($read['App.nullTest'], false);
        $this->assertSame($read['App.zeroTest'], false);
        $this->assertSame($read['App.zeroTest2'], false);
        $this->assertSame($read['App.keepTest'], 'keepMe');
    }

    /**
     * Test that failed writes cause errors to be triggered.
     *
     * @expectedException \PHPUnit_Framework_Error
     * @return void
     */
    public function testWriteTriggerError()
    {
        Configure::write('App.namespace', 'TestApp');
        Cache::config('test_trigger', [
            'engine' => 'TestAppCache',
            'prefix' => ''
        ]);

        Cache::write('fail', 'value', 'test_trigger');
    }

    /**
     * testCacheDisable method
     *
     * Check that the "Cache.disable" configuration and a change to it
     * (even after a cache config has been setup) is taken into account.
     *
     * @return void
     */
    public function testCacheDisable()
    {
        Cache::enable();
        Cache::config('test_cache_disable_1', [
            'engine' => 'File',
            'path' => TMP . 'tests'
        ]);

        $this->assertTrue(Cache::write('key_1', 'hello', 'test_cache_disable_1'));
        $this->assertSame(Cache::read('key_1', 'test_cache_disable_1'), 'hello');

        Cache::disable();

        $this->assertNull(Cache::write('key_2', 'hello', 'test_cache_disable_1'));
        $this->assertFalse(Cache::read('key_2', 'test_cache_disable_1'));

        Cache::enable();

        $this->assertTrue(Cache::write('key_3', 'hello', 'test_cache_disable_1'));
        $this->assertSame('hello', Cache::read('key_3', 'test_cache_disable_1'));
        Cache::clear(false, 'test_cache_disable_1');

        Cache::disable();
        Cache::config('test_cache_disable_2', [
            'engine' => 'File',
            'path' => TMP . 'tests'
        ]);

        $this->assertNull(Cache::write('key_4', 'hello', 'test_cache_disable_2'));
        $this->assertFalse(Cache::read('key_4', 'test_cache_disable_2'));

        Cache::enable();

        $this->assertTrue(Cache::write('key_5', 'hello', 'test_cache_disable_2'));
        $this->assertSame(Cache::read('key_5', 'test_cache_disable_2'), 'hello');

        Cache::disable();
        $this->assertNull(Cache::write('key_6', 'hello', 'test_cache_disable_2'));
        $this->assertFalse(Cache::read('key_6', 'test_cache_disable_2'));

        Cache::enable();
        Cache::clear(false, 'test_cache_disable_2');
    }

    /**
     * test clearAll() method
     *
     * @return void
     */
    public function testClearAll()
    {
        Cache::config('configTest', [
            'engine' => 'File',
            'path' => TMP . 'tests'
        ]);
        Cache::config('anotherConfigTest', [
            'engine' => 'File',
            'path' => TMP . 'tests'
        ]);

        Cache::write('key_1', 'hello', 'configTest');
        Cache::write('key_2', 'hello again', 'anotherConfigTest');

        $this->assertSame(Cache::read('key_1', 'configTest'), 'hello');
        $this->assertSame(Cache::read('key_2', 'anotherConfigTest'), 'hello again');

        $result = Cache::clearAll();
        $this->assertTrue($result['configTest']);
        $this->assertTrue($result['anotherConfigTest']);
        $this->assertFalse(Cache::read('key_1', 'configTest'));
        $this->assertFalse(Cache::read('key_2', 'anotherConfigTest'));
        Cache::drop('configTest');
        Cache::drop('anotherConfigTest');
    }

    /**
     * Test toggling enabled state of cache.
     *
     * @return void
     */
    public function testEnableDisableEnabled()
    {
        $this->assertNull(Cache::enable());
        $this->assertTrue(Cache::enabled(), 'Should be on');
        $this->assertNull(Cache::disable());
        $this->assertFalse(Cache::enabled(), 'Should be off');
    }

    /**
     * test remember method.
     *
     * @return void
     */
    public function testRemember()
    {
        $this->_configCache();
        $counter = 0;
        $cacher = function () use ($counter) {
            return 'This is some data ' . $counter;
        };

        $expected = 'This is some data 0';
        $result = Cache::remember('test_key', $cacher, 'tests');
        $this->assertEquals($expected, $result);

        $counter = 1;
        $result = Cache::remember('test_key', $cacher, 'tests');
        $this->assertEquals($expected, $result);
    }

    /**
     * Test add method.
     *
     * @return void
     */
    public function testAdd()
    {
        $this->_configCache();
        Cache::delete('test_add_key', 'tests');

        $result = Cache::add('test_add_key', 'test data', 'tests');
        $this->assertTrue($result);

        $expected = 'test data';
        $result = Cache::read('test_add_key', 'tests');
        $this->assertEquals($expected, $result);

        $result = Cache::add('test_add_key', 'test data 2', 'tests');
        $this->assertFalse($result);
    }

    /**
     * test registry method
     *
     * @return void
     */
    public function testRegistry()
    {
        $this->assertInstanceOf('Cake\Cache\CacheRegistry', Cache::registry());
    }

    /**
     * test registry method setting
     *
     * @return void
     */
    public function testRegistrySet()
    {
        $registry = new CacheRegistry();
        Cache::registry($registry);

        $this->assertSame($registry, Cache::registry());
    }
}


text:
<?php

namespace GS\ProyectosBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Tiporecurso
 *
 * @ORM\Table(name="tiporecurso")
 * @ORM\Entity
 */
class Tiporecurso
{
    /**
     * @var integer
     *
     * @ORM\Column(name="idtipoRecurso", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idtiporecurso;

    /**
     * @var string
     *
     * @ORM\Column(name="nombre", type="string", length=45, nullable=false)
     */
    private $nombre;

    /**
     * Get idtiporecurso
     *
     * @return integer
     */
    public function getIdtiporecurso()
    {
        return $this->idtiporecurso;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return Tiporecurso
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }
}


text:
package jp.troter.servlet.httpsession.state;

import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultSessionState implements SessionState {

    Map<String, Object> attributes;

    protected final long creationTime = new Date().getTime();

    protected long lastAccessedTime;

    protected boolean isNew;

    protected int maxInactiveInterval;

    public DefaultSessionState(int maxInactiveInterval) {
        this(Collections.<String, Object>emptyMap(), new Date().getTime(), true, maxInactiveInterval);
    }

    public DefaultSessionState(Map<String, Object> attributes, long lastAccessedTime, boolean isNew, int maxInactiveInterval) {
        this.attributes = new ConcurrentHashMap<String, Object>(attributes);
        this.lastAccessedTime = lastAccessedTime;
        this.isNew = isNew;
        this.maxInactiveInterval = maxInactiveInterval;
    }

    @Override
    public long getCreationTime() {
        return creationTime;
    }

    @Override
    public long getLastAccessedTime() {
        return lastAccessedTime;
    }

    @Override
    public Enumeration<?> getAttributeNames() {
        return Collections.enumeration(attributes.keySet());
    }

    @Override
    public void setAttribute(String name, Object value) {
        attributes.put(name, value);
    }

    @Override
    public void removeAttribute(String name) {
        attributes.remove(name);
    }

    @Override
    public Object getAttribute(String name) {
        return attributes.get(name);
    }

    @Override
    public boolean isNew() {
        return isNew;
    }

    @Override
    public int getMaxInactiveInterval() {
        return maxInactiveInterval;
    }

    @Override
    public void setMaxInactiveInterval(int interval) {
        maxInactiveInterval = interval;
    }
}


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

using SampSharp.Entities.SAMP.Commands;
using static SampSharp.Entities.SAMP.SampEntities;

namespace SampSharp.Entities.SAMP;

/// Provides methods for enabling SA:MP systems in an <see cref="IEcsBuilder" /> instance.
public static class SampEcsBuilderExtensions
{
    /// Enables player commands.
    /// <param name="builder">The builder.</param>
    /// <returns>The builder.</returns>
    public static IEcsBuilder EnablePlayerCommands(this IEcsBuilder builder)
    {
        return builder.UseMiddleware<PlayerCommandProcessingMiddleware>("OnPlayerCommandText");
    }

    /// Enables RCON commands.
    /// <param name="builder">The builder.</param>
    /// <returns>The builder.</returns>
    public static IEcsBuilder EnableRconCommands(this IEcsBuilder builder)
    {
        return builder.UseMiddleware<RconCommandProcessingMiddleware>("OnRconCommand");
    }

    /// Enables all actor, player related SA:MP events.
    /// <param name="builder">The builder.</param>
    /// <returns>The builder.</returns>
    public static IEcsBuilder EnableSampEvents(this IEcsBuilder builder)
    {
        return builder.EnableActorEvents()
            .EnablePlayerEvents()
            .EnableObjectEvents()
            .EnableRconEvents()
            .EnableVehicleEvents();
    }

    /// Enables all actor related SA:MP events.
    /// <param name="builder">The builder.</param>
    /// <returns>The builder.</returns>
    public static IEcsBuilder EnableActorEvents(this IEcsBuilder builder)
    {
        builder.EnableEvent<int, int>("OnActorStreamIn");
        builder.EnableEvent<int, int>("OnActorStreamOut");

        builder.UseMiddleware<EntityMiddleware>("OnActorStreamIn", 0, ActorType, true);
        builder.UseMiddleware<EntityMiddleware>("OnActorStreamIn", 1, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnActorStreamOut", 0, ActorType, true);
        builder.UseMiddleware<EntityMiddleware>("OnActorStreamOut", 1, PlayerType, true);

        return builder;
    }

    /// Enables all player related SA:MP events.
    /// <param name="builder">The builder.</param>
    /// <returns>The builder.</returns>
    public static IEcsBuilder EnablePlayerEvents(this IEcsBuilder builder)
    {
        builder.EnableEvent<int>("OnPlayerConnect");
        builder.EnableEvent<int, int>("OnPlayerDisconnect");
        builder.EnableEvent<int>("OnPlayerSpawn");
        builder.EnableEvent<int, int, int>("OnPlayerDeath");
        builder.EnableEvent<int, string>("OnPlayerText");
        builder.EnableEvent<int, string>("OnPlayerCommandText");
        builder.EnableEvent<int, int>("OnPlayerRequestClass");
        builder.EnableEvent<int, int, bool>("OnPlayerEnterVehicle");
        builder.EnableEvent<int, int>("OnPlayerExitVehicle");
        builder.EnableEvent<int, int, int>("OnPlayerStateChange");
        builder.EnableEvent<int>("OnPlayerEnterCheckpoint");
        builder.EnableEvent<int>("OnPlayerLeaveCheckpoint");
        builder.EnableEvent<int>("OnPlayerEnterRaceCheckpoint");
        builder.EnableEvent<int>("OnPlayerLeaveRaceCheckpoint");
        builder.EnableEvent<int>("OnPlayerRequestSpawn");
        builder.EnableEvent<int, int>("OnPlayerPickUpPickup");
        builder.EnableEvent<int, int>("OnPlayerSelectedMenuRow");
        builder.EnableEvent<int>("OnPlayerExitedMenu");
        builder.EnableEvent<int, int, int>("OnPlayerInteriorChange");
        builder.EnableEvent<int, int, int>("OnPlayerKeyStateChange");
        builder.EnableEvent<int>("OnPlayerUpdate");
        builder.EnableEvent<int, int>("OnPlayerStreamIn");
        builder.EnableEvent<int, int>("OnPlayerStreamOut");
        builder.EnableEvent<int, int, float, int, int>("OnPlayerTakeDamage");
        builder.EnableEvent<int, int, float, int, int>("OnPlayerGiveDamage");
        builder.EnableEvent<int, int, float, int, int>("OnPlayerGiveDamageActor");
        builder.EnableEvent<int, float, float, float>("OnPlayerClickMap");
        builder.EnableEvent<int, int>("OnPlayerClickTextDraw");
        builder.EnableEvent<int, int>("OnPlayerClickPlayerTextDraw");
        builder.EnableEvent<int, int, int>("OnPlayerClickPlayer");
        builder.EnableEvent<int, bool, int, int, float, float, float, float, float, float>("OnPlayerEditObject");
        builder.EnableEvent<int, int, int, int, int, float, float, float, float, float, float, float, float, float>("OnPlayerEditAttachedObject");
        builder.EnableEvent<int, int, int, int, float, float, float>("OnPlayerSelectObject");
        builder.EnableEvent<int, int, int, int, float, float, float>("OnPlayerWeaponShot");
        builder.EnableEvent<int, bool, int>("OnEnterExitModShop");
        builder.EnableEvent<int, int, int, int, string>("OnDialogResponse");
        builder.EnableEvent<int, string, int>("OnIncomingConnection"); // Don't swap out player id

        void AddPlayerTarget(string callback)
        {
            builder.UseMiddleware<EntityMiddleware>(callback, 0, PlayerType, true);
        }

        builder.UseMiddleware<PlayerConnectMiddleware>("OnPlayerConnect");
        builder.UseMiddleware<PlayerDisconnectMiddleware>("OnPlayerDisconnect");
        AddPlayerTarget("OnPlayerSpawn");
        AddPlayerTarget("OnPlayerDeath");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerDeath", 1, PlayerType, false);
        AddPlayerTarget("OnPlayerText");
        AddPlayerTarget("OnPlayerCommandText");
        AddPlayerTarget("OnPlayerRequestClass");
        AddPlayerTarget("OnPlayerEnterVehicle");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerEnterVehicle", 1, VehicleType, true);
        AddPlayerTarget("OnPlayerExitVehicle");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerExitVehicle", 1, VehicleType, true);
        AddPlayerTarget("OnPlayerStateChange");
        AddPlayerTarget("OnPlayerEnterCheckpoint");
        AddPlayerTarget("OnPlayerLeaveCheckpoint");
        AddPlayerTarget("OnPlayerEnterRaceCheckpoint");
        AddPlayerTarget("OnPlayerLeaveRaceCheckpoint");
        AddPlayerTarget("OnPlayerRequestSpawn");
        AddPlayerTarget("OnPlayerPickUpPickup");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerPickUpPickup", 1, SampEntities.PickupType, true);
        AddPlayerTarget("OnPlayerSelectedMenuRow");
        AddPlayerTarget("OnPlayerExitedMenu");
        AddPlayerTarget("OnPlayerInteriorChange");
        AddPlayerTarget("OnPlayerKeyStateChange");
        AddPlayerTarget("OnPlayerUpdate");
        AddPlayerTarget("OnPlayerStreamIn");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerStreamIn", 1, PlayerType, true);
        AddPlayerTarget("OnPlayerStreamOut");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerStreamOut", 1, PlayerType, true);
        AddPlayerTarget("OnPlayerTakeDamage");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerTakeDamage", 1, PlayerType, false);
        AddPlayerTarget("OnPlayerGiveDamage");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerGiveDamage", 1, PlayerType, true);
        AddPlayerTarget("OnPlayerGiveDamageActor");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerGiveDamageActor", 1, ActorType, true);
        builder.UseMiddleware<PlayerClickMapMiddleware>("OnPlayerClickMap");
        builder.UseMiddleware<TextDrawClickMiddleware>("OnPlayerClickTextDraw");
        builder.UseMiddleware<PlayerTextDrawMiddleware>("OnPlayerClickPlayerTextDraw");
        AddPlayerTarget("OnPlayerClickPlayer");
        builder.UseMiddleware<EntityMiddleware>("OnPlayerClickPlayer", 1, PlayerType, true);
        builder.UseMiddleware<PlayerEditObjectMiddleware>("OnPlayerEditObject");
        builder.UseMiddleware<PlayerEditAttachedObjectMiddleware>("OnPlayerEditAttachedObject");
        builder.UseMiddleware<PlayerSelectObjectMiddleware>("OnPlayerSelectObject");
        builder.UseMiddleware<PlayerWeaponShotMiddleware>("OnPlayerWeaponShot");
        AddPlayerTarget("OnEnterExitModShop");
        AddPlayerTarget("OnDialogResponse");

        return builder;
    }

    /// Enables all object related SA:MP events.
    /// <param name="builder">The builder.</param>
    /// <returns>The builder.</returns>
    public static IEcsBuilder EnableObjectEvents(this IEcsBuilder builder)
    {
        builder.EnableEvent<int>("OnObjectMoved");
        builder.EnableEvent<int, int>("OnPlayerObjectMoved");

        builder.UseMiddleware<EntityMiddleware>("OnObjectMoved", 0, SampEntities.ObjectType, false);
        builder.UseMiddleware<PlayerObjectMiddleware>("OnPlayerObjectMoved");
        return builder;
    }

    /// Enables all RCON related SA:MP events.
    /// <param name="builder">The builder.</param>
    /// <returns>The builder.</returns>
    public static IEcsBuilder EnableRconEvents(this IEcsBuilder builder)
    {
        builder.EnableEvent<string>("OnRconCommand");
        builder.EnableEvent<string, string, bool>("OnRconLoginAttempt");

        return builder;
    }

    /// Enables all vehicle related SA:MP events.
    /// <param name="builder">The builder.</param>
    /// <returns>The builder.</returns>
    public static IEcsBuilder EnableVehicleEvents(this IEcsBuilder builder)
    {
        builder.EnableEvent<int>("OnVehicleSpawn");
        builder.EnableEvent<int, int>("OnVehicleDeath");
        builder.EnableEvent<int, int, int>("OnVehicleMod");
        builder.EnableEvent<int, int, int>("OnVehiclePaintjob");
        builder.EnableEvent<int, int, int, int>("OnVehicleRespray");
        builder.EnableEvent<int, int>("OnVehicleDamageStatusUpdate");
        builder.EnableEvent<int, int>("OnVehicleStreamIn");
        builder.EnableEvent<int, int>("OnVehicleStreamOut");
        builder.EnableEvent<int, int, int>("OnVehicleSirenStateChange");
        builder.EnableEvent<int, int>("OnTrailerUpdate");
        builder.EnableEvent<int, int, int, float, float, float, float, float, float>("OnUnoccupiedVehicleUpdate");

        builder.UseMiddleware<EntityMiddleware>("OnVehicleSpawn", 0, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleDeath", 0, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleDeath", 1, PlayerType, false);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleMod", 0, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleMod", 1, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehiclePaintjob", 0, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehiclePaintjob", 1, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleRespray", 0, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleRespray", 1, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleDamageStatusUpdate", 0, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleDamageStatusUpdate", 1, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleStreamIn", 0, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleStreamIn", 1, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleStreamOut", 0, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleStreamOut", 1, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleSirenStateChange", 0, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnVehicleSirenStateChange", 1, VehicleType, true);
        builder.UseMiddleware<EntityMiddleware>("OnTrailerUpdate", 0, PlayerType, true);
        builder.UseMiddleware<EntityMiddleware>("OnTrailerUpdate", 1, VehicleType, true);
        builder.UseMiddleware<UnoccupiedVehicleUpdateMiddleware>("OnUnoccupiedVehicleUpdate");

        return builder;
    }
}


text:
export function countBy(fn, list){
  if (arguments.length === 1){
    return _list => countBy(fn, _list)
  }
  const willReturn = {}

  list.forEach(item => {
    const key = fn(item)
    if (!willReturn[ key ]){
      willReturn[ key ] = 1
    } else {
      willReturn[ key ]++
    }
  })

  return willReturn
}


text:
<?php

class Project_Relation_Model extends Vtiger_Relation_Model{

	/**
	 * Function that deletes Project related records information
	 * @param <Integer> $sourceRecordId - Project Id
	 * @param <Integer> $relatedRecordId - Related Record Id
	 */
	public function deleteRelation($sourceRecordId, $relatedRecordId){
		$sourceModule = $this->getParentModuleModel();
		$sourceModuleName = $sourceModule->get('name');
		$destinationModuleName = $this->getRelationModuleModel()->get('name');
		$sourceModuleFocus = CRMEntity::getInstance($sourceModuleName);
        	$sourceModuleFocus->delete_related_module($sourceModuleName, $sourceRecordId, $destinationModuleName, $relatedRecordId);
		return true;
	}
}


text:
namespace WhiskeyFacotryMethodDemo.Products
{
    using System.Text;

    public abstract class AlcoholicBeverage
    {
        public string Taste { get; set; }

        public int YearsMatured { get; set; }

        public string CountryOfOrigin { get; protected set; }

        public override string ToString()
        {
            var drinkAsString = new StringBuilder();
            drinkAsString.AppendFormat("Drink type: {0}", this.GetType().Name);
            drinkAsString.AppendLine();
            drinkAsString.AppendFormat("Tastes: {0}", this.Taste);
            drinkAsString.AppendLine();
            drinkAsString.AppendFormat("Matured for: {0} years", this.YearsMatured);
            drinkAsString.AppendLine();
            drinkAsString.AppendFormat("Made in: {0}", this.CountryOfOrigin);
            return drinkAsString.ToString();
        }
    }
}


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.integration.cdi.service;

/**
 * @author Hardy Ferentschik
 */
public class PingServiceImpl implements PingService {
	public String ping() {
		return "pong";
	}
}


text:
using System;
using System.Runtime.InteropServices;
using Godot.NativeInterop;

namespace Godot
{
    public static class Dispatcher
    {
        internal static GodotTaskScheduler DefaultGodotTaskScheduler;

        internal static void InitializeDefaultGodotTaskScheduler()
            => DefaultGodotTaskScheduler = new GodotTaskScheduler();

        public static GodotSynchronizationContext SynchronizationContext => DefaultGodotTaskScheduler.Context;
    }
}


text:
require 'goliath'
require 'em-synchrony/em-http'

class TwilioResponse < Goliath::API
  use Goliath::Rack::Params
  use Goliath::Rack::JSONP

  HEADERS = { authorization: ENV.values_at("TWILIO_SID","TWILIO_AUTH_TOKEN") }
  BASE_URL = "https://api.twilio.com/2010-04-01/Accounts/#{ENV['TWILIO_SID']}/AvailablePhoneNumbers/US"

  def response(env)
    url = "#{BASE_URL}#{env['REQUEST_PATH']}?#{env['QUERY_STRING']}"
    logger.debug "Proxying #{url}"

    http = EM::HttpRequest.new(url).get head: HEADERS
    logger.debug "Received #{http.response_header.status} from Twilio"

    [200, {'X-Goliath' => 'Proxy','Content-Type' => 'application/javascript'}, http.response]
  end
end

class Twilio < Goliath::API
  get %r{^/(Local|TollFree)}, TwilioResponse
end


text:
"""Output the differences between two Docker images.

Usage:
  python docker_diff.py [--deep=path] <image_1> <image_2>
"""

import argparse
import json
import logging
import os
import shutil
import subprocess
import tarfile
import tempfile

def call(cmd, **kwargs):
    """run call with args."""
    logging.info('exec %s', ' '.join(cmd))
    return subprocess.call(cmd, **kwargs)

def check_call(cmd):
    """run check_call with args."""
    logging.info('exec %s', ' '.join(cmd))
    return subprocess.check_call(cmd)

def dockerfile_layers(tarball):
    '''Given a `docker save` tarball, return the layer metadata in order.'''

    layer_by_parent = {}

    for member in tarball.getmembers():
        if member.name.endswith('/json'):
            layer = json.load(tarball.extractfile(member))
            layer_by_parent[layer.get('parent')] = layer

    # assemble layers by following parent pointers
    layers = []
    parent = None  # base image has no parent
    while parent in layer_by_parent:
        layer = layer_by_parent[parent]
        layers.append(layer)
        parent = layer['id']

    return layers

def is_whiteout(fname):
    """Check if whiteout."""
    return fname.startswith('.wh.') or '/.wh.' in fname

def extract_layers(tarball, layers, outdir):
    '''Extract docker layers to a specific directory (fake a union mount).'''
    for layer in layers:
        obj = tarball.extractfile('%s/layer.tar' % layer['id'])
        with tarfile.open(fileobj=obj) as fp:
            # Complication: .wh. files indicate deletions.
            # https://github.com/docker/docker/blob/master/image/spec/v1.md
            members = fp.getmembers()
            members_good = [m for m in members if not is_whiteout(m.name)]

            fp.extractall(outdir, members_good)

            for member in members:
                name = member.name
                if is_whiteout(name):
                    path = os.path.join(outdir, name.replace('.wh.', ''))
                    if os.path.isdir(path):
                        shutil.rmtree(path)
                    elif os.path.exists(path):
                        os.unlink(path)

def docker_diff(image_a, image_b, tmpdir, deep):
    """Diff two docker images."""

    # dump images for inspection
    tf_a_path = '%s/a.tar' % tmpdir
    tf_b_path = '%s/b.tar' % tmpdir

    check_call(['docker', 'save', '-o', tf_a_path, image_a])
    check_call(['docker', 'save', '-o', tf_b_path, image_b])

    tf_a = tarfile.open(tf_a_path)
    tf_b = tarfile.open(tf_b_path)

    # find layers in order
    layers_a = dockerfile_layers(tf_a)
    layers_b = dockerfile_layers(tf_b)

    # minor optimization: skip identical layers
    common = len(os.path.commonprefix([layers_a, layers_b]))

    tf_a_out = '%s/a' % tmpdir
    tf_b_out = '%s/b' % tmpdir

    extract_layers(tf_a, layers_a[common:], tf_a_out)
    extract_layers(tf_b, layers_b[common:], tf_b_out)

    # actually compare the resulting directories

    # just show whether something changed (OS upgrades change a lot)
    call(['diff', '-qr', 'a', 'b'], cwd=tmpdir)

    if deep:
        # if requested, do a more in-depth content diff as well.
        call([
            'diff', '-rU5',
            os.path.join('a', deep),
            os.path.join('b', deep)],
             cwd=tmpdir)

def main():
    """Run docker_diff."""
    logging.basicConfig(level=logging.INFO)
    parser = argparse.ArgumentParser()
    parser.add_argument('--deep', help='Show full differences for specific directory')
    parser.add_argument('image_a')
    parser.add_argument('image_b')
    options = parser.parse_args()

    tmpdir = tempfile.mkdtemp(prefix='docker_diff_')
    try:
        docker_diff(options.image_a, options.image_b, tmpdir, options.deep)
    finally:
        shutil.rmtree(tmpdir)

if __name__ == '__main__':
    main()


text:
package com.google.errorprone.bugpatterns.threadsafety;

import static com.google.errorprone.BugPattern.Category.JDK;
import static com.google.errorprone.BugPattern.MaturityLevel.MATURE;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;

import com.google.common.base.Joiner;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;

import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;

/**
 * @author cushon@google.com (Liam Miller-Cushon)
 */
@BugPattern(name = "GuardedByChecker", altNames = "GuardedBy",
    summary = "Checks for unguarded accesses to fields and methods with @GuardedBy annotations",
    category = JDK, severity = ERROR, maturity = MATURE)
public class GuardedByChecker extends GuardedByValidator implements BugChecker.VariableTreeMatcher,
    BugChecker.MethodTreeMatcher {

  private static final String JUC_READ_WRITE_LOCK = "java.util.concurrent.locks.ReadWriteLock";

  @Override
  public Description matchMethod(MethodTree tree, final VisitorState state) {
    // Constructors are free to mutate guarded state without holding the necessary locks. It is
    // assumed that all objects are thread-local during initialization.
    if (ASTHelpers.getSymbol(tree).isConstructor()) {
      return Description.NO_MATCH;
    }

    HeldLockAnalyzer.analyze(state, new HeldLockAnalyzer.LockEventListener() {
      @Override
      public void handleGuardedAccess(
          ExpressionTree tree, GuardedByExpression guard, HeldLockSet live) {
        report(GuardedByChecker.this.checkGuardedAccess(tree, guard, live, state), state);
      }
    });

    return GuardedByValidator.validate(this, tree, state);
  }

  @Override
  public Description matchVariable(VariableTree tree, VisitorState state) {
    // We only want to check field declarations. The VariableTree might be for a local or a
    // parameter, but they won't have @GuardedBy annotations.
    return GuardedByValidator.validate(this, tree, state);
  }

  protected Description checkGuardedAccess(Tree tree, GuardedByExpression guard,
      HeldLockSet locks, VisitorState state) {

    // TODO(user): support ReadWriteLocks
    //
    // A common pattern with ReadWriteLocks is to create a copy (either a field or a local
    // variable) to refer to the read and write locks. The analysis currently can't
    // recognize that locking the copies is equivalent to locking the read or write
    // locks directly.
    //
    // Also - there are currently no annotations to specify an access policy for
    // members guarded by ReadWriteLocks. We could allow accesses when either the
    // read or write locks are held, but that's not much better than enforcing
    // nothing.
    if (isRWLock(guard, state)) {
      return Description.NO_MATCH;
    }

    if (locks.allLocks().contains(guard)) {
      return Description.NO_MATCH;
    }

    return buildDescription(tree).setMessage(buildMessage(guard, locks)).build();
  }

  /**
   * Construct a diagnostic message, e.g.:
   *
   *

   *
This access should be guarded by 'this', which is not currently held
   *
This access should be guarded by 'this'; instead found 'mu'
   *
This access should be guarded by 'this'; instead found: 'mu1', 'mu2'
   *

   */
  private String buildMessage(GuardedByExpression guard, HeldLockSet locks) {
    StringBuilder message = new StringBuilder();
    message.append(
        String.format(
            "This access should be guarded by '%s'",
            guard));
    int heldLocks = locks.allLocks().size();
    if (heldLocks == 0) {
      message.append(", which is not currently held");
    } else {
      message.append(String.format("; instead found: '%s'",
          Joiner.on("', '").join(locks.allLocks())));
    }
    String content = message.toString();
    return content;
  }

  /**
   * Returns true if the lock expression corresponds to a
   * {@code java.util.concurrent.locks.ReadWriteLock}.
   */
  private static boolean isRWLock(GuardedByExpression guard, VisitorState state) {
    Type guardType = guard.type();
    if (guardType == null) {
      return false;
    }

    Symbol rwLockSymbol = state.getSymbolFromString(JUC_READ_WRITE_LOCK);
    if (rwLockSymbol  == null) {
      return false;
    }

    return state.getTypes().isSubtype(guardType, rwLockSymbol.type);
  }

  // TODO(user) - this is a hack. Provide an abstraction for matchers that need to do
  // stateful visiting? (e.g. a traversal that passes along a set of held locks...)
  private void report(Description description, VisitorState state) {
    if (description == null || description == Description.NO_MATCH) {
      return;
    }
    state.reportMatch(description);
  }
}


text:
package com.jvpichowski.examples.es.bullet.extension;

import com.jme3.app.FlyCamAppState;
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.collision.PhysicsRayTestResult;
import com.jme3.bullet.collision.shapes.CapsuleCollisionShape;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.math.*;
import com.jme3.scene.Node;
import com.jvpichowski.jme3.es.bullet.BulletSystem;
import com.jvpichowski.jme3.es.bullet.components.*;
import com.jvpichowski.jme3.es.bullet.extension.forces.SimpleDrag;
import com.jvpichowski.jme3.es.bullet.extension.forces.SimpleDragForceLogic;
import com.jvpichowski.jme3.es.bullet.extension.logic.PhysicsSimpleLogicManager;
import com.jvpichowski.jme3.es.bullet.extension.view.PhysicsToViewLocation;
import com.jvpichowski.jme3.es.bullet.extension.view.PhysicsToViewRotation;
import com.jvpichowski.jme3.es.logic.BaseSimpleEntityLogic;
import com.jvpichowski.jme3.states.ESBulletState;
import com.jvpichowski.jme3.states.SimpleLogicManagerState;
import com.jvpichowski.jme3.states.view.BoxView;
import com.jvpichowski.jme3.states.view.CapsuleView;
import com.jvpichowski.jme3.states.view.ShapeViewState;
import com.jvpichowski.jme3.states.view.UnshadedColor;
import com.simsilica.es.EntityComponent;
import com.simsilica.es.EntityData;
import com.simsilica.es.EntityId;
import com.simsilica.es.base.DefaultEntityData;

import java.util.List;

/**
 * A simple character demo with lots of features. Test it yourself and enhance it.
 * I would be glade to see your improvements.
 */
public class CustomCharacterExample extends SimpleApplication {

    private static final int MAX_JUMP_NUMBER = 2; //Double JumpState, 3 = Triple JumpState, 1 = normal jump, 0 = no jumping
    private static final float MAX_MOVE_SPEED = 5f; //m/s
    private static final float MOVE_ACCELERATION = 2; //m/s^2
    private static final float CHARACTER_STEP_HEIGHT = 0.2f; // the height of steps that this character can climb
    private static final float CHARACTER_RADIUS = 0.3f;
    private static final float CHARACTER_HEIGHT = 1.8f; // the whole height of the character
    private static final float CHARACTER_MASS = 80f;
    private static final float CHARACTER_JUMP_HEIGHT = 0.8f; // the max jump height a character can reach with a single jump

    //the speed which is needed to throw the character to the jump height in the air
    //Epot = Ekin; m*g*h = 1/2mv^2 -> v = sqrt(2gh)
    private static final float CHARACTER_JUMP_SPEED = FastMath.sqrt(2*9.81f*CHARACTER_JUMP_HEIGHT);//m/s
    //the height of the collision capsule without the round edges
    private static final float CHARACTER_CAPSULE_HEIGHT = CHARACTER_HEIGHT-2*CHARACTER_RADIUS-CHARACTER_STEP_HEIGHT;
    //the height og the whole collision capsule
    private static final float CHARACTER_BODY_HEIGHT = CHARACTER_CAPSULE_HEIGHT+2*CHARACTER_RADIUS;
    //TODO drag only for horizontal movement on ground
    //the factor which forces the character to keep the maximum speed
    //ma = mfv^2 f = a/v^2
    private static final float DRAG_FACTOR = CHARACTER_MASS*MOVE_ACCELERATION/(MAX_MOVE_SPEED*MAX_MOVE_SPEED);

    public static void main(String[] args) {
        EntityData entityData = new DefaultEntityData();
        CustomCharacterExample app = new CustomCharacterExample(entityData, new Node());
        app.start();
    }

    private final EntityData entityData;
    private final Node root;

    public CustomCharacterExample(EntityData entityData, Node node){
        super(new FlyCamAppState(),
                new ShapeViewState(entityData, node),
                new ESBulletState(entityData),
                new SimpleLogicManagerState(entityData));
        this.entityData = entityData;
        this.root = node;
    }

    //the character id
    private EntityId character;

    @Override
    public void simpleInitApp() {
        getRootNode().attachChild(root);
        DirectionalLight sun = new DirectionalLight();
        sun.setDirection(new Vector3f(1,-0.5f,-2).normalizeLocal());
        sun.setColor(ColorRGBA.White);
        getRootNode().addLight(sun);

        SimpleLogicManagerState logicManager = getStateManager().getState(SimpleLogicManagerState.class);
        logicManager.attach(new PhysicsToViewRotation.Logic());
        logicManager.attach(new PhysicsToViewLocation.Logic());

        ESBulletState esBulletState = stateManager.getState(ESBulletState.class);
        esBulletState.onInitialize(() -> {
            //we need to register the move force otherwise the force system wouldn't apply it
            esBulletState.getBulletSystem().getForceSystem().registerForce(MoveForce.class);

            //we need a logic manager for advanced logic scripts
            PhysicsSimpleLogicManager physicsLogicManager = new PhysicsSimpleLogicManager();
            physicsLogicManager.initialize(entityData, esBulletState.getBulletSystem());
            //don't forget to destroy the logic manager in a real application
            //physicsLogicManager.destroy();

            //the simple physics logic manager supports execution of logic scripts before and
            //after the physics update. We need the drag force to be executed before because it is a force.
            physicsLogicManager.getPreTickLogicManager().attach(new CharacterLogic());
            SimpleDragForceLogic sdfl = new SimpleDragForceLogic();
            sdfl.initLogic(esBulletState.getBulletSystem());
            physicsLogicManager.getPreTickLogicManager().attach(sdfl);

            //create a simple level
            createLevel();
            createCharacter();

            //create some controls
            initInput();

        });//End of onInitialize
    }

    private void initInput(){
        getInputManager().addMapping("LEFT", new KeyTrigger(KeyInput.KEY_J));
        getInputManager().addMapping("RIGHT", new KeyTrigger(KeyInput.KEY_L));
        getInputManager().addMapping("UP", new KeyTrigger(KeyInput.KEY_I));
        getInputManager().addMapping("DOWN", new KeyTrigger(KeyInput.KEY_K));
        getInputManager().addMapping("JUMP", new KeyTrigger(KeyInput.KEY_SPACE));
        getInputManager().addListener((ActionListener) (name, isPressed, tpf) -> {
            Vector2f movement = new Vector2f();
            if(isPressed){
                switch (name) {
                    case "LEFT": movement.setX(-1); break;
                    case "RIGHT": movement.setX(+1); break;
                    case "UP": movement.setY(-1); break;
                    case "DOWN": movement.setY(+1); break;
                }
                movement.multLocal(CHARACTER_MASS*MOVE_ACCELERATION);
            }
            entityData.setComponent(character,  new MoveForce(movement));
        }, "LEFT", "RIGHT", "UP", "DOWN");
        getInputManager().addListener((ActionListener) (name, isPressed, tpf) -> {
            if(isPressed) entityData.setComponent(character, new JumpState(true));
        }, "JUMP");
    }

    //------------------------------------------------------------------------------------------//
    // logic definition                                                                         //
    //------------------------------------------------------------------------------------------//

    //the main character logic as script
    private class CharacterLogic extends BaseSimpleEntityLogic {

        @Override
        public void registerComponents() {
            //register the needed components for a character
            dependsOn(
                    PhysicsCharacter.class, PhysicsPosition.class,
                    LinearVelocity.class, AngularVelocity.class,
                    JumpCount.class, JumpState.class, MoveForce.class
            );
        }

        @Override
        public void update() {
            //update the character state based on the needed components
            //first collect some necessary information
            boolean shouldJump = get(JumpState.class).shouldJump();
            set(new JumpState(false));
            int jumpCount = get(JumpCount.class).getJumpNumber();
            boolean onGround = false;
            Vector3f velocity = get(LinearVelocity.class).getVelocity();
            PhysicsPosition pos = get(PhysicsPosition.class);

            //the most important part is the ray system which keeps the capsule floating
            //in the air over the ground
            BulletSystem bulletSystem = getStateManager().getState(ESBulletState.class).getBulletSystem();
            List<PhysicsRayTestResult> rayTestResultList = bulletSystem.getPhysicsSpace()
                    .rayTest(pos.getLocation(), pos.getLocation().add(0,-50,0));
            if(rayTestResultList.size() > 0){
                float len = 60;
                for (PhysicsRayTestResult physicsRayTestResult : rayTestResultList) {
                    if(physicsRayTestResult.getHitFraction()*50 < len){
                        len = physicsRayTestResult.getHitFraction()*50;
                    }
                }
                //if the character is near the ground or below it push it to the min step height.
                if(len <= CHARACTER_STEP_HEIGHT + CHARACTER_BODY_HEIGHT/2){
                    float diff = CHARACTER_STEP_HEIGHT + CHARACTER_BODY_HEIGHT/2-len;
                    set(new WarpPosition(pos.getLocation().add(0, diff,  0), pos.getRotation()));
                    if(velocity.y < 0) {
                        set(new WarpVelocity(velocity.clone().setY(0), Vector3f.ZERO));
                    }
                    onGround = true;
                    set(new JumpCount(0));
                    jumpCount = 0;
                }
            }

            Vector3f impulse = new Vector3f();
            //apply jump
            if(shouldJump && (onGround || jumpCount < MAX_JUMP_NUMBER)){
                set(new JumpCount(jumpCount+1));
                impulse.addLocal(new Vector3f(0, CHARACTER_MASS*CHARACTER_JUMP_SPEED, 0));
            }
            //slow the character down if no movement is applied
            if(onGround){
                Vector3f slowDownImpulse = new Vector3f();
                Vector3f move = get(MoveForce.class).getForce();
                if(FastMath.approximateEquals(move.x, 0)){
                    slowDownImpulse.setX(-velocity.x*CHARACTER_MASS*0.05f);
                }
                if(FastMath.approximateEquals(move.z, 0)){
                    slowDownImpulse.setZ(-velocity.z*CHARACTER_MASS*0.05f);
                }
                impulse.addLocal(slowDownImpulse);
            }
            //TODO use combined impulse
            set(new Impulse(impulse, new Vector3f()));
        }
    }

    //--------------------------------------------------------------------------------------//
    // data type definition                                                                 //
    //--------------------------------------------------------------------------------------//

    //a simple flag component to mark the character
    private final class PhysicsCharacter implements EntityComponent {}

    //obtain the jump number with this component
    private final class JumpCount implements EntityComponent {

        private final int jumpNumber;

        public JumpCount(int jumpNumber) {
            this.jumpNumber = jumpNumber;
        }

        public int getJumpNumber() {
            return jumpNumber;
        }
    }

    //change this component to jump
    private final class JumpState implements EntityComponent {

        private final boolean shouldJump;

        public JumpState(boolean shouldJump) {
            this.shouldJump = shouldJump;
        }

        public JumpState() {
            this(false);
        }

        public boolean shouldJump() {
            return shouldJump;
        }
    }

    //a simple force which moves the character horizontal
    private final class MoveForce implements ForceComponent {

        private final Vector3f force;

        public MoveForce(Vector2f move) {
            this.force = new Vector3f(move.x, 0, move.y);
        }

        @Override
        public Vector3f getForce() { return force; }

        @Override
        public Vector3f getLocation() { return null; }
    }

    //---------------------------------------------------------------------------------------//
    // data definition                                                                       //
    //---------------------------------------------------------------------------------------//

    private void createCharacter(){
        character = entityData.createEntity();
        entityData.setComponents(character,
                //some view stuff
                new PhysicsToViewLocation(new Vector3f(0, -CHARACTER_STEP_HEIGHT/2, 0)),
                new PhysicsToViewRotation(),
                new UnshadedColor(ColorRGBA.Red),
                new CapsuleView(CHARACTER_RADIUS, CHARACTER_HEIGHT-2*CHARACTER_RADIUS),
                //basic properties of the capsule
                new Friction(0),
                new Factor(new Vector3f(1,1,1), new Vector3f(0,0,0)),
                new RigidBody(false, CHARACTER_MASS),
                new CustomShape(new CapsuleCollisionShape(CHARACTER_RADIUS, CHARACTER_CAPSULE_HEIGHT)),
                //base character definition
                new PhysicsCharacter(),
                //drag force for max speed
                new SimpleDrag(DRAG_FACTOR),
                //jump system
                new JumpState(false),
                new JumpCount(0),
                //initial zero move force
                new MoveForce(new Vector2f()),
                new WarpPosition(new Vector3f(0, 5, 0), new Quaternion()));
    }

    private void createLevel(){
        EntityId plane = entityData.createEntity();
        entityData.setComponents(plane,
                new PhysicsToViewLocation(),
                new PhysicsToViewRotation(),
                new UnshadedColor(ColorRGBA.DarkGray),
                new BoxView(new Vector3f(50f, 0.1f, 50f)),
                new RigidBody(false, 0),
                new BoxShape(new Vector3f(50f, 0.1f, 50f)),
                new WarpPosition(new Vector3f(0f, -0.1f, 0f), new Quaternion()));

        EntityId box = entityData.createEntity();
        entityData.setComponents(box,
                new PhysicsToViewLocation(),
                new PhysicsToViewRotation(),
                new UnshadedColor(ColorRGBA.Green),
                new BoxView(new Vector3f(2f, 0.2f, 2f)),
                new RigidBody(false, 0),
                new WarpPosition(new Vector3f(0f, -0.1f, 0f), new Quaternion()),
                new BoxShape(new Vector3f(2, 0.2f, 2)));

        EntityId wall = entityData.createEntity();
        entityData.setComponents(wall,
                new PhysicsToViewLocation(),
                new PhysicsToViewRotation(),
                new UnshadedColor(ColorRGBA.Green),
                new BoxView(new Vector3f(0.2f, 10f, 10f)),
                new RigidBody(false, 0),
                new WarpPosition(new Vector3f(5,0,0), new Quaternion()),
                new BoxShape(new Vector3f(0.2f, 10f, 10f)));

        EntityId ramp = entityData.createEntity();
        entityData.setComponents(ramp,
                new PhysicsToViewLocation(),
                new PhysicsToViewRotation(),
                new UnshadedColor(ColorRGBA.Blue),
                new BoxView(new Vector3f(2f, 0.2f, 2f)),
                new WarpPosition(new Vector3f(-10,0,0),
                        new Quaternion().fromAngleAxis(FastMath.DEG_TO_RAD * 10, Vector3f.UNIT_Z)),
                new RigidBody(false, 0),
                new BoxShape(new Vector3f(2f, 0.2f, 2f)));

        EntityId ramp2 = entityData.createEntity();
        entityData.setComponents(ramp2,
                new PhysicsToViewLocation(),
                new PhysicsToViewRotation(),
                new UnshadedColor(ColorRGBA.Blue),
                new BoxView(new Vector3f(2f, 0.2f, 2f)),
                new WarpPosition(new Vector3f(-6f,0,0),
                        new Quaternion().fromAngleAxis(FastMath.DEG_TO_RAD * -10, Vector3f.UNIT_Z)),
                new RigidBody(false, 0),
                new BoxShape(new Vector3f(2f, 0.2f, 2f)));
    }
}


text:
import os

import wx

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title='Dialog Show', size=(640, 640))
        self.panel = wx.Panel(self)

        # result show
        wx.StaticText(self.panel, -1, 'Result Show:', (10, 10), (100, -1))
        self.textShow = wx.TextCtrl(self.panel, -1, 'This is result show', (100, 10), (300, -1))

        # MessageDialog
        wx.Button(self.panel, 10, 'MessageDialog', (100, 50))
        self.Bind(wx.EVT_BUTTON, self.OnMessageDialog, id=10)
        wx.Button(self.panel, 11, 'MessageDialog2', (250, 50))
        self.Bind(wx.EVT_BUTTON, self.OnMessageDialog2, id=11)

        # TextEntryDialog
        wx.Button(self.panel, 20, 'TextEntryDialog', (100, 80))
        self.Bind(wx.EVT_BUTTON, self.OnTextEntryDialog, id=20)
        wx.Button(self.panel, 21, 'TextEntryDialog2', (250, 80))
        self.Bind(wx.EVT_BUTTON, self.OnTextEntryDialog2, id=21)

        # SingleChoiceDialgo
        self.choices = ['Alpha', 'Baker', 'Charlie', 'Delta']
        wx.Button(self.panel, 30, 'SingleChoiceDialog', (100, 110))
        self.Bind(wx.EVT_BUTTON, self.OnSingleChoiceDialog, id=30)
        wx.Button(self.panel, 31, 'SingleChoiceDialog2', (250, 110))
        self.Bind(wx.EVT_BUTTON, self.OnSingleChoiceDialog2, id=31)

        # ProgressDialog
        progressMax = 100
        dlg = wx.ProgressDialog('A Progress Box', 'Time remaining', progressMax,
                                style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME)  # |wx.PD_AUTO_HIDE)
        keepGoing = True
        count = 0
        while keepGoing and count < progressMax:
            count += 1
            # wx.Sleep(1)
            keepGoing = dlg.Update(count, 'Count:%d' % count)
        dlg.Destroy()

        # FileDialog & DirDialog
        wx.Button(self.panel, 40, 'FileDialog', (100, 150))
        self.Bind(wx.EVT_BUTTON, self.OnFileDialog, id=40)
        wx.Button(self.panel, 41, 'DirDialog', (250, 150))
        self.Bind(wx.EVT_BUTTON, self.OnDirDialog, id=41)

    def OnMessageDialog(self, event):
        dlg = wx.MessageDialog(None, 'This is a MessageDialog Created By class!', 'MessageDialog',
                               wx.YES_NO | wx.ICON_QUESTION)
        dlg.ShowModal()
        dlg.Destroy()

    def OnMessageDialog2(self, event):
        dlg = wx.MessageBox('This is a MessageDialog Created By function!', 'MessageDialog2',
                            wx.OK | wx.CANCEL | wx.ICON_QUESTION)

    def OnTextEntryDialog(self, event):
        dlg = wx.TextEntryDialog(None, 'Just input text,ok?', 'Text Entry', 'Default value', style=wx.OK | wx.CANCEL)
        if dlg.ShowModal() == wx.ID_OK:
            self.textShow.SetValue('TextEntryDialog:%s' % dlg.GetValue())
        dlg.Destroy()

    def OnTextEntryDialog2(self, event):
        password = wx.GetPasswordFromUser('Your password:')
        self.textShow.SetValue('TextEntryDialog:password=%s' % password)

    def OnSingleChoiceDialog(self, event):
        dlg = wx.SingleChoiceDialog(None, 'Picke a word', 'Choices', self.choices)
        if dlg.ShowModal() == wx.ID_OK:
            self.textShow.SetValue('SingleChoiceDialog:You select %s' % dlg.GetStringSelection())
        dlg.Destroy()

    def OnSingleChoiceDialog2(self, event):
        choice = wx.GetSingleChoice('Pick a word', 'Choices', self.choices)
        self.textShow.SetValue('SingleChoiceDialog:choice=%s' % choice)

    def OnFileDialog(self, event):
        wildcard = "JPG(*.jpg)|*.jpg|All files(*.*)|*.*"
        dlg = wx.FileDialog(None, 'Choose a file', os.getcwd(), "", wildcard, wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.textShow.SetValue('You choose file:%s' % dlg.GetPath())
        dlg.Destroy()

    def OnDirDialog(self, event):
        dlg = wx.DirDialog(None, 'Choose a directory:', style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        if dlg.ShowModal() == wx.ID_OK:
            self.textShow.SetValue('You choose dir:%s' % dlg.GetPath())
        dlg.Destroy()

class MyApp(wx.App):
    def OnInit(self):
        self.frame = MainFrame()
        self.frame.Show()

        self.SetTopWindow(self.frame)

        return True

if __name__ == '__main__':
    app = MyApp()
    app.MainLoop()


text:
namespace TeensyStep
{

    namespace
    {
        TF_Handler* Handler[4];

        template <int n>
        void dispatchFunc()
        {
            Handler[n]->stepTimerISR();
        }

        constexpr void (*dispatcher[])(void) =
            {
                dispatchFunc<0>,
                dispatchFunc<1>,
                dispatchFunc<2>,
                dispatchFunc<3>};

        void dummyISR(void) {}
    }

    pitErr PIT::begin(TF_Handler* handler)
    {
        if (timer.begin(dummyISR, 1E6)) // try to reserve a timer
        {
            const int channelNr = setupChannel();    // find pit channel of reserved timer
            Handler[channelNr] = handler;            // store handler
            timer.priority(32);
            timer.begin(dispatcher[channelNr], 1E6); // attach an ISR which will call the stored handler
            stop();                                  // stop doesn't clear TEN, we want to keep the IntervalTimer reserved
            return pitErr::OK;
        }
        return err(pitErr::outOfTimers);
    }

    int PIT::setupChannel()
    {
        IRQ_NUMBER_t number = (IRQ_NUMBER_t)timer;
        switch (number)
        {
            case IRQ_PIT_CH0:
                channel = KINETISK_PIT_CHANNELS + 0;
                return 0;
            case IRQ_PIT_CH1:
                channel = KINETISK_PIT_CHANNELS + 1;
                return 1;
            case IRQ_PIT_CH2:
                channel = KINETISK_PIT_CHANNELS + 2;
                return 2;
            case IRQ_PIT_CH3:
                channel = KINETISK_PIT_CHANNELS + 3;
                return 3;
            default:
                channel = nullptr;
                err(pitErr::argErr);
                return -1;
        }
    }
}
#endif