text:
package com.mb3364.twitch.api.models;

public class TopGame {

    private Game game;
    private int viewers;
    private int channels;

    @Override
    public String toString() {
        return "TopGame{" +
                "game=" + game +
                ", viewers=" + viewers +
                ", channels=" + channels +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TopGame topGame = (TopGame) o;

        if (viewers != topGame.viewers) return false;
        if (channels != topGame.channels) return false;
        return !(game != null ? !game.equals(topGame.game) : topGame.game != null);

    }

    @Override
    public int hashCode() {
        int result = game != null ? game.hashCode() : 0;
        result = 31 * result + viewers;
        result = 31 * result + channels;
        return result;
    }

    public Game getGame() {
        return game;
    }

    public void setGame(Game game) {
        this.game = game;
    }

    public int getViewers() {
        return viewers;
    }

    public void setViewers(int viewers) {
        this.viewers = viewers;
    }

    public int getChannels() {
        return channels;
    }

    public void setChannels(int channels) {
        this.channels = channels;
    }
}


text:
<?php
/*
 * @Author: michael.shi
 * @Date: 2017-08-17 19:22:12
 * @Last Modified by: michael.shi
 * @Last Modified time: 2017-08-17 19:45:02
 */

namespace app\models\form;

use Yii;
use yii\base\Model;
use app\models\ar\User;
use app\models\ar\Project;

/**
* ContactForm is the model behind the contact form.
*/
class ProjectUserRoleForm extends Model
{

    public $username;

    public $role;

    /**
     * @var Project
     */
    public $project;

    public $_user = false;

    /**
    * @return array the validation rules.
    */
    public function rules()
    {
        return [
            [['username', 'role'], 'required'],
            [['username'], 'exist', 'targetClass' => 'app\models\ar\User'],
            [['username'], 'verify'],
        ];
    }

    public function verify($attribute, $params){
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if($this->project->isUserInProject($user->id)){
                $this->addError($attribute, 'This user has already been added to the project.');
            }
        }
    }

    public function save(){
        $user = $this->getUser();
        if(!empty($user)){
            return $this->project->associateUserToRole($this->role, $user->id);
        }
        return false;
    }

    public function getUser(){
        if($this->_user === false){
            $this->_user = User::find()->where('username=:username', [':username' => $this->username])->one();
        }

        return $this->_user;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

/*
 * Aluno 01: Ivanildo Simplício da Silva Filho
 * Aluno 02: Fernanda Eduarda de Medeiros Silva
 * Aluno 03: Wesley Porto Santos
 *
 */

public class PedraPapelTesoura {

	Scanner sc = new Scanner(System.in);
	Random rand = new Random();
	final int COMBINACOES = 3;
	final int SAIR = -1;
	int escolhaPlayer1;
	int escolhaPlayer2;
	String tipoJogador;

	public static void main(String[] args) {
		PedraPapelTesoura jogo = new PedraPapelTesoura();
		jogo.play();
	}

	public void play() {
		tipoJogador = tipoDeJogo();
		while(true) {
			System.out.print("JOGADOR 1:");
			escolhaPlayer1 = escolhaDoJogador();
			System.out.printf("%s: ", tipoJogador);
			if(tipoJogador.equals("COMPUTADOR")){
				escolhaPlayer2 = 1+rand.nextInt(3);
				System.out.println(escolhaPlayer2);
			}else {
				escolhaPlayer2 = escolhaDoJogador();
			}

			System.out.printf("\n%s - %s\n", jogada(escolhaPlayer1), jogada(escolhaPlayer2));
			if(!resultado()) {
				sc.nextLine();
				String buffer = sc.nextLine();
				if(buffer.equals("-1"))
					break;
			}
		}
	}

	public String tipoDeJogo() {
		int opcao = -1;
		do {
			System.out.print("Deseja jogar contra: (1) Player - (2) Computador ? ");
			try{
				opcao = sc.nextInt();
			}catch(InputMismatchException e) {
				sc.nextLine();
				//Não trata nada, apenas repetirá a mensagem solicitando um valor
			}
		}while(opcao < 1 || opcao > 2);
		return opcao == 1 ? "JOGADOR 2" : "COMPUTADOR";
	}

	public int escolhaDoJogador() {
		int escolha = -1;
		do {
			System.out.print("\n(1) Pedra - (2) Papel - (3) Tesoura? ");
			try {
				escolha = sc.nextInt();
			}catch(InputMismatchException e) {
				sc.nextLine();
				//Não trata nada, apenas repetirá a mensagem solicitando um valor
			}
		}while(escolha < 1 || escolha > COMBINACOES);
		return escolha;
	}

	public String jogada(int escolhaDoPlayer) {
		String jogada = "";
		switch(escolhaDoPlayer) {
			case 1: jogada = "PEDRA";
				break;
			case 2: jogada = "PAPEL";
				break;
			case 3: jogada = "TESOURA";
				break;
		}
		return jogada;
	}

	public boolean resultado() {
		int resultado = Math.abs((COMBINACOES+escolhaPlayer1-escolhaPlayer2) % COMBINACOES);

		if(0 < resultado && resultado <= (COMBINACOES/2)) {
			System.out.println("O JOGADOR 1 VENCEU!");
		}else if(resultado > (COMBINACOES/2)) {
			System.out.printf("O %s VENCEU!\n", tipoJogador);
		}else{
			System.out.println("EMPATE!\n");
			return true;
		}
		return false;
	}
}


text:
@interface NSMutableAttributedString (PYException)

@end


text:
export {default as Example} from './modules/Example';
export {default as Load} from './modules/Load';
export {default as Scroll} from './modules/Scroll';


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('itclassified', '0020_itclog_date_update'),
    ]

    operations = [
        migrations.AlterField(
            model_name='itclog',
            name='status',
            field=models.CharField(choices=[('5', 'ALL'), ('1', 'waiting'), ('2', 'running'), ('3', 'done'), ('4', 'error')], default='0', help_text='Current status', max_length=1),
        ),
    ]


text:
<?php

/**
 * Single Product Share
 *
 * Sharing plugins can hook into here or you can add your own code directly.
 *
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version     1.6.4
 */
if ( !defined( 'ABSPATH' ) )
    exit; // Exit if accessed directly
?>

<?php

do_action( 'woocommerce_share' ); // Sharing plugins can hook into here ?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.sap.cloud.yaas.service-sdk</groupId>
		<artifactId>service-sdk-superpom</artifactId>
		<version>4.3.4</version>
		<relativePath />
	</parent>

	<groupId>com.sap.cloud.yaas.service-sdk.example</groupId>
	<artifactId>java-jersey-wishlist</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<!-- SAP projects -->
		<service-sdk.version>4.3.4</service-sdk.version>

		<!-- plugins -->
		<jetty.plugin.version>9.3.2.v20150730</jetty.plugin.version>

		<!-- libraries -->
		<jaxrs.version>2.0.1</jaxrs.version>
		<jersey.version>2.19</jersey.version>
		<javax.servlet.version>3.1.0</javax.servlet.version>
		<spring.version>4.2.0.RELEASE</spring.version>
		<cors.filter.version>2.4</cors.filter.version>

		<!-- test libraries -->
		<junit.version>4.12</junit.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.sap.cloud.yaas.service-sdk</groupId>
			<artifactId>service-sdk-libraries</artifactId>
			<version>${service-sdk.version}</version>
		</dependency>
		<dependency>
			<groupId>com.sap.cloud.yaas.service-sdk</groupId>
			<artifactId>service-sdk-authorization</artifactId>
			<version>${service-sdk.version}</version>
		</dependency>
		<!-- Jersey Dependencies -->
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>${jaxrs.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-jackson</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-multipart</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.ext</groupId>
			<artifactId>jersey-spring3</artifactId>
			<version>${jersey.version}</version>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-core</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-beans</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-context</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-web</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.ext</groupId>
			<artifactId>jersey-bean-validation</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.test-framework.providers</groupId>
			<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
			<version>${jersey.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Servlet Dependencies -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${javax.servlet.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- testing -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- CORS support -->
		<dependency>
			<groupId>com.thetransactioncompany</groupId>
			<artifactId>cors-filter</artifactId>
			<version>${cors.filter.version}</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>java-jersey-wishlist</finalName>
		<plugins>

            <plugin>
                <groupId>com.sap.cloud.yaas.service-sdk</groupId>
                <artifactId>service-sdk-generator-maven-plugin</artifactId>
                <version>${service-sdk.version}</version>
                <executions>
                    <execution>
                        <id>Service</id>
                        <goals>
                            <goal>generate-service</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>Customer</id>
                        <goals>
                            <goal>generate-client</goal>
                        </goals>
                        <configuration>
                            <sourceRamlUri>https://api.yaas.io/hybris/customer/b1/api-console/raml/api/api-specification.raml</sourceRamlUri>
                            <basePackage>com.sap.wishlist.client.customer</basePackage>
                        </configuration>
                    </execution>

                    <execution>
                        <id>DocumentRepository</id>
                        <goals>
                            <goal>generate-client</goal>
                        </goals>
                        <configuration>
                            <sourceRamlUri>https://api.yaas.io/hybris/document/b2/api-console/raml/api/document.raml</sourceRamlUri>
                            <basePackage>com.sap.wishlist.client.documentrepository</basePackage>
                        </configuration>
                    </execution>

                    <execution>
                        <id>EMail</id>
                        <goals>
                            <goal>generate-client</goal>
                        </goals>
                        <configuration>
                            <sourceRamlFile>emailservice.raml</sourceRamlFile>
                            <basePackage>com.sap.wishlist.client.email</basePackage>
                        </configuration>
                    </execution>

                    <execution>
                        <id>MediaRepository</id>
                        <goals>
                            <goal>generate-client</goal>
                        </goals>
                        <configuration>
                            <sourceRamlUri>https://api.yaas.io/hybris/media/b2/api-console/raml/api/media.raml</sourceRamlUri>
                            <basePackage>com.sap.wishlist.client.mediaRepository</basePackage>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>${jetty.plugin.version}</version>
				<configuration>
					<scanIntervalSeconds>10</scanIntervalSeconds>
					<webApp>
						<contextPath>/</contextPath>
					</webApp>
				</configuration>
			</plugin>

		</plugins>
		<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings
					only. It has no influence on the Maven build itself. -->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>com.sap.cloud.yaas.service-sdk</groupId>
										<artifactId>service-sdk-generator-maven-plugin</artifactId>
										<versionRange>[${service-sdk.version},)</versionRange>
										<goals>
											<goal>generate-service</goal>
											<goal>generate-client</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore />
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>

</project>


text:
import * as React from 'react';
import {Page, Navbar, Timeline, TimelineItem, TimelineItemChild, TimelineYear, TimelineMonth, List, ListItem, Card} from 'framework7-react';

const generateRandomDailyTasks = (maxNumberOfTasksPerDay: number) => {
    return (Array.apply(null, Array(Math.round(Math.random() * maxNumberOfTasksPerDay))).map((item, index) => {
        return (
            <TimelineItemChild
                key={index}
                inner
                time={`${Math.round(Math.random()*23)} :00`}
                text={`Task ${index + 1}`} />
        );
    }));
}

export const TimelineCalendarPage = () => {
    return (
        <Page>
            <Navbar backLink="Back" title="Timeline Calendar" sliding />

            <Timeline horizontal col="33" tablet-col="15">
                <TimelineYear title="2016">
                    <TimelineMonth title="December">
                    {
                        Array.apply(null, Array(11)).map((item, index) => {
                            return (
                                <TimelineItem  key={index} date={index + 21}>
                                {
                                    generateRandomDailyTasks(3)
                                }
                                </TimelineItem>
                            );
                        })
                    }
                    </TimelineMonth>
                </TimelineYear>
                <TimelineYear title="2017">
                    <TimelineMonth title="January">
                    {
                        Array.apply(null, Array(31)).map((item, index) => {
                            return (
                                <TimelineItem  key={index} date={index + 1}>
                                {
                                    generateRandomDailyTasks(4)
                                }
                                </TimelineItem>
                            );
                        })
                    }
                    </TimelineMonth>
                    <TimelineMonth title="February">
                    {
                        Array.apply(null, Array(28)).map((item, index) => {
                            return (
                                <TimelineItem  key={index} date={index + 1}>
                                {
                                    generateRandomDailyTasks(5)
                                }
                                </TimelineItem>
                            );
                        })
                    }
                    </TimelineMonth>
                </TimelineYear>
            </Timeline>
        </Page>
    );
}


text:
package uk.gov.hmrc.ct.accounts

import uk.gov.hmrc.ct.box.{CtBoxIdentifier, CtOptionalString, Input}

case class AC2(value: Option[String]) extends CtBoxIdentifier(name = "Company Name") with CtOptionalString with Input


text:
import _Base = require('../Core/_Base');
import _ScrollViewer = require('./ScrollViewer/_ScrollViewer');

var module: typeof _ScrollViewer = null;
function getModule() {
    if (!module) {
        require(["./ScrollViewer/_ScrollViewer"], (m: typeof _ScrollViewer) => {
            module = m;
        });
    }
    return module;
}

_Base.Namespace.define("WinJS.UI", {
    /// <summary locid="WinJS.UI.ScrollMode">
    /// The input behavior for the ScrollViewer.
    /// </summary>
    ScrollMode: {
        get: () => {
            return getModule().ScrollMode;
        }
    },

    /// <signature helpKeyword="WinJS.UI.ScrollViewer">
    /// <summary locid="WinJS.UI.ScrollViewer.constructor">
    /// Creates a new ScrollViewer.
    /// </summary>
    /// <param name="element" type="HTMLElement" domElement="true" isOptional="true" locid="WinJS.UI.ScrollViewer.constructor_p:element">
    /// The DOM element that hosts the ScrollViewer.
    /// </param>
    /// <param name="options" type="Object" isOptional="true" locid="WinJS.UI.ScrollViewer.constructor_p:options">
    /// An object that contains one or more property/value pairs to apply to the new control.
    /// Each property of the options object corresponds to one of the control's properties or events.
    /// </param>
    /// <returns type="WinJS.UI.ScrollViewer" locid="WinJS.UI.ScrollViewer.constructor_returnValue">
    /// The new ScrollViewer.
    /// </returns>
    /// </signature>
    ScrollViewer: {
        get: () => {
            return getModule().ScrollViewer;
        }
    }
});


text:
package com.evolveum.midpoint.prism;

import com.evolveum.midpoint.prism.delta.ContainerDelta;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.path.NameItemPathSegment;
import com.evolveum.midpoint.prism.schema.PrismSchema;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.QNameUtil;

import javax.xml.namespace.QName;

import org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * Definition of a property container.
 *

 * Property container groups properties into logical blocks. The reason for
 * grouping may be as simple as better understandability of data structure. But
 * the group usually means different meaning, source or structure of the data.
 * For example, the property container is frequently used to hold properties
 * that are dynamic, not fixed by a static schema. Such grouping also naturally
 * translates to XML and helps to "quarantine" such properties to avoid Unique
 * Particle Attribute problems.
 *

 * Property Container contains a set of (potentially multi-valued) properties.
 * The order of properties is not significant, regardless of the fact that it
 * may be fixed in the XML representation. In the XML representation, each
 * element inside Property Container must be either Property or a Property
 * Container.
 *

 * This class represents schema definition for property container. See
 * {@link Definition} for more details.
 *
 * @author Radovan Semancik
 */
public class PrismContainerDefinition<V extends Containerable> extends ItemDefinition {

    private static final long serialVersionUID = -5068923696147960699L;

    protected ComplexTypeDefinition complexTypeDefinition;
    protected Class<V> compileTimeClass;

    /**
     * The constructors should be used only occasionally (if used at all).
     * Use the factory methods in the ResourceObjectDefintion instead.
     */
    public PrismContainerDefinition(QName name, ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext) {
        this(name, complexTypeDefinition, prismContext, null);
    }

    public PrismContainerDefinition(QName name, ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext,
    		Class<V> compileTimeClass) {
        super(name, determineTypeName(complexTypeDefinition), prismContext);
        this.complexTypeDefinition = complexTypeDefinition;
        if (complexTypeDefinition == null) {
            isRuntimeSchema = true;
            super.setDynamic(true);
        } else {
            isRuntimeSchema = complexTypeDefinition.isXsdAnyMarker();
            super.setDynamic(isRuntimeSchema);
        }
		this.compileTimeClass = compileTimeClass;
    }

    private static QName determineTypeName(ComplexTypeDefinition complexTypeDefinition) {
        if (complexTypeDefinition == null) {
            // Property container without type: xsd:any
            // FIXME: this is kind of hack, but it works now
            return DOMUtil.XSD_ANY;
        }
        return complexTypeDefinition.getTypeName();
    }

    public Class<V> getCompileTimeClass() {
		if (compileTimeClass != null) {
			return compileTimeClass;
		}
		if (complexTypeDefinition == null) {
			return null;
		}
		return (Class<V>) complexTypeDefinition.getCompileTimeClass();
	}

	public void setCompileTimeClass(Class<V> compileTimeClass) {
		this.compileTimeClass = compileTimeClass;
	}

    protected String getSchemaNamespace() {
        return getName().getNamespaceURI();
    }

    public ComplexTypeDefinition getComplexTypeDefinition() {
        return complexTypeDefinition;
    }

    public void setComplexTypeDefinition(ComplexTypeDefinition complexTypeDefinition) {
        this.complexTypeDefinition = complexTypeDefinition;
    }

    @Override
    public boolean isAbstract() {
        if (super.isAbstract()) {
            return true;
        }
        if (complexTypeDefinition != null && complexTypeDefinition.isAbstract()) {
            return true;
        }
        return false;
    }

    /**
     * Returns true if the definition does not define specific items but it is just
     * a "wildcard" for any kind of item (usually represented as xsd:any type).
     */
	public boolean isWildcard() {
		if (getTypeName().equals(DOMUtil.XSD_ANY)) {
			return true;
		}
//		if (complexTypeDefinition != null && complexTypeDefinition.isXsdAnyMarker()) {
//			return true;
//		}
		return false;
	}

    @Override
	void revive(PrismContext prismContext) {
		if (this.prismContext != null) {
			return;
		}
		this.prismContext = prismContext;
		if (complexTypeDefinition != null) {
			complexTypeDefinition.revive(prismContext);
		}
	}

	public <D extends ItemDefinition> D findItemDefinition(QName name, Class<D> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("type not specified while searching for " + name + " in " + this);
        }
        if (name == null) {
            throw new IllegalArgumentException("name not specified while searching in " + this);
        }

        if (complexTypeDefinition == null) {
        	// xsd:any and similar dynamic definitions
        	return null;
        }

        return complexTypeDefinition.findItemDefinition(name, clazz);
    }

    public <T extends ItemDefinition> T findItemDefinition(ItemPath path, Class<T> clazz) {
    	while (!path.isEmpty() && !(path.first() instanceof NameItemPathSegment)) {
    		path = path.rest();
    	}
        if (path.isEmpty()) {
            return (T) this;
        }

        QName firstName = ((NameItemPathSegment)path.first()).getName();

		// we need to be compatible with older versions..soo if the path does
		// not contains qnames with namespaces defined (but the prefix was
		// specified) match definition according to the local name
        if (StringUtils.isEmpty(firstName.getNamespaceURI())) {
        	for (ItemDefinition def : getDefinitions()){
        		if (QNameUtil.match(firstName, def.getName())){
        			return def.findItemDefinition(path.rest(), clazz);
        		}
        	}
        }

        for (ItemDefinition def : getDefinitions()) {
            if (firstName.equals(def.getName())) {
                return def.findItemDefinition(path.rest(), clazz);
            }
        }
        return null;
    }

    public ItemDefinition findItemDefinition(QName name) {
        return findItemDefinition(name, ItemDefinition.class);
    }

    public ItemDefinition findItemDefinition(ItemPath path) {
        return findItemDefinition(path, ItemDefinition.class);
    }

    /**
     * Finds a PropertyDefinition by looking at the property name.
     *

     * Returns null if nothing is found.
     *
     * @param name property definition name
     * @return found property definition or null
     */
    public PrismPropertyDefinition findPropertyDefinition(QName name) {
        return findItemDefinition(name, PrismPropertyDefinition.class);
    }

    public PrismPropertyDefinition findPropertyDefinition(ItemPath path) {
        while (!path.isEmpty() && !(path.first() instanceof NameItemPathSegment)) {
    		path = path.rest();
    	}
        if (path.isEmpty()) {
            throw new IllegalArgumentException("Property path is empty while searching for property definition in " + this);
        }
        QName firstName = ((NameItemPathSegment)path.first()).getName();
        if (path.size() == 1) {
            return findPropertyDefinition(firstName);
        }
        PrismContainerDefinition pcd = findContainerDefinition(firstName);
        if (pcd == null) {
            throw new IllegalArgumentException("There is no " + firstName + " subcontainer in " + this);
        }
        return pcd.findPropertyDefinition(path.rest());
    }

    public PrismReferenceDefinition findReferenceDefinition(QName name) {
        return findItemDefinition(name, PrismReferenceDefinition.class);
    }

    /**
     * Finds an inner PropertyContainerDefinition by looking at the property container name.
     *

     * Returns null if nothing is found.
     *
     * @param name property container definition name
     * @return found property container definition or null
     */
    public <X extends Containerable> PrismContainerDefinition<X> findContainerDefinition(QName name) {
        return findItemDefinition(name, PrismContainerDefinition.class);
    }

    public <X extends Containerable> PrismContainerDefinition<X> findContainerDefinition(String name) {
        return findContainerDefinition(new QName(getNamespace(), name));
    }

    /**
     * Finds an inner PropertyContainerDefinition by following the property container path.
     *

     * Returns null if nothing is found.
     *
     * @param path property container path
     * @return found property container definition or null
     */
    public PrismContainerDefinition findContainerDefinition(ItemPath path) {
        return findItemDefinition(path, PrismContainerDefinition.class);
    }

    /**
     * Returns set of property definitions.
     *

     * WARNING: This may return definitions from the associated complex type.
     * Therefore changing the returned set may influence also the complex type definition.
     *

     * The set contains all property definitions of all types that were parsed.
     * Order of definitions is insignificant.
     *
     * @return set of definitions
     */
    public List<? extends ItemDefinition> getDefinitions() {
        if (complexTypeDefinition == null) {
            // e.g. for xsd:any containers
            // FIXME
            return new ArrayList<ItemDefinition>();
        }
        return complexTypeDefinition.getDefinitions();
    }

    /**
     * Returns set of property definitions.
     *

     * The set contains all property definitions of all types that were parsed.
     * Order of definitions is insignificant.
     *

     * The returned set is immutable! All changes may be lost.
     *
     * @return set of definitions
     */
    public List<PrismPropertyDefinition> getPropertyDefinitions() {
    	List<PrismPropertyDefinition> props = new ArrayList<PrismPropertyDefinition>();
        for (ItemDefinition def : complexTypeDefinition.getDefinitions()) {
            if (def instanceof PrismPropertyDefinition) {
                props.add((PrismPropertyDefinition) def);
            }
        }
        return props;
    }

    /**
     * Create property container instance with a default name.
     *

     * This is a preferred way how to create property container.
     */
    @Override
    public PrismContainer<V> instantiate() {
        return instantiate(getName());
    }

    /**
     * Create property container instance with a specified name and element.
     *

     * This is a preferred way how to create property container.
     */
    @Override
    public PrismContainer<V> instantiate(QName elementName) {
        return new PrismContainer<V>(elementName, this, prismContext);
    }

    @Override
	public ContainerDelta<V> createEmptyDelta(ItemPath path) {
		return new ContainerDelta(path, this);
	}

	/**
     * Shallow clone
     */
    @Override
    public PrismContainerDefinition<V> clone() {
        PrismContainerDefinition<V> clone = new PrismContainerDefinition<V>(name, complexTypeDefinition, prismContext, compileTimeClass);
        copyDefinitionData(clone);
        return clone;
    }

    protected void copyDefinitionData(PrismContainerDefinition<V> clone) {
        super.copyDefinitionData(clone);
        clone.complexTypeDefinition = this.complexTypeDefinition;
        clone.isRuntimeSchema = this.isRuntimeSchema;
        clone.compileTimeClass = this.compileTimeClass;
    }

    public PrismContainerDefinition<V> cloneWithReplacedDefinition(QName itemName, ItemDefinition newDefinition) {
    	PrismContainerDefinition<V> clone = clone();
    	ComplexTypeDefinition originalComplexTypeDefinition = getComplexTypeDefinition();
        ComplexTypeDefinition cloneComplexTypeDefinition = originalComplexTypeDefinition.clone();
        clone.setComplexTypeDefinition(cloneComplexTypeDefinition);
        cloneComplexTypeDefinition.replaceDefinition(itemName, newDefinition);
        return clone;
    }

    /**
     * Creates new instance of property definition and adds it to the container.
     *

     * This is the preferred method of creating a new definition.
     *
     * @param name     name of the property (element name)
     * @param typeName XSD type of the property
     * @return created property definition
     */
    public PrismPropertyDefinition createPropertyDefinition(QName name, QName typeName) {
        PrismPropertyDefinition propDef = new PrismPropertyDefinition(name, typeName, prismContext);
        addDefinition(propDef);
        return propDef;
    }

    private void addDefinition(ItemDefinition itemDef) {
    	((Collection)getDefinitions()).add(itemDef);
    }

    /**
     * Creates new instance of property definition and adds it to the container.
     *

     * This is the preferred method of creating a new definition.
     *
     * @param name      name of the property (element name)
     * @param typeName  XSD type of the property
     * @param minOccurs minimal number of occurrences
     * @param maxOccurs maximal number of occurrences (-1 means unbounded)
     * @return created property definition
     */
    public PrismPropertyDefinition createPropertyDefinition(QName name, QName typeName,
            int minOccurs, int maxOccurs) {
        PrismPropertyDefinition propDef = new PrismPropertyDefinition(name, typeName, prismContext);
        propDef.setMinOccurs(minOccurs);
        propDef.setMaxOccurs(maxOccurs);
        addDefinition(propDef);
        return propDef;
    }

    // Creates reference to other schema
    // TODO: maybe check if the name is in different namespace
    // TODO: maybe create entirely new concept of property reference?
    public PrismPropertyDefinition createPropertyDefinition(QName name) {
        PrismPropertyDefinition propDef = new PrismPropertyDefinition(name, null, prismContext);
        addDefinition(propDef);
        return propDef;
    }

    /**
     * Creates new instance of property definition and adds it to the container.
     *

     * This is the preferred method of creating a new definition.
     *
     * @param localName name of the property (element name) relative to the schema namespace
     * @param typeName  XSD type of the property
     * @return created property definition
     */
    public PrismPropertyDefinition createPropertyDefinition(String localName, QName typeName) {
        QName name = new QName(getSchemaNamespace(), localName);
        return createPropertyDefinition(name, typeName);
    }

    /**
     * Creates new instance of property definition and adds it to the container.
     *

     * This is the preferred method of creating a new definition.
     *
     * @param localName     name of the property (element name) relative to the schema namespace
     * @param localTypeName XSD type of the property
     * @return created property definition
     */
    public PrismPropertyDefinition createPropertyDefinition(String localName, String localTypeName) {
        QName name = new QName(getSchemaNamespace(), localName);
        QName typeName = new QName(getSchemaNamespace(), localTypeName);
        return createPropertyDefinition(name, typeName);
    }

    /**
     * Creates new instance of property definition and adds it to the container.
     *

     * This is the preferred method of creating a new definition.
     *
     * @param localName     name of the property (element name) relative to the schema namespace
     * @param localTypeName XSD type of the property
     * @param minOccurs     minimal number of occurrences
     * @param maxOccurs     maximal number of occurrences (-1 means unbounded)
     * @return created property definition
     */
    public PrismPropertyDefinition createPropertyDefinition(String localName, String localTypeName,
            int minOccurs, int maxOccurs) {
        QName name = new QName(getSchemaNamespace(), localName);
        QName typeName = new QName(getSchemaNamespace(), localTypeName);
        PrismPropertyDefinition propertyDefinition = createPropertyDefinition(name, typeName);
        propertyDefinition.setMinOccurs(minOccurs);
        propertyDefinition.setMaxOccurs(maxOccurs);
        return propertyDefinition;
    }

    public PrismContainerDefinition createContainerDefinition(QName name, QName typeName) {
    	return createContainerDefinition(name, typeName, 1, 1);
    }

    public PrismContainerDefinition createContainerDefinition(QName name, QName typeName,
            int minOccurs, int maxOccurs) {
    	PrismSchema typeSchema = prismContext.getSchemaRegistry().findSchemaByNamespace(typeName.getNamespaceURI());
    	if (typeSchema == null) {
    		throw new IllegalArgumentException("Schema for namespace "+typeName.getNamespaceURI()+" is not known in the prism context");
    	}
    	ComplexTypeDefinition typeDefinition = typeSchema.findComplexTypeDefinition(typeName);
    	if (typeDefinition == null) {
    		throw new IllegalArgumentException("Type "+typeName+" is not known in the schema");
    	}
    	return createContainerDefinition(name, typeDefinition, minOccurs, maxOccurs);
    }

    public PrismContainerDefinition<V> createContainerDefinition(QName name, ComplexTypeDefinition complexTypeDefinition,
            int minOccurs, int maxOccurs) {
    	PrismContainerDefinition<V> def = new PrismContainerDefinition<V>(name, complexTypeDefinition, prismContext);
        def.setMinOccurs(minOccurs);
        def.setMaxOccurs(maxOccurs);
        addDefinition(def);
        return def;
    }

	public PrismContainerValue<V> createValue() {
		return new PrismContainerValue<V>();
	}

    @Override
    public String debugDump(int indent) {
        StringBuilder sb = new StringBuilder();
        DebugUtil.indentDebugDump(sb, indent);
        sb.append(toString());
        if (isRuntimeSchema()) {
            sb.append(" dynamic");
        }
        for (Definition def : getDefinitions()) {
        	sb.append("\n");
        	if (def == this) {
        		// Not perfect loop protection, but works for now
                DebugUtil.indentDebugDump(sb, indent);
                sb.append("<itself>");
        	} else {
        		sb.append(def.debugDump(indent + 1));
        	}
        }
        return sb.toString();
    }

    public boolean isEmpty() {
        return complexTypeDefinition.isEmpty();
    }

    /**
     * Return a human readable name of this class suitable for logs.
     */
    @Override
    protected String getDebugDumpClassName() {
        return "PCD";
    }

    @Override
    public String getDocClassName() {
        return "container";
    }

	@Override
	protected void extendToString(StringBuilder sb) {
		super.extendToString(sb);
		if (isRuntimeSchema) {
			sb.append(",runtime");
		}
	}
}


text:
ModuleLoader.require(["tinymce/text/ExtendingChar"], function(ExtendingChar) {
	module("tinymce.text.ExtendingChar");

	test('isExtendingChar', function() {
		strictEqual(ExtendingChar.isExtendingChar('a'), false);
		strictEqual(ExtendingChar.isExtendingChar('\u0301'), true);
	});
});


text:
class GccAT6 < Formula
  desc "GNU compiler collection"
  homepage "https://gcc.gnu.org"
  url "https://ftp.gnu.org/gnu/gcc/gcc-6.3.0/gcc-6.3.0.tar.bz2"
  mirror "https://ftpmirror.gnu.org/gcc/gcc-6.3.0/gcc-6.3.0.tar.bz2"
  sha256 "f06ae7f3f790fbf0f018f6d40e844451e6bc3b7bc96e128e63b09825c1f8b29f"

  bottle do
    sha256 "1e735a72ac85834927fcac843f30c5166f88dfa910c052caac826843ccec4927" => :sierra
    sha256 "9df78ad5b4c442ec37870fa0aaecbc57cd15a2b826d50be059c3aca5df91a6a7" => :el_capitan
    sha256 "947e8edb596ebfea654991123c8d943a1ac2cf9d05192e6a7a9d8f594d162477" => :yosemite
  end

  # GCC's Go compiler is not currently supported on macOS.
  # See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=46986
  option "with-java", "Build the gcj compiler"
  option "with-all-languages", "Enable all compilers and languages, except Ada"
  option "with-nls", "Build with native language support (localization)"
  option "with-jit", "Build the jit compiler"
  option "without-fortran", "Build without the gfortran compiler"
  # enabling multilib on a host that can't run 64-bit results in build failures
  option "without-multilib", "Build without multilib support" if MacOS.prefer_64_bit?

  depends_on "gmp"
  depends_on "libmpc"
  depends_on "mpfr"
  depends_on "isl"
  depends_on "ecj" if build.with?("java") || build.with?("all-languages")

  fails_with :gcc_4_0

  # GCC bootstraps itself, so it is OK to have an incompatible C++ stdlib
  cxxstdlib_check :skip

  # The bottles are built on systems with the CLT installed, and do not work
  # out of the box on Xcode-only systems due to an incorrect sysroot.
  pour_bottle? do
    reason "The bottle needs the Xcode CLT to be installed."
    satisfy { MacOS::CLT.installed? }
  end

  # Fix for libgccjit.so linkage on Darwin
  # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64089
  # https://github.com/Homebrew/homebrew-core/issues/1872#issuecomment-225625332
  # https://github.com/Homebrew/homebrew-core/issues/1872#issuecomment-225626490
  patch do
    url "https://raw.githubusercontent.com/Homebrew/formula-patches/e9e0ee09389a54cc4c8fe1c24ebca3cd765ed0ba/gcc/6.1.0-jit.patch"
    sha256 "863957f90a934ee8f89707980473769cff47ca0663c3906992da6afb242fb220"
  end

  def install
    # GCC will suffer build errors if forced to use a particular linker.
    ENV.delete "LD"

    if build.with? "all-languages"
      # Everything but Ada, which requires a pre-existing GCC Ada compiler
      # (gnat) to bootstrap. GCC 4.6.0 adds go as a language option, but it is
      # currently only compilable on Linux.
      languages = %w[c c++ objc obj-c++ fortran java jit]
    else
      # C, C++, ObjC compilers are always built
      languages = %w[c c++ objc obj-c++]

      languages << "fortran" if build.with? "fortran"
      languages << "java" if build.with? "java"
      languages << "jit" if build.with? "jit"
    end

    version_suffix = version.to_s.slice(/\d/)

    # Even when suffixes are appended, the info pages conflict when
    # install-info is run so pretend we have an outdated makeinfo
    # to prevent their build.
    ENV["gcc_cv_prog_makeinfo_modern"] = "no"

    osmajor = `uname -r`.chomp
    arch = MacOS.prefer_64_bit? ? "x86_64" : "i686"

    args = [
      "--build=#{arch}-apple-darwin#{osmajor}",
      "--prefix=#{prefix}",
      "--libdir=#{lib}/gcc/#{version_suffix}",
      "--enable-languages=#{languages.join(",")}",
      # Make most executables versioned to avoid conflicts.
      "--program-suffix=-#{version_suffix}",
      "--with-gmp=#{Formula["gmp"].opt_prefix}",
      "--with-mpfr=#{Formula["mpfr"].opt_prefix}",
      "--with-mpc=#{Formula["libmpc"].opt_prefix}",
      "--with-isl=#{Formula["isl"].opt_prefix}",
      "--with-system-zlib",
      "--enable-stage1-checking",
      "--enable-checking=release",
      "--enable-lto",
      # Use 'bootstrap-debug' build configuration to force stripping of object
      # files prior to comparison during bootstrap (broken by Xcode 6.3).
      "--with-build-config=bootstrap-debug",
      "--disable-werror",
      "--with-pkgversion=Homebrew GCC #{pkg_version} #{build.used_options*" "}".strip,
      "--with-bugurl=https://github.com/Homebrew/homebrew-core/issues",
    ]

    # The pre-Mavericks toolchain requires the older DWARF-2 debugging data
    # format to avoid failure during the stage 3 comparison of object files.
    # See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=45248
    args << "--with-dwarf2" if MacOS.version <= :mountain_lion

    args << "--disable-nls" if build.without? "nls"

    if build.with?("java") || build.with?("all-languages")
      args << "--with-ecj-jar=#{Formula["ecj"].opt_share}/java/ecj.jar"
    end

    if build.without?("multilib") || !MacOS.prefer_64_bit?
      args << "--disable-multilib"
    else
      args << "--enable-multilib"
    end

    args << "--enable-host-shared" if build.with?("jit") || build.with?("all-languages")

    # Ensure correct install names when linking against libgcc_s;
    # see discussion in https://github.com/Homebrew/homebrew/pull/34303
    inreplace "libgcc/config/t-slibgcc-darwin", "@shlib_slibdir@", "#{HOMEBREW_PREFIX}/lib/gcc/#{version_suffix}"

    mkdir "build" do
      unless MacOS::CLT.installed?
        # For Xcode-only systems, we need to tell the sysroot path.
        # "native-system-headers" will be appended
        args << "--with-native-system-header-dir=/usr/include"
        args << "--with-sysroot=#{MacOS.sdk_path}"
      end

      system "../configure", *args
      system "make", "bootstrap"
      system "make", "install"
    end

    # Handle conflicts between GCC formulae and avoid interfering
    # with system compilers.
    # Rename man7.
    Dir.glob(man7/"*.7") { |file| add_suffix file, version_suffix }
    # Even when we disable building info pages some are still installed.
    info.rmtree
  end

  def add_suffix(file, suffix)
    dir = File.dirname(file)
    ext = File.extname(file)
    base = File.basename(file, ext)
    File.rename file, "#{dir}/#{base}-#{suffix}#{ext}"
  end

  test do
    (testpath/"hello-c.c").write <<-EOS.undent
      #include <stdio.h>
      int main()
      {
        puts("Hello, world!");
        return 0;
      }
    EOS
    system "#{bin}/gcc-6", "-o", "hello-c", "hello-c.c"
    assert_equal "Hello, world!\n", `./hello-c`

    (testpath/"hello-cc.cc").write <<-EOS.undent
      #include <iostream>
      int main()
      {
        std::cout << "Hello, world!" << std::endl;
        return 0;
      }
    EOS
    system "#{bin}/g++-6", "-o", "hello-cc", "hello-cc.cc"
    assert_equal "Hello, world!\n", `./hello-cc`

    if build.with?("fortran") || build.with?("all-languages")
      fixture = <<-EOS.undent
        integer,parameter::m=10000
        real::a(m), b(m)
        real::fact=0.5

        do concurrent (i=1:m)
          a(i) = a(i) + fact*b(i)
        end do
        print *, "done"
        end
      EOS
      (testpath/"in.f90").write(fixture)
      system "#{bin}/gfortran-6", "-o", "test", "in.f90"
      assert_equal "done", `./test`.strip
    end
  end
end


text:
Scorching Ray

**Source** [_scorching ray_](spells/scorchingRay#_scorching-ray)

Each ray's damage increases to 6d6 points of fire damage. The first ray bypasses fire resistance and immunity.


text:
class ActionController::Base
  alias :ac_flash :flash
  def flash(*args)
    return ac_flash(*args) if args.empty? || args.first.nil? || args.first === true || args.first == :refresh
    case args.first
    when Hash
      args.first.each do |flash_key, name|
        text = (flashdance([controller_name, action_name, name]) || flashdance(name))
        ac_flash[flash_key] = text
      end
    when Symbol
      if args[1] && (args[1].is_a?(String) || args[1].is_a?(Symbol) || args[1].is_a?(Array))
        ac_flash[args[0]] = flashdance(args[1])
      elsif text = flashdance([controller_name, action_name, args[0]]) || text = flashdance([controller_name, action_name])
        ac_flash[args[0]] = text
      else
        ac_flash(*args)
      end
    end
  end
end


text:
typedef struct Auth Auth;
struct Auth {
};

int validtoken(Auth *, char *token);


text:
/**
    File Name:          15.9.5.4-2-n.js
    ECMA Section:       15.9.5.4-1 Date.prototype.getTime
    Description:

    1.  If the this value is not an object whose [[Class]] property is "Date",
        generate a runtime error.
    2.  Return this time value.
    Author:             christine@netscape.com
    Date:               12 november 1997
*/

    var SECTION = "15.9.5.4-2-n";
    var VERSION = "ECMA_1";
    startTest();
    var TITLE   = "Date.prototype.getTime";

    writeHeaderToLog( SECTION + " "+ TITLE);

    var testcases = new Array();

    var MYDATE = new MyDate( TIME_2000 );

    testcases[tc++] = new TestCase( SECTION,
                      "MYDATE.getTime()",
                      "error",
                      MYDATE.getTime() );

function MyDate( value ) {
    this.value = value;
    this.getTime = Date.prototype.getTime;
}
function test() {
    for ( tc=0; tc < testcases.length; tc++ ) {
        testcases[tc].passed = writeTestCaseResult(
                            testcases[tc].expect,
                            testcases[tc].actual,
                            testcases[tc].description +" = "+
                            testcases[tc].actual );

        testcases[tc].reason += ( testcases[tc].passed ) ? "" : "wrong value ";
    }
    stopTest();
    return ( testcases );
}


text:
import httpManager from "../../services/httpManager";
import {Incident} from '../../incident/incident';
import {Attachment} from '../../attachment/attachment';
import {Attribute} from '../../attribute/attribute';
import loginService from "../../services/loginService";
import './view-incident.less';

export class ViewIncident {
    constructor() {
        this.found = false;
        this.error = 'Initializing';
    }

    activate(value) {
        if (value.token) {
            loginService.setToken(value.token);
        }

        // TODO clean up incident manager and start using it.
        httpManager.get(`/sona/v1/incidents/${value.id}`).then((incident) => {
            const attributes = [];
            if (incident.attributes) {
                for (var prop in incident.attributes) {
                    if (incident.attributes.hasOwnProperty(prop)) {
                        attributes.push(new Attribute(prop, incident.attributes[prop]));
                    }
                }
            }

            this.incident = new Incident(incident.id, incident.reporter, incident.state, incident.description, attributes);
            this.found = true;

            httpManager.get(`/sona/v1/incidents/${incident.id}/attachments`).then(data => {
                if (!data) {
                    return;
                }

                data.forEach(attach => {
                    this.incident.addAttachment(new Attachment(attach.filename, attach.time));
                });
            }).catch(err => {
                if (err.status === 404) {
                    return;
                }

                console.log('Unable to get attachments for ', incident.id);
            });
        }).catch(err => {
            if (err.status === 404) {
                this.error = 'Incident not found';
                return;
            }

            if (err.status === 403) {
                this.error = 'Cannot view Incident due to invalid permissions';
                return;
            }

            this.error = 'Unable to view incident at this time';
        });
    }
}


text:
import argparse
import bz2

parser = argparse.ArgumentParser(description='script to convert a Wikidata dump to csv file'
                                             'and change it according to a given properties files')
parser.add_argument('-i', '--input', help='Wikidata dump', required=True)
parser.add_argument('-p', '--properties', help='properties file', required=True)
parser.add_argument('-o', '--out', help='output file name', required=True)
args = parser.parse_args()

# reading properties
properties = []
with open(args.properties) as f:
    for l in f.readlines():
        properties.append(l.strip())

properties = set(properties)

out = open(args.out, "w")
counter = 0
with bz2.BZ2File(args.input) as f:
    for l in f:
        if "/prop/direct/P" not in l:
            continue
        tmp = l.split(' ')
        p = tmp[1][1:-1]
        if p in properties:
            s = tmp[0][1:-1]
            o = ' '.join(tmp[2:])[0:-2]
            if 'XMLSchema' not in o and 'Point' not in o:
                o = o[1:-2]
            out.write(s + '\t' + p + '\t' + o + '\n')

        if counter % 10000 == 0:
            print("%s logged triples" % counter)

        counter += 1


text:
package org.xbib.elasticsearch.plugin.jdbc.pipeline.element;

public interface PipelineElement<E> {

    E get();

    PipelineElement<E> set(E e);

}


text:
package io.grpc.transport.netty;

import static io.netty.util.CharsetUtil.UTF_8;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;

import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.transport.ClientTransport.PingCallback;
import io.grpc.transport.Http2Ping;
import io.grpc.transport.HttpUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2ConnectionAdapter;
import io.netty.handler.codec.http2.Http2ConnectionHandler;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2FrameAdapter;
import io.netty.handler.codec.http2.Http2FrameReader;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.handler.codec.http2.Http2StreamVisitor;

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Nullable;

/**
 * Client-side Netty handler for GRPC processing. All event handlers are executed entirely within
 * the context of the Netty Channel thread.
 */
class NettyClientHandler extends Http2ConnectionHandler {
  private static final Logger logger = Logger.getLogger(NettyClientHandler.class.getName());

  private final Http2Connection.PropertyKey streamKey;
  private final Ticker ticker;
  private final Random random = new Random();
  private WriteQueue clientWriteQueue;
  private int flowControlWindow;
  private Http2Settings initialSettings = new Http2Settings();
  private Throwable connectionError;
  private Http2Ping ping;
  private Status goAwayStatus;
  private ChannelHandlerContext ctx;
  private int nextStreamId;

  public NettyClientHandler(BufferingHttp2ConnectionEncoder encoder, Http2Connection connection,
                            Http2FrameReader frameReader,
                            int flowControlWindow) {
    this(encoder, connection, frameReader, flowControlWindow,
         Ticker.systemTicker());
  }

  @VisibleForTesting
  NettyClientHandler(BufferingHttp2ConnectionEncoder encoder, Http2Connection connection,
      Http2FrameReader frameReader, int flowControlWindow, Ticker ticker) {
    super(new DefaultHttp2ConnectionDecoder(connection, encoder, frameReader,
        new LazyFrameListener()), encoder);
    this.ticker = ticker;
    Preconditions.checkArgument(flowControlWindow > 0, "flowControlWindow must be positive");
    this.flowControlWindow = flowControlWindow;

    initListener();

    streamKey = connection.newKey();

    nextStreamId = connection.local().nextStreamId();
    connection.addListener(new Http2ConnectionAdapter() {
      @Override
      public void onGoAwayReceived(int lastStreamId, long errorCode, ByteBuf debugData) {
        goAwayStatus(statusFromGoAway(errorCode, debugData));
        goingAway();
      }
    });

    // TODO(nmittler): this is a temporary hack as we currently have to send a 2nd SETTINGS
    // frame. Once we upgrade to Netty 4.1.Beta6 we'll be able to pass in the initial SETTINGS
    // to the super class constructor.
    initialSettings.pushEnabled(false);
    initialSettings.initialWindowSize(flowControlWindow);
    initialSettings.maxConcurrentStreams(0);
  }

  @Nullable
  public Throwable connectionError() {
    return connectionError;
  }

  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    this.ctx = ctx;
    // Sends the connection preface if we haven't already.
    super.handlerAdded(ctx);
    sendInitialSettings();
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // Sends connection preface if we haven't already.
    super.channelActive(ctx);
    sendInitialSettings();
  }

  /**
   * Handler for commands sent from the stream.
   */
  @Override
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (msg instanceof CreateStreamCommand) {
      createStream((CreateStreamCommand) msg, promise);
    } else if (msg instanceof SendGrpcFrameCommand) {
      sendGrpcFrame(ctx, (SendGrpcFrameCommand) msg, promise);
    } else if (msg instanceof CancelStreamCommand) {
      cancelStream(ctx, (CancelStreamCommand) msg, promise);
    } else if (msg instanceof RequestMessagesCommand) {
      ((RequestMessagesCommand) msg).requestMessages();
    } else if (msg instanceof SendPingCommand) {
      sendPingFrame(ctx, (SendPingCommand) msg, promise);
    } else {
      throw new AssertionError("Write called for unexpected type: " + msg.getClass().getName());
    }
  }

  void startWriteQueue(Channel channel) {
    clientWriteQueue = new WriteQueue(channel);
  }

  WriteQueue getWriteQueue() {
    return clientWriteQueue;
  }

  /**
   * Returns the given processed bytes back to inbound flow control.
   */
  void returnProcessedBytes(Http2Stream stream, int bytes) {
    try {
      decoder().flowController().consumeBytes(ctx, stream, bytes);
    } catch (Http2Exception e) {
      throw new RuntimeException(e);
    }
  }

  private void initListener() {
    ((LazyFrameListener) decoder().listener()).setHandler(this);
  }

  private void onHeadersRead(int streamId, Http2Headers headers, boolean endStream)
      throws Http2Exception {
    NettyClientStream stream = clientStream(requireHttp2Stream(streamId));
    stream.transportHeadersReceived(headers, endStream);
  }

  /**
   * Handler for an inbound HTTP/2 DATA frame.
   */
  private void onDataRead(int streamId, ByteBuf data, boolean endOfStream) throws Http2Exception {
    NettyClientStream stream = clientStream(requireHttp2Stream(streamId));
    stream.transportDataReceived(data, endOfStream);
  }

  /**
   * Handler for an inbound HTTP/2 RST_STREAM frame, terminating a stream.
   */
  private void onRstStreamRead(int streamId)
      throws Http2Exception {
    // TODO(nmittler): do something with errorCode?
    NettyClientStream stream = clientStream(requireHttp2Stream(streamId));
    stream.transportReportStatus(Status.UNKNOWN, false, new Metadata.Trailers());
  }

  @Override
  public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
    logger.fine("Network channel being closed by the application.");
    super.close(ctx, promise);
  }

  /**
   * Handler for the Channel shutting down.
   */
  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    try {
      logger.fine("Network channel is closed");
      goAwayStatus(goAwayStatus().augmentDescription("Network channel closed"));
      cancelPing();
      // Report status to the application layer for any open streams
      connection().forEachActiveStream(new Http2StreamVisitor() {
        @Override
        public boolean visit(Http2Stream stream) throws Http2Exception {
          clientStream(stream).transportReportStatus(goAwayStatus, false, new Metadata.Trailers());
          return true;
        }
      });
    } finally {
      // Close any open streams
      super.channelInactive(ctx);
    }
  }

  @Override
  protected void onConnectionError(ChannelHandlerContext ctx, Throwable cause,
      Http2Exception http2Ex) {
    logger.log(Level.FINE, "Caught a connection error", cause);

    // Save the error.
    connectionError = cause;
    goAwayStatus(Status.fromThrowable(connectionError));
    cancelPing();

    super.onConnectionError(ctx, cause, http2Ex);
  }

  @Override
  protected void onStreamError(ChannelHandlerContext ctx, Throwable cause,
      Http2Exception.StreamException http2Ex) {
    // Close the stream with a status that contains the cause.
    Http2Stream stream = connection().stream(http2Ex.streamId());
    if (stream != null) {
      clientStream(stream).transportReportStatus(Status.fromThrowable(cause), false,
              new Metadata.Trailers());
    }

    // Delegate to the base class to send a RST_STREAM.
    super.onStreamError(ctx, cause, http2Ex);
  }

  @Override
  protected boolean isGracefulShutdownComplete() {
    // Only allow graceful shutdown to complete after all pending streams have completed.
    return super.isGracefulShutdownComplete()
        && ((BufferingHttp2ConnectionEncoder) encoder()).numBufferedStreams() == 0;
  }

  /**
   * Attempts to create a new stream from the given command. If there are too many active streams,
   * the creation request is queued.
   */
  private void createStream(CreateStreamCommand command, final ChannelPromise promise) {
    final int streamId = getAndIncrementNextStreamId();
    final NettyClientStream stream = command.stream();
    final Http2Headers headers = command.headers();
    // TODO: Send GO_AWAY if streamId overflows
    stream.id(streamId);
    encoder().writeHeaders(ctx, streamId, headers, 0, false, promise)
            .addListener(new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                  // The http2Stream will be null in case a stream buffered in the encoder
                  // was canceled via RST_STREAM.
                  Http2Stream http2Stream = connection().stream(streamId);
                  if (http2Stream != null) {
                    http2Stream.setProperty(streamKey, stream);
                  }
                  // Attach the client stream to the HTTP/2 stream object as user data.
                  stream.setHttp2Stream(http2Stream);
                } else {
                  if (future.cause() instanceof GoAwayClosedStreamException) {
                    GoAwayClosedStreamException e = (GoAwayClosedStreamException) future.cause();
                    goAwayStatus(statusFromGoAway(e.errorCode(), e.debugData()));
                    stream.transportReportStatus(goAwayStatus, false, new Metadata.Trailers());
                  } else {
                    stream.transportReportStatus(Status.fromThrowable(future.cause()), true,
                        new Metadata.Trailers());
                  }
                }
              }
            });
  }

  /**
   * Cancels this stream.
   */
  private void cancelStream(ChannelHandlerContext ctx, CancelStreamCommand cmd,
      ChannelPromise promise) {
    NettyClientStream stream = cmd.stream();
    stream.transportReportStatus(cmd.reason(), true, new Metadata.Trailers());
    encoder().writeRstStream(ctx, stream.id(), Http2Error.CANCEL.code(), promise);
  }

  /**
   * Sends the given GRPC frame for the stream.
   */
  private void sendGrpcFrame(ChannelHandlerContext ctx, SendGrpcFrameCommand cmd,
      ChannelPromise promise) {
    // Call the base class to write the HTTP/2 DATA frame.
    // Note: no need to flush since this is handled by the outbound flow controller.
    encoder().writeData(ctx, cmd.streamId(), cmd.content(), 0, cmd.endStream(), promise);
  }

  /**
   * Sends a PING frame. If a ping operation is already outstanding, the callback in the message is
   * registered to be called when the existing operation completes, and no new frame is sent.
   */
  private void sendPingFrame(ChannelHandlerContext ctx, SendPingCommand msg,
      ChannelPromise promise) {
    PingCallback callback = msg.callback();
    Executor executor = msg.executor();
    if (!ctx.channel().isOpen()) {
      Http2Ping.notifyFailed(callback, executor, getPingFailure());
      return;
    }

    // we only allow one outstanding ping at a time, so just add the callback to
    // any outstanding operation
    if (ping != null) {
      ping.addCallback(callback, executor);
      return;
    }

    // set outstanding operation
    long data = random.nextLong();
    ByteBuf buffer = ctx.alloc().buffer(8);
    buffer.writeLong(data);
    Stopwatch stopwatch = Stopwatch.createStarted(ticker);
    ping = new Http2Ping(data, stopwatch);
    ping.addCallback(callback, executor);
    // and then write the ping
    encoder().writePing(ctx, false, buffer, promise);
    ctx.flush();
    final Http2Ping finalPing = ping;
    promise.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
        if (!future.isSuccess()) {
          finalPing.failed(future.cause());
          if (ping == finalPing) {
            ping = null;
          }
        }
      }
    });
  }

  /**
   * Handler for a GOAWAY being either sent or received. Fails any streams created after the
   * last known stream.
   */
  private void goingAway() {
    final Status goAwayStatus = goAwayStatus();
    final int lastKnownStream = connection().local().lastStreamKnownByPeer();
    try {
      connection().forEachActiveStream(new Http2StreamVisitor() {
        @Override
        public boolean visit(Http2Stream stream) throws Http2Exception {
          if (stream.id() > lastKnownStream) {
            clientStream(stream)
                .transportReportStatus(goAwayStatus, false, new Metadata.Trailers());
            stream.close();
          }
          return true;
        }
      });
    } catch (Http2Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Returns the appropriate status used to represent the cause for GOAWAY.
   */
  private Status goAwayStatus() {
    if (goAwayStatus != null) {
      return goAwayStatus;
    }
    return Status.UNAVAILABLE.withDescription("Connection going away, but for unknown reason");
  }

  private void goAwayStatus(Status status) {
    goAwayStatus = goAwayStatus == null ? status : goAwayStatus;
  }

  private void cancelPing() {
    if (ping != null) {
      ping.failed(getPingFailure());
      ping = null;
    }
  }

  private Throwable getPingFailure() {
    if (connectionError != null) {
      return connectionError;
    } else if (goAwayStatus != null) {
      return goAwayStatus.asException();
    } else {
      return Status.UNAVAILABLE.withDescription("Connection closed").asException();
    }
  }

  private Status statusFromGoAway(long errorCode, ByteBuf debugData) {
    Status status = HttpUtil.Http2Error.statusForCode((int) errorCode);
    if (debugData.isReadable()) {
      // If a debug message was provided, use it.
      String msg = debugData.toString(UTF_8);
      status = status.augmentDescription(msg);
    }
    return status;
  }

  /**
   * Gets the client stream associated to the given HTTP/2 stream object.
   */
  private NettyClientStream clientStream(Http2Stream stream) {
    return stream.getProperty(streamKey);
  }

  private int getAndIncrementNextStreamId() {
    int id = nextStreamId;
    nextStreamId += 2;
    return id;
  }

  private Http2Stream requireHttp2Stream(int streamId) {
    Http2Stream stream = connection().stream(streamId);
    if (stream == null) {
      // This should never happen.
      throw new AssertionError("Stream does not exist: " + streamId);
    }
    return stream;
  }

  /**
   * Sends initial configuration of this endpoint to the remote endpoint.
   */
  private void sendInitialSettings() throws Http2Exception {
    if (!ctx.channel().isActive()) {
      return;
    }
    boolean needToFlush = false;

    // Send the initial settings for this endpoint.
    if (initialSettings != null) {
      needToFlush = true;
      encoder().writeSettings(ctx, initialSettings, ctx.newPromise());
      initialSettings = null;
    }

    // Send the initial connection window if different than the default.
    if (flowControlWindow > 0) {
      needToFlush = true;
      Http2Stream connectionStream = connection().connectionStream();
      int currentSize = connection().local().flowController().windowSize(connectionStream);
      int delta = flowControlWindow - currentSize;
      decoder().flowController().incrementWindowSize(ctx, connectionStream, delta);
      flowControlWindow = -1;
    }

    if (needToFlush) {
      ctx.flush();
    }

  }

  private static class LazyFrameListener extends Http2FrameAdapter {
    private NettyClientHandler handler;

    void setHandler(NettyClientHandler handler) {
      this.handler = handler;
    }

    @Override
    public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
        boolean endOfStream) throws Http2Exception {
      handler.onDataRead(streamId, data, endOfStream);
      return padding;
    }

    @Override
    public void onHeadersRead(ChannelHandlerContext ctx,
        int streamId,
        Http2Headers headers,
        int streamDependency,
        short weight,
        boolean exclusive,
        int padding,
        boolean endStream) throws Http2Exception {
      handler.onHeadersRead(streamId, headers, endStream);
    }

    @Override
    public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode)
        throws Http2Exception {
      handler.onRstStreamRead(streamId);
    }

    @Override public void onPingAckRead(ChannelHandlerContext ctx, ByteBuf data)
        throws Http2Exception {
      Http2Ping p = handler.ping;
      if (p != null) {
        long ackPayload = data.readLong();
        if (p.payload() == ackPayload) {
          p.complete();
          handler.ping = null;
        } else {
          logger.log(Level.WARNING, String.format("Received unexpected ping ack. "
              + "Expecting %d, got %d", p.payload(), ackPayload));
        }
      } else {
        logger.warning("Received unexpected ping ack. No ping outstanding");
      }
    }
  }
}


text:
'use strict';

const lowkie = require('lowkie');
const Schema = lowkie.Schema;
const ObjectId = Schema.ObjectId;
const scheme = {
  name: {
    type: String,
    required: true,
    index: {
      unique: true,
    },
  },
  title: String,
  author: String,
  content: String,
  cron_interval: {
    type: String,
    required: true,
  },
  cron_interval_pretty: String,
  active: {
    type: Boolean,
    default: false,
  },
  container: {
    type: String,
    'default': 'periodicjs.container.default',
  },
  command_line_arguments: String,
  runtime_options: Schema.Types.Mixed,
  cron_properties: Schema.Types.Mixed,
  internal_function: String,
  inline_function: String,
  inline_test: String,
  time_zone: String,
  label: String,
  asset_signature: {
    type: String,
    // required: true
  },
  asset: {
    type: ObjectId,
    ref: 'Asset',
    // required: true
  },
};

module.exports = {
  scheme,
  options: {},
  coreDataOptions: {
    docid: ['_id', 'name',],
    sort: { createdat: -1, },
    search: ['title', 'name', 'asset_signature',],
    population: 'asset',
  },
};


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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.
package com.google.devtools.build.lib.rules.cpp;

import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.HOST;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static com.google.devtools.build.lib.packages.BuildType.LICENSE;
import static com.google.devtools.build.lib.syntax.Type.BOOLEAN;
import static com.google.devtools.build.lib.syntax.Type.STRING;

import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Attribute.LateBoundLabel;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClass.Builder;
import com.google.devtools.build.lib.packages.Target;

/**
 * Rule definition for compiler definition.
 */
public final class CcToolchainRule implements RuleDefinition {

  /**
   * Determines if the given target is a cc_toolchain or one of its subclasses. New subclasses
   * should be added to this method.
   */
  static boolean isCcToolchain(Target target) {
    String ruleClass = ((Rule) target).getRuleClass();
    return ruleClass.endsWith("cc_toolchain");
  }

  private static final LateBoundLabel<BuildConfiguration> LIBC_TOP =
      new LateBoundLabel<BuildConfiguration>(CppConfiguration.class) {
        @Override
        public Label resolve(
            Rule rule, AttributeMap attributes, BuildConfiguration configuration) {
          return configuration.getFragment(CppConfiguration.class).getLibcLabel();
        }
      };

  @Override
  public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
    return builder
        .setUndocumented()
        .requiresConfigurationFragments(CppConfiguration.class)
        .add(attr("output_licenses", LICENSE))
        .add(attr("cpu", STRING).mandatory())
        .add(attr("all_files", LABEL).legacyAllowAnyFileType().cfg(HOST).mandatory())
        .add(attr("compiler_files", LABEL).legacyAllowAnyFileType().cfg(HOST).mandatory())
        .add(attr("strip_files", LABEL).legacyAllowAnyFileType().cfg(HOST).mandatory())
        .add(attr("objcopy_files", LABEL).legacyAllowAnyFileType().cfg(HOST).mandatory())
        .add(attr("linker_files", LABEL).legacyAllowAnyFileType().cfg(HOST).mandatory())
        .add(attr("dwp_files", LABEL).legacyAllowAnyFileType().cfg(HOST).mandatory())
        .add(attr("static_runtime_libs", LABEL_LIST).legacyAllowAnyFileType().mandatory())
        .add(attr("dynamic_runtime_libs", LABEL_LIST).legacyAllowAnyFileType().mandatory())
        .add(attr("module_map", LABEL).legacyAllowAnyFileType().cfg(HOST))
        .add(attr("supports_param_files", BOOLEAN).value(true))
        .add(attr("supports_header_parsing", BOOLEAN).value(false))
        // TODO(bazel-team): Should be using the TARGET configuration.
        .add(attr(":libc_top", LABEL).cfg(HOST).value(LIBC_TOP))
        .build();
  }

  @Override
  public Metadata getMetadata() {
    return RuleDefinition.Metadata.builder()
        .name("cc_toolchain")
        .ancestors(BaseRuleClasses.BaseRule.class)
        .factoryClass(CcToolchain.class)
        .build();
  }
}


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

namespace LeanpubApi\StartPreview;

use LeanpubApi\Common\LeanpubApiClient;

final class StartPreviewUsingLeanpubApi implements StartPreview
{
    private LeanpubApiClient $leanpubApiClient;

    public function __construct(LeanpubApiClient $leanpubApiClient)
    {
        $this->leanpubApiClient = $leanpubApiClient;
    }

    public function startPreview(): void
    {
        $responseData = $this->leanpubApiClient->postFormData('/preview.json', []);

        if (!isset($responseData['success']) || $responseData['success'] !== true) {
            throw CouldNotStartPreview::unknownReason();
        }
    }

    public function startPreviewOfSubset(): void
    {
        $responseData = $this->leanpubApiClient->postFormData('/preview/subset.json', []);

        if (!isset($responseData['success']) || $responseData['success'] !== true) {
            throw CouldNotStartPreview::unknownReason();
        }
    }
}


text:
<?PHP

#################################################
##                                             ##
##              Gold Classifieds               ##
##         http://www.abscripts.com/           ##
##         e-mail: mail@abscripts.com          ##
##                                             ##
##                                             ##
##               version:  4.0                 ##
##            copyright (c) 2011               ##
##                                             ##
##  This script is not freeware nor shareware  ##
##    Please do no distribute it by any way    ##
##                                             ##
#################################################

include('./common.php');
check_admin('database_tools');

switch ($_GET[action]) {
case 'database_home'			: database_home();
case 'database_backup'			: database_backup($_GET);
case 'database_restore'			: database_restore($_GET);
case 'database_optimize'		: database_optimize($_GET);
case 'uninstall'				: uninstall(0);
}
switch ($_POST[action]) {
case 'uninstall'				: uninstall(1);
case 'database_command'			: database_command($_POST[command]);
}

#################################################################################
#################################################################################
#################################################################################

function database_home() {
global $s;
ih();
echo $s[info];
echo page_title('Database Tools');
?>
<form method="get" action="database_tools.php"><?PHP echo check_field_create('admin') ?>
<input type="hidden" name="action" value="database_backup">

Backup Database To A File

Name of a backup file to create in your data directory: <input class="field10" name="backupfile" value="backup.db" style="width:200px">

<input type="submit" name="A1" value="Submit" class="button10">

Note: To restore the database from this backup use PHPMyAdmin. You also can use it to create the backup. It's a free tool for managing a mysql database.

</form>

<form method="get" action="database_tools.php"><?PHP echo check_field_create('admin') ?>
<input type="hidden" name="action" value="database_optimize">

Database Optimization

Optimize all tables

You should run this function from time to time.
Optimized database works faster.

<input type="submit" name="A1" value="Submit" class="button10">

</form>

<form method="post" action="database_tools.php"><?PHP echo check_field_create('admin') ?>
<input type="hidden" name="action" value="database_command">

Run A Mysql Command

Enter a mysql command to run.

<textarea class="field10" name="command" rows="15" style="width:550px"></textarea>

<input type="submit" name="A1" value="Submit" class="button10">

</form>
<?PHP
ift();
}

#########################################################################

function database_backup($data) {
global $s;
set_magic_quotes_runtime(0);
set_time_limit(1000);
$line_separator = "\n";
$tables = mysql_list_tables($s[dbname]);
$num_tables = mysql_numrows($tables);
if ($num_tables == 0) $backup .= "# No tables found";
else
{ $i = 0;
  $backup .= "# Database name: $s[dbname]\n";
  while ($i < $num_tables)
  { $table = mysql_tablename($tables,$i);
    $i++;
    if (!ereg("^$s[pr]",$table)) continue;
    $backup .= "\n#\n# Structure of table '$table'\n#\n\n";
    $backup .= get_table_def($table,$line_separator,0).";\n\n";
    $backup .= "#\n# Data in table '$table'\n#\n\n";
    $backup .= get_table_content($table);
    increase_print_time(2,1);
  }
}
$write = fopen("$s[phppath]/data/$data[backupfile]",'w');
fwrite($write,$backup);
chmod("$s[phppath]/data/$data[backupfile]",0666);
increase_print_time(2,'end');
ih();
echo info_line('Finished!');
echo 'Your mysql database has been backed up to file '.$data[backupfile].' in your "data" directory.
It\'s recommended to check this file. If this file is empty or is missing, you don\'t have the right to backup a database on this server. In this case you have to use phpmyadmin.
';
ift();
}

#########################################################################

function get_table_def($table,$line_separator,$drop) {
global $s;
if ($drop) $schema_create .= "DROP TABLE IF EXISTS $table;$line_separator";
$schema_create .= "CREATE TABLE $table ($line_separator";
$q = mysql_query("SHOW FIELDS FROM $table");
while ($row = mysql_fetch_assoc($q))
{ $schema_create .= "   $row[Field] $row[Type]";
  if (!empty($row["Default"])) $schema_create .= " DEFAULT '$row[Default]'";
  if ($row["Null"] != "YES") $schema_create .= " NOT NULL";
  if ($row["Extra"] != "") $schema_create .= " $row[Extra]";
  $schema_create .= ",$line_separator";
}
$schema_create = ereg_replace(",".$line_separator."$","",$schema_create);
$q = mysql_query("SHOW KEYS FROM $table");
while ($row = mysql_fetch_assoc($q))
{ $kname=$row['Key_name'];
  if (($kname != "PRIMARY") && ($row['Non_unique'] == 0)) $kname="UNIQUE|$kname";
  if ($row[Index_type]!='BTREE') $kname="FULLTEXT|$kname";
  if(!is_array($index[$kname])) $index[$kname] = array();
  $index[$kname][] = $row['Column_name'];
}
while(list($x,$columns) = each($index))
{ $schema_create .= ",$line_separator";
  if($x == "PRIMARY") $schema_create .= "   PRIMARY KEY (" . implode($columns, ", ") . ")";
  elseif (substr($x,0,6) == 'UNIQUE') $schema_create .= "   UNIQUE ".substr($x,7)." (" . implode($columns, ", ") . ")";
  elseif (substr($x,0,8) == 'FULLTEXT') $schema_create .= "   FULLTEXT KEY  (" . implode($columns, ", ") . ")";
  else $schema_create .= "   KEY $x (" . implode($columns, ", ") . ")";
}
$schema_create .= "$line_separator)";
return (stripslashes($schema_create));
}

#########################################################################

function get_table_content($table) {
$q = mysql_query("SELECT * FROM $table");
while ($row = mysql_fetch_row($q))
{ set_time_limit(60);
  $schema_insert = "INSERT INTO $table VALUES(";
  for ($j=0; $j<mysql_num_fields($q);$j++)
  { if (!isset($row[$j])) $schema_insert .= " NULL,";
    elseif ($row[$j] != "") $schema_insert .= " '".addslashes($row[$j])."',";
    else $schema_insert .= " '',";
  }
  $schema_insert = ereg_replace(",$", "", $schema_insert);
  $schema_insert .= ")";
  $backup .= trim($schema_insert).";\n";
}
return $backup;
}

#################################################################################

function database_optimize() {
global $s;
$q = mysql_list_tables($s[dbname]);
while ($table = mysql_fetch_row($q))
{ if (eregi("^$s[pr].*",$table[0])) dq("optimize table $table[0]",1); }
$s[info] = info_line('All tables used by Gold Classifieds have been optimized');
database_home();
}

#################################################################################

function database_command($command) {
global $s;
$command = stripslashes($command);
$q = dq($command,1);
$s[info] = info_line('Your command has been run.
If your database returned a result, you can see it below this line',$q);
database_home();
}

#################################################################################
#################################################################################
#################################################################################

function uninstall($sure) {
global $s;
ih();
if (!is_array(file($s[phppath].'/data/uninstall')))
{ echo info_line('Unistallation is disabled for security reasons. To enable it upload file "uninstall" which can be found in folder "do_not_upload/tools" to your data directory.');
  ift();
}
if (!$sure)
{ echo info_line('This function deletes all tables with names which begin to "'.$s[pr].'"
(it\'s prefix of tables which are used by Gold Classifieds).
All data will be lost. This can\'t be undone.

Are you sure?').
  '<form action="database_tools.php" method="post">'.check_field_create('admin').'
  <input type="hidden" name="action" value="uninstall">
  <input type="submit" name="x" value="Yes, I\'m sure" class="button10"></form>
  Once it deletes all the tables, you will not be able to use most functions from the menu on the left. If you will want to use the script furthermore, you will need to install it again.';
  ift();
}
$q = mysql_list_tables($s[dbname]);
while ($table = mysql_fetch_row($q))
{ if (eregi("^$s[pr].*",$table[0]))
  { dq("drop table $table[0]",1);
    $x++;
  }
}
echo info_line('Total of '.$x.' tables have been deleted','If you want to use the script furthermore, you will need to install it again.');
ift();
}

#################################################################################
#################################################################################
#################################################################################

?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Criterion;
using PholioVisualisation.PholioObjects;

namespace PholioVisualisation.DataAccess.Repositories
{
    public interface IDatabaseLogRepository
    {
        IList<DatabaseLog> GetDatabaseLogs();
        DateTime GetPholioBackUpTimestamp();
    }

    public class DatabaseLogRepository : RepositoryBase, IDatabaseLogRepository
    {
        public DatabaseLogRepository(ISessionFactory sessionFactory) : base(sessionFactory)
        {
        }

        public DatabaseLogRepository() : this(NHibernateSessionFactory.GetSession())
        {
        }

        public IList<DatabaseLog> GetDatabaseLogs()
        {
            return CurrentSession.QueryOver<DatabaseLog>()
                .List();
        }

        public DateTime GetPholioBackUpTimestamp()
        {
            return GetDatabaseLogs()
                .First(x => x.Event.ToLower().StartsWith("backed up"))
                .Timestamp;
        }
    }
}


text:
layout: page
title: Contact
---

If you are having any problems, any questions or suggestions, feel free to  [tweet at me](https://twitter.com/intent/tweet?text=%40paululele), or [file a GitHub issue](https://github.com/lenpaul/lagrange/issues/new)


text:
using namespace std;

/// <summary>
/// The main logic of the program.
/// </summary>
class Loop
{
public:
	Loop();
	~Loop();

	/// <summary>
	/// The main loop of the console.
	/// </summary>
	void MainLoop();

	/// <summary>
	/// Some startup logic.
	/// </summary>
	void Startup();

private:
	/// <summary>
	/// Adds all of the known commands at startup.
	/// </summary>
	void AddAllCommands();

	void ProtectProcess();

	/// <summary>
	/// The current or last parsed command.
	/// </summary>
	ParsedCommand* parsed;
};


text:
MyModule = function() {
  console.log('Inside MyModule constructor');
  this.init_();
};

MyModule.prototype.init_ = function() {
  console.log('Init MyModule');
};

module.exports = MyModule;


text:
package org.ii.attr;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Created by bhill on 11/6/15.
 * <ATTRIBUTE>
 * <ATTR_TYPE>DOB</ATTR_TYPE>
 * <ATTR_VALUE>19601221</ATTR_VALUE>
 * <ATTR_LARGE_DATA></ATTR_LARGE_DATA>
 * <LOAD_ACTION></LOAD_ACTION> A Add. C Change. D Soft delete. F Hard delete.
 * </ATTRIBUTE>
 */
@XmlRootElement(name = "ATTRIBUTE")
@XmlType(propOrder = {"type", "value", "largeData", "loadAction"})
public class Attribute {
    public enum LOAD_ACTION_ENUM {A, C, D, F}

    private String type;
    private String value;
    private String largeData; // clobs/blobs
    private LOAD_ACTION_ENUM loadAction;

    public Attribute() {

    }

    public Attribute(String type, String value) {
        this.loadAction = LOAD_ACTION_ENUM.A;
        this.type = type;
        this.value = value;
    }

    @XmlElement(name = "ATTR_TYPE")
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @XmlElement(name = "ATTR_VALUE")
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @XmlElement(name = "ATTR_LARGE_DATA")
    public String getLargeData() {
        return largeData;
    }

    public void setLargeData(String largeData) {
        this.largeData = largeData;
    }

    @XmlElement(name = "LOAD_ACTION")
    public LOAD_ACTION_ENUM getLoadAction() {
        return loadAction;
    }

    public void setLoadAction(LOAD_ACTION_ENUM loadAction) {
        this.loadAction = loadAction;
    }

    public String toString() {
        return type + "=" + value;
    }
}


text:
package app.hanks.com.conquer.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import app.hanks.com.conquer.R;
import app.hanks.com.conquer.util.PhotoUtil;
import app.hanks.com.conquer.util.SDUtil;

/**
 * 说明:主要用于选择文件操作
 */

public class SelectPicActivity extends Activity implements OnClickListener {

	/***
	 * 使用照相机拍照获取图片
	 */
	public static final int SELECT_PIC_BY_TACK_PHOTO = 1;
	/***
	 * 使用相册中的图片
	 */
	public static final int SELECT_PIC_BY_PICK_PHOTO = 2;

	/***
	 * 从Intent获取图片路径的KEY
	 */
	public static final String KEY_PHOTO_PATH = "photo_path";

	private static final String TAG = "SelectPicActivity";
	private static final int RESULT_CORD = RESULT_OK;

	private LinearLayout dialogLayout;
	private Button takePhotoBtn, pickPhotoBtn, cancelBtn;

	/** 获取到的图片路径 */
	private String picPath;

	private Intent lastIntent;

	private Uri photoUri;
	private String filePath;
	private boolean isShuoShuo;
	private int cutW;
	private int cutH;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_pic_layout);
		isShuoShuo = getIntent().getBooleanExtra("noCut", true);
		cutW = getIntent().getIntExtra("cutW", 200);
		cutH = getIntent().getIntExtra("cutH", 200);
		initView();
	}

	/**
	 * 初始化加载View
	 */
	private void initView() {
		dialogLayout = (LinearLayout) findViewById(R.id.dialog_layout);
		dialogLayout.setOnClickListener(this);
		takePhotoBtn = (Button) findViewById(R.id.btn_take_photo);
		takePhotoBtn.setOnClickListener(this);
		pickPhotoBtn = (Button) findViewById(R.id.btn_pick_photo);
		pickPhotoBtn.setOnClickListener(this);
		cancelBtn = (Button) findViewById(R.id.btn_cancel);
		cancelBtn.setOnClickListener(this);
		lastIntent = getIntent();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.dialog_layout:
				finish();
				break;
			case R.id.btn_take_photo:
				takePhoto();
				break;
			case R.id.btn_pick_photo:
				pickPhoto();
				break;
			default:
				finish();
				break;
		}
	}

	/**
	 * 拍照获取图片
	 */
	private void takePhoto() {
		// 执行拍照前,应该先判断SD卡是否存在
		String SDState = Environment.getExternalStorageState();
		if (SDState.equals(Environment.MEDIA_MOUNTED)) {

			File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 原图
			File file = new File(dir, new SimpleDateFormat("yyMMddHHmmss").format(new Date()));
			filePath = file.getAbsolutePath();
			Uri imageUri = Uri.fromFile(file);

			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			startActivityForResult(intent, 1);

		} else {
			Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show();
		}
	}

	/***
	 * 从相册中取图片
	 */
	private void pickPhoto() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, 2);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		finish();
		return super.onTouchEvent(event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
			case 1:// 相机
				if (resultCode == RESULT_OK) {
					if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
						Toast.makeText(this, "SD不可用", Toast.LENGTH_SHORT).show();
						return;
					}
					File file = new File(filePath);
					if (isShuoShuo) {
						Intent i = new Intent();
						i.putExtra(KEY_PHOTO_PATH, filePath);
						setResult(RESULT_CORD, i);
						finish();
					} else startImageAction(Uri.fromFile(file), cutW, cutH, 3, true);
				} else {
					finish();
					return;
				}
				break;
			case 2:// 相册
				if (data == null || data.getData() ==null) {
					finish();
					return;
				}
				Uri uri = data.getData();
				if (isShuoShuo) {
					String[] pojo = { MediaStore.Images.Media.DATA };
					Cursor cursor = getContentResolver().query(uri, pojo, null, null, null);
					String path = "";
					if (cursor != null) {
						int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
						cursor.moveToFirst();
						path = cursor.getString(columnIndex);
						cursor.close();
					}
					Intent i = new Intent();
					i.putExtra(KEY_PHOTO_PATH, path);
					setResult(RESULT_CORD, i);
					finish();
				} else startImageAction(uri, cutW, cutH, 3, true);
				break;
			case 3:
				saveCropAvator(data);
			default:
				break;
		}

	}

	private void startImageAction(Uri uri, int outputX, int outputY, int requestCode, boolean isCrop) {
		Intent intent = null;
		if (isCrop) {
			intent = new Intent("com.android.camera.action.CROP");
		} else {
			intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		}

//	Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
//	intent.setType("image/*");
//	intent.putExtra("crop", "true");
//	intent.putExtra("aspectX", 2);
//	intent.putExtra("aspectY", 1);
//	intent.putExtra("outputX", 600);
//	intent.putExtra("outputY", 300);
//	intent.putExtra("scale", true);
//	intent.putExtra("return-data", false);
//	intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//	intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//	intent.putExtra("noFaceDetection", true); // no face detection
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", outputX);
		intent.putExtra("aspectY", outputY);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		intent.putExtra("return-data", true);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		startActivityForResult(intent, requestCode);
	}

	private void saveCropAvator(Intent data) {
		if (data != null) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap bitmap = extras.getParcelable("data");
				if (bitmap != null) {
					String filename = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
					PhotoUtil.saveBitmap(SDUtil.getProjectDir(), filename, bitmap, true);
					data.putExtra(KEY_PHOTO_PATH, SDUtil.getProjectDir() + "/" + filename);
					setResult(RESULT_CORD, data);
					PhotoUtil.recycle(bitmap);
				}
			}
		}
		this.finish();
	}
}