text:
<?php

/**
 * Provides support for session storage using a PDO database abstraction layer.
 *
 * Required parameters:
 *
 * # db_table - [none] - The database table in which session data will be stored.
 *
 * Optional parameters:
 *
 * # database     - [default]   - The database connection to use (see databases.yml).
 * # db_id_col    - [sess_id]   - The database column in which the session id will be stored.
 * # db_data_col  - [sess_data] - The database column in which the session data will be stored.
 * # db_time_col  - [sess_time] - The database column in which the session timestamp will be stored.
 * # session_name - [symfony]   - The name of the session.
 *
 * @package    symfony
 * @subpackage storage
 * @author     Mathew Toth <developer@poetryleague.com>
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author     Sean Kerr <sean@code-box.org>
 * @version    SVN: $Id: sfPDOSessionStorage.class.php 7791 2008-03-09 21:57:09Z fabien $
 */
class sfPDOSessionStorage extends sfSessionStorage
{
  /**
   * PDO connection
   * @var Connection
   */
  protected $db;

  /**
   * Initializes this Storage instance.
   *
   * @param sfContext A sfContext instance
   * @param array     An associative array of initialization parameters
   *
   * @return boolean true, if initialization completes successfully, otherwise false
   *
   * @throws InitializationException If an error occurs while initializing this Storage
   */
  public function initialize($context, $parameters = null)
  {
    // disable auto_start
    $parameters['auto_start'] = false;

    // initialize the parent
    parent::initialize($context, $parameters);

    if (!$this->getParameterHolder()->has('db_table'))
    {
      // missing required 'db_table' parameter
      $error = 'Factory configuration file is missing required "db_table" parameter for the Storage category';

      throw new sfInitializationException($error);
    }

    // use this object as the session handler
    session_set_save_handler(array($this, 'sessionOpen'),
                             array($this, 'sessionClose'),
                             array($this, 'sessionRead'),
                             array($this, 'sessionWrite'),
                             array($this, 'sessionDestroy'),
                             array($this, 'sessionGC'));

    // start our session
    session_start();
  }

  /**
  * Closes a session.
  *
  * @return boolean true, if the session was closed, otherwise false
  */
  public function sessionClose()
  {
    // do nothing
    return true;
  }

  /**
   * Destroys a session.
   *
   * @param string A session ID
   *
   * @return boolean true, if the session was destroyed, otherwise an exception is thrown
   *
   * @throws DatabaseException If the session cannot be destroyed
   */
  public function sessionDestroy($id)
  {
    // get table/column
    $db_table  = $this->getParameterHolder()->get('db_table');
    $db_id_col = $this->getParameterHolder()->get('db_id_col', 'sess_id');

    // delete the record associated with this id
    $sql = 'DELETE FROM '.$db_table.' WHERE '.$db_id_col.'= ?';

    try
    {
      $stmt = $this->db->prepare($sql);
      $stmt->bindParam(1, $id, PDO::PARAM_STR); // setString(1, $id);
      $stmt->execute();
    }
    catch (PDOException $e)
    {
      $error = sprintf('PDOException was thrown when trying to manipulate session data. Message: %s', $e->getMessage());

      throw new sfDatabaseException($error);
    }
  }

  /**
   * Cleans up old sessions.
   *
   * @param int The lifetime of a session
   *
   * @return boolean true, if old sessions have been cleaned, otherwise an exception is thrown
   *
   * @throws DatabaseException If any old sessions cannot be cleaned
   */
  public function sessionGC($lifetime)
  {
    // determine deletable session time
    $time = time() - $lifetime;

    // get table/column
    $db_table    = $this->getParameterHolder()->get('db_table');
    $db_time_col = $this->getParameterHolder()->get('db_time_col', 'sess_time');

    // delete the record associated with this id
    $sql = 'DELETE FROM '.$db_table.' WHERE '.$db_time_col.' < '.$time;

    try
    {
      $this->db->query($sql);
      return true;
    }
    catch (PDOException $e)
    {
      $error = sprintf('PDOException was thrown when trying to manipulate session data. Message: %s', $e->getMessage());

      throw new sfDatabaseException($error);
    }
  }

  /**
   * Opens a session.
   *
   * @param string
   * @param string
   *
   * @return boolean true, if the session was opened, otherwise an exception is thrown
   *
   * @throws DatabaseException If a connection with the database does not exist or cannot be created
   */
  public function sessionOpen($path, $name)
  {
    // what database are we using?
    $database = $this->getParameterHolder()->get('database', 'default');

    $this->db = $this->getContext()->getDatabaseConnection($database);
    if ($this->db == null || !$this->db instanceof PDO)
    {
      $error = 'PDO dabatase connection doesn\'t exist. Unable to open session.';

      throw new sfDatabaseException($error);
    }

    return true;
  }

  /**
   * Reads a session.
   *
   * @param string A session ID
   *
   * @return boolean true, if the session was read, otherwise an exception is thrown
   *
   * @throws DatabaseException If the session cannot be read
   */
  public function sessionRead($id)
  {
    // get table/columns
    $db_table    = $this->getParameterHolder()->get('db_table');
    $db_data_col = $this->getParameterHolder()->get('db_data_col', 'sess_data');
    $db_id_col   = $this->getParameterHolder()->get('db_id_col', 'sess_id');
    $db_time_col = $this->getParameterHolder()->get('db_time_col', 'sess_time');

    try
    {
      $sql = 'SELECT '.$db_data_col.' FROM '.$db_table.' WHERE '.$db_id_col.'=?';

      $stmt = $this->db->prepare($sql);
      $stmt->bindParam(1, $id, PDO::PARAM_STR, 255);

      $stmt->execute();
      if ($data = $stmt->fetchColumn())
      {
        return $data;
      }
      else
      {
        // session does not exist, create it
        $sql = 'INSERT INTO '.$db_table.'('.$db_id_col.', '.$db_data_col.', '.$db_time_col.') VALUES (?, ?, ?)';

        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(1, $id, PDO::PARAM_STR); // setString(1, $id);
        $stmt->bindValue(2, '', PDO::PARAM_STR); // setString(2, '');
        $stmt->bindValue(3, time(), PDO::PARAM_INT); // setInt(3, time());
        $stmt->execute();

        return '';
      }
    }
    catch (PDOException $e)
    {
      $error = sprintf('PDOException was thrown when trying to manipulate session data. Message: %s', $e->getMessage());

      throw new sfDatabaseException($error);
    }
  }

  /**
   * Writes session data.
   *
   * @param string A session ID
   * @param string A serialized chunk of session data
   *
   * @return boolean true, if the session was written, otherwise an exception is thrown
   *
   * @throws DatabaseException If the session data cannot be written
   */
  public function sessionWrite($id, $data)
  {
    // get table/column
    $db_table    = $this->getParameterHolder()->get('db_table');
    $db_data_col = $this->getParameterHolder()->get('db_data_col', 'sess_data');
    $db_id_col   = $this->getParameterHolder()->get('db_id_col', 'sess_id');
    $db_time_col = $this->getParameterHolder()->get('db_time_col', 'sess_time');

    $sql = 'UPDATE '.$db_table.' SET '.$db_data_col.' = ?, '.$db_time_col.' = '.time().' WHERE '.$db_id_col.'= ?';

    try
    {
      $stmt = $this->db->prepare($sql);
      $stmt->bindParam(1, $data, PDO::PARAM_STR); // setString(1, $data);
      $stmt->bindParam(2, $id, PDO::PARAM_STR); // setString(2, $id);
      $stmt->execute();
      return true;
    }

    catch (PDOException $e)
    {
      $error = sprintf('PDOException was thrown when trying to manipulate session data. Message: %s', $e->getMessage());

      throw new sfDatabaseException($error);
    }

    return false;
  }

  /**
   * Executes the shutdown procedure.
   *
   */
  public function shutdown()
  {
  }
}


text:
require_dependency "renalware/patients"

module Renalware
  module Patients
    class WorryPolicy < BasePolicy
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.boot.diagnostics.analyzer;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.Collections;
import java.util.List;

import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
import org.springframework.boot.diagnostics.FailureAnalysis;
import org.springframework.util.ClassUtils;

/**
 * An {@link AbstractFailureAnalyzer} that analyzes {@link NoSuchMethodError
 * NoSuchMethodErrors}.
 *
 * @author Andy Wilkinson
 */
class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer<NoSuchMethodError> {

	@Override
	protected FailureAnalysis analyze(Throwable rootFailure, NoSuchMethodError cause) {
		String className = extractClassName(cause);
		if (className == null) {
			return null;
		}
		List<URL> candidates = findCandidates(className);
		if (candidates == null) {
			return null;
		}
		URL actual = getActual(className);
		if (actual == null) {
			return null;
		}
		String description = getDescription(cause, className, candidates, actual);
		return new FailureAnalysis(description,
				"Correct the classpath of your application so that it contains a single,"
						+ " compatible version of " + className,
				cause);
	}

	private String extractClassName(NoSuchMethodError cause) {
		int descriptorIndex = cause.getMessage().indexOf('(');
		if (descriptorIndex == -1) {
			return null;
		}
		String classAndMethodName = cause.getMessage().substring(0, descriptorIndex);
		int methodNameIndex = classAndMethodName.lastIndexOf('.');
		if (methodNameIndex == -1) {
			return null;
		}
		return classAndMethodName.substring(0, methodNameIndex);
	}

	private List<URL> findCandidates(String className) {
		try {
			return Collections.list(NoSuchMethodFailureAnalyzer.class.getClassLoader()
					.getResources(ClassUtils.convertClassNameToResourcePath(className)
							+ ".class"));
		}
		catch (Throwable ex) {
			return null;
		}
	}

	private URL getActual(String className) {
		try {
			return getClass().getClassLoader().loadClass(className).getProtectionDomain()
					.getCodeSource().getLocation();
		}
		catch (Throwable ex) {
			return null;
		}
	}

	private String getDescription(NoSuchMethodError cause, String className,
			List<URL> candidates, URL actual) {
		StringWriter description = new StringWriter();
		PrintWriter writer = new PrintWriter(description);
		writer.println("An attempt was made to call a method that does not"
				+ " exist. The attempt was made from the following location:");
		writer.println();
		writer.print("    ");
		writer.println(cause.getStackTrace()[0]);
		writer.println();
		writer.println("The following method did not exist:");
		writer.println();
		writer.print("    ");
		writer.println(cause.getMessage());
		writer.println();
		writer.println("The method's class, " + className
				+ ", is available from the following locations:");
		writer.println();
		for (URL candidate : candidates) {
			writer.print("    ");
			writer.println(candidate);
		}
		writer.println();
		writer.println("It was loaded from the following location:");
		writer.println();
		writer.print("    ");
		writer.println(actual);
		return description.toString();
	}

}


text:
package com.beecavegames.videopoker.data;

import java.util.List;

import com.beecavegames.poker.Description;
import com.beecavegames.poker.PokerCard;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public class BestMatch {

	public int multiplier;
	public VideoPokerPaytableEntry pte;
	public Description description;
	public List<PokerCard> hand;

	public boolean isBetterThan(BestMatch best) {
		return multiplier > best.multiplier || (multiplier == best.multiplier && pte.getId() < best.pte.getId());
	}
}


text:
<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>
	<groupId>com.github.codegerm</groupId>
	<artifactId>org.cg.spark-databroker</artifactId>
	<version>1.0.1-SNAPSHOT</version>
	<name>${project.groupId}:${project.artifactId}</name>
	<description>All kinds of data brokers implemented using spark, e.g. sliding window streaming data broker.</description>
	<url>https://github.com/CodeGerm/spark-databroker</url>
	<organization>
		<name>CodeGerm</name>
		<url>https://github.com/CodeGerm</url>
	</organization>
	<scm>
		<url>https://github.com/CodeGerm/spark-databroker</url>
		<connection>scm:git:git@github.com:CodeGerm/spark-databroker.git</connection>
		<developerConnection>scm:git:git@github.com:CodeGerm/spark-databroker.git</developerConnection>
	  <tag>HEAD</tag>
  </scm>
	<licenses>
		<license>
			<name>The Apache License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
		</license>
	</licenses>
	<developers>
		<developer>
			<name>Yanlin Wang</name>
			<email>wangyanlin@gmail.com</email>
			<organization>CodeGerm</organization>
			<organizationUrl>https://github.com/CodeGerm</organizationUrl>
		</developer>
	</developers>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
		<encoding>UTF-8</encoding>
		<scala.version>2.10.4</scala.version>
		<scala.version>2.10.4</scala.version>
		<scala.binary.version>2.10</scala.binary.version>
		<spark.version>1.5.2</spark.version>
		<spark.jobserver.version>0.6.1</spark.jobserver.version>
		<avro.version>1.7.7</avro.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.scala-lang</groupId>
			<artifactId>scala-library</artifactId>
			<version>${scala.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.6</version>
		</dependency>
		<dependency>
			<groupId>com.github.codegerm</groupId>
			<artifactId>spark-job-server-client</artifactId>
			<version>1.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.spark</groupId>
			<artifactId>spark-sql_2.10</artifactId>
			<version>${spark.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.spark</groupId>
			<artifactId>spark-core_2.10</artifactId>
			<version>${spark.version}</version>
			<scope>provided</scope>
			<exclusions>
				<exclusion>
					<groupId>org.xerial.snappy</groupId>
					<artifactId>snappy-java</artifactId>
				</exclusion>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
				<exclusion>
					<artifactId>slf4j-log4j12</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.spark</groupId>
			<artifactId>spark-streaming_2.10</artifactId>
			<version>${spark.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.spark</groupId>
			<artifactId>spark-streaming-kafka_2.10</artifactId>
			<version>${spark.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.kafka</groupId>
			<artifactId>kafka_2.10</artifactId>
			<version>0.8.2.1</version>
			<exclusions>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>3.4.6</version>
			<scope>provided</scope>
			<exclusions>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
				<exclusion>
					<artifactId>slf4j-log4j12</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.github.codegerm</groupId>
			<artifactId>org.cg.monadic-lib</artifactId>
			<version>1.0.0</version>
		</dependency>
		<dependency>
			<groupId>com.databricks</groupId>
			<artifactId>spark-csv_2.10</artifactId>
			<version>1.2.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.spark</groupId>
			<artifactId>spark-yarn_2.10</artifactId>
			<version>${spark.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>spark.jobserver</groupId>
			<artifactId>job-server-api_2.10</artifactId>
			<version>${spark.jobserver.version}</version>
		</dependency>
		<dependency>
			<groupId>spark.jobserver</groupId>
			<artifactId>job-server-extras_2.10</artifactId>
			<version>${spark.jobserver.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>akka-app_2.10</artifactId>
					<groupId>spark.jobserver</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.typesafe.akka</groupId>
			<artifactId>akka-cluster_2.10</artifactId>
			<version>2.3.11</version>
		</dependency>
		<dependency>
			<groupId>com.typesafe.akka</groupId>
			<artifactId>akka-contrib_2.10</artifactId>
			<version>2.3.11</version>
		</dependency>
		<dependency>
			<groupId>org.apache.avro</groupId>
			<artifactId>avro</artifactId>
			<version>1.7.7</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.twitter</groupId>
			<artifactId>bijection-avro_2.10</artifactId>
			<version>0.6.3</version>
		</dependency>
		<dependency>
			<groupId>org.twitter4j</groupId>
			<artifactId>twitter4j-stream</artifactId>
			<version>4.0.2</version>
		</dependency>
	</dependencies>

	<build>
		<!-- <sourceDirectory>src/main</sourceDirectory> <testSourceDirectory>src/test</testSourceDirectory> -->
		<plugins>
			<plugin>
				<groupId>org.scala-tools</groupId>
				<artifactId>maven-scala-plugin</artifactId>
				<executions>
					<execution>
						<id>compile</id>
						<goals>
							<goal>compile</goal>
						</goals>
						<phase>compile</phase>
					</execution>

					<execution>
						<id>test-compile</id>
						<goals>
							<goal>testCompile</goal>
						</goals>
						<phase>test-compile</phase>
					</execution>

					<execution>
						<phase>process-resources</phase>
						<goals>
							<goal>compile</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<!-- see http://davidb.github.com/scala-maven-plugin -->
				<groupId>net.alchim31.maven</groupId>
				<artifactId>scala-maven-plugin</artifactId>
				<version>3.2.0</version>
				<executions>
					<execution>
						<goals>
							<goal>compile</goal>
							<goal>testCompile</goal>
							<goal>doc-jar</goal>
						</goals>
						<configuration>
							<args>
								<arg>-make:transitive</arg>
								<arg>-dependencyfile</arg>
								<arg>${project.build.directory}/.scala_dependencies</arg>
							</args>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.18.1</version>
				<configuration>
					<useFile>false</useFile>
					<disableXmlReport>true</disableXmlReport>
					<!-- If you have classpath issue like NoDefClassError,... -->
					<!-- useManifestOnlyJar>false</useManifestOnlyJar -->
					<includes>
						<include>**/*Test.*</include>
						<include>**/*Suite.*</include>
					</includes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.sonatype.plugins</groupId>
				<artifactId>nexus-staging-maven-plugin</artifactId>
				<version>1.6.7</version>
				<extensions>true</extensions>
				<configuration>
					<serverId>ossrh</serverId>
					<nexusUrl>https://oss.sonatype.org/</nexusUrl>
					<autoReleaseAfterClose>true</autoReleaseAfterClose>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.2.1</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar-no-fork</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${maven.compiler.source}</source>
					<target>${maven.compiler.target}</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.avro</groupId>
				<artifactId>avro-maven-plugin</artifactId>
				<version>${avro.version}</version>
				<executions>
					<execution>
						<id>schemas</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>schema</goal>
							<goal>protocol</goal>
							<goal>idl-protocol</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<mainClass />
						</manifest>
					</archive>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>prepare-package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>target/lib</outputDirectory>
							<overWriteReleases>false</overWriteReleases>
							<overWriteSnapshots>false</overWriteSnapshots>
							<overWriteIfNewer>true</overWriteIfNewer>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.7</version>
				<executions>
					<execution>
						<id>copy-resources</id>
						<!-- here the phase you need -->
						<phase>install</phase>
						<goals>
							<goal>copy-resources</goal>
						</goals>
						<configuration>
							<outputDirectory>${basedir}/docker/job-server</outputDirectory>
							<resources>
								<resource>
									<directory>target</directory>
									<includes>
										<include>*.jar</include>
									</includes>
								</resource>
								<resource>
									<directory>target/release</directory>
									<includes>
										<include>*.jar</include>
									</includes>
								</resource>
								<resource>
									<directory>target/lib</directory>
									<includes>
										<include>akka-contrib_2.10-2.3.11.jar</include>
										<include>akka-cluster_2.10-2.3.11.jar</include>
										<include>akka-remote_2.10-2.3.11.jar</include>
									</includes>
								</resource>
							</resources>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>

		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-release-plugin</artifactId>
					<version>2.5.3</version>
					<configuration>
						<autoVersionSubmodules>true</autoVersionSubmodules>
						<useReleaseProfile>false</useReleaseProfile>
						<releaseProfiles>release</releaseProfiles>
						<goals>deploy</goals>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>org.apache.maven.plugins</groupId>
										<artifactId>maven-dependency-plugin</artifactId>
										<versionRange>[2.0,)</versionRange>
										<goals>
											<goal>copy-dependencies</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<execute />
									</action>
								</pluginExecution>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>org.codehaus.mojo</groupId>
										<artifactId>build-helper-maven-plugin</artifactId>
										<versionRange>[1.0,)</versionRange>
										<goals>
											<goal>add-source</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<execute />
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>

<profiles>
		<profile>
			<id>release</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-source-plugin</artifactId>
						<version>2.2.1</version>
						<executions>
							<execution>
								<id>attach-sources</id>
								<goals>
									<goal>jar-no-fork</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-javadoc-plugin</artifactId>
						<version>2.9.1</version>
						<executions>
							<execution>
								<id>attach-javadocs</id>
								<goals>
									<goal>jar</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-gpg-plugin</artifactId>
						<version>1.5</version>
						<executions>
							<execution>
								<id>sign-artifacts</id>
								<phase>verify</phase>
								<goals>
									<goal>sign</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>

	<distributionManagement>
		<snapshotRepository>
			<id>ossrh</id>
			<url>https://oss.sonatype.org/content/repositories/snapshots</url>
		</snapshotRepository>
		<repository>
			<id>ossrh</id>
			<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
		</repository>
	</distributionManagement>

	<repositories>
		<repository>
			<id>twitter4j.org</id>
			<name>twitter4j.org Repository</name>
			<url>http://twitter4j.org/maven2</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>jobserver</id>
			<url>https://dl.bintray.com/spark-jobserver/maven</url>
		</repository>
	</repositories>
</project>


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Module5
{
	class Program
	{
		public enum SchoolStatus
		{
			Student,
			Teacher,
			Other
		}

		public class UProgram
		{
			public string Name { get; private set; }
			public Degree Degree { get; set; }

			public UProgram(string name)
			{
				Name = name;
			}

			public override string ToString()
			{
				return "The " + Name
				       + " program contains the "
				       + Degree.Name + " degree";
			}
		}

		public class Degree
		{
			public string Name { get; private set; }
			public Course Course { get; set; }

			public Degree(string name)
			{
				Name = name;
			}

			public override string ToString()
			{
				return "The " + Name
				       + " degree contains the course "
				       + Course.Name;
			}
		}

		public class Course
		{
			public string Name { get; private set; }
			public IEnumerable<Student> Students { get; set; }

			private IEnumerable<Teacher> _teachers;
			public IEnumerable<Teacher> Teachers
			{
				get { return _teachers; }
				set
				{
					// Instantiate at least one Teacher object.
					if (!value.Any())
						throw new Exception("Instantiate at least one Teacher object.");
					_teachers = value;
				}
			}

			public Course(string name)
			{
				Name = name;
			}

			public override string ToString()
			{
				return "The " + Name
				       + " course contains " + Students.Count()
				       + " student<s>";
			}
		}

		public abstract class APerson
		{
			public string FirstName { get; set; }
			public string LastName { get; set; }
			public DateTime Birthdate { get; set; }

			public abstract SchoolStatus SchoolStatus { get; }

			protected APerson(string firstName, string lastName, DateTime birthdate)
			{
				FirstName = firstName;
				LastName = lastName;
				Birthdate = birthdate;
			}
		}

		public class Student : APerson
		{
			// Add a static class variable to the Student class to track the number of students currently enrolled in a school.
			// Increment a student object count every time a Student is created.
			public static uint EnrolledCount;

			public override SchoolStatus SchoolStatus { get { return SchoolStatus.Student; } }

			public Student(string firstName, string lastName, DateTime birthdate)
				: base(firstName, lastName, birthdate)
			{
				EnrolledCount++;
			}
		}

		public class Teacher : APerson
		{
			public override SchoolStatus SchoolStatus { get { return SchoolStatus.Teacher; } }

			public Teacher(string firstName, string lastName, DateTime birthdate)
				: base(firstName, lastName, birthdate) {}
		}

		private static void Main()
		{
			// Instantiate three Student objects.
			var harry = new Student("Harry", "Potter", new DateTime(1980, 7, 31));
			var ron = new Student("Ron", "Weasley", new DateTime(1980, 3, 1));
			var hermione = new Student("Hermione", "Granger", new DateTime(1979, 9, 19));

			// Instantiate a Course object called Programming with C#.
			var course = new Course("Programming with C#")
			{
				// Add your three students to this Course object.
				Students = new Collection<Student> { harry, ron, hermione },
				// Add that Teacher object to your Course object.
				Teachers = new Collection<Teacher> { new Teacher("Remus",  "Lupin", new DateTime(1960, 3, 10)) }
			};

			// Instantiate a Degree object, such as Bachelor.
			var degree = new Degree("Bachelor")
			{
				// Add your Course object to the Degree object.
				Course = course
			};

			// Instantiate a UProgram object called Information Technology.
			var uProgram = new UProgram("Information Technology")
			{
				// Add the Degree object to the UProgram object.
				Degree = degree
			};

			try
			{
				// Using Console.WriteLine statements, output the following information to the console window:
				Console.WriteLine(uProgram + Environment.NewLine);
				Console.WriteLine(degree + Environment.NewLine);
				Console.WriteLine(course.ToString());

				// Uncomment the following line to print the current enrolled count
				// Console.WriteLine(Student.EnrolledCount);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
			finally
			{
				Console.WriteLine("Press any key to continue ...");
				Console.ReadLine();
			}
		}
	}
}


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>org.tinymediamanager</groupId>
		<artifactId>tmm-parent</artifactId>
		<version>1.1</version>
	</parent>

	<groupId>org.tinymediamanager.plugins</groupId>
	<artifactId>scraper-kodi</artifactId>
	<version>1.15-SNAPSHOT</version>

	<name>Kodi-Scraper plugin</name>
	<description>A Kodi-Scraper plugin</description>
	<url>http://www.tinyMediaManager.org</url>

	<scm>
		<url>https://github.com/tinyMediaManager/${project.artifactId}</url>
		<connection>scm:git:git@github.com:tinyMediaManager/${project.artifactId}.git</connection>
		<developerConnection>scm:git:git@github.com:tinyMediaManager/${project.artifactId}.git</developerConnection>
	  <tag>HEAD</tag>
  </scm>

	<dependencies>
		<dependency>
			<groupId>org.tinymediamanager</groupId>
			<artifactId>api-scraper</artifactId>
			<version>2.9</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

</project>


text:
import java.io.*;

public class sequence {

	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
		int n = Integer.parseInt(in.readLine());

		for (int i = 0; i < n; i++) {
			long s = Long.parseLong(in.readLine());
			long calculito = (s * s) + (2 * s);
			out.write(calculito + "\n");
		}
		in.close();
		out.close();
	}
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @author Ivan Tcholakov <ivantcholakov@gmail.com>, 2014
 * @license The MIT License, http://opensource.org/licenses/MIT
 */

?>

Gravatar Test

Request:

                        <?php echo form_open('', 'id="gravatar_test_form" method="post" role="form"'); ?>
<?php

if (isset($error_message) && $error_message != '') {

?>

                                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                                <?php echo $error_message; ?>

<?php

}

?>

                                <div class="input-group<?php if (!empty($validation_errors['email'])) { ?> has-error<?php } ?>" style="width: 100%;">

                                    <input type="text" id="email" name="email" class="form-control" placeholder="* Enter an email address" value="<?php echo set_value('email', $email); ?>" />

                                <img id="captcha_image"
                                    src="<?php echo $this->captcha->src.'?nocache='.rand(100000000, 999999999); ?>"
                                    class="thumbnail"
                                    style="cursor: pointer;"
                                    i18n:title="captcha.tip"
                                />

                                <div class="input-group<?php if (!empty($validation_errors['captcha'])) { ?> has-error<?php } ?>">

                                    <input type="text" id="captcha" name="captcha" class="form-control" i18n:placeholder="captcha.label|* " maxlength="<?php echo $this->captcha->length; ?>" />

                                <i18n>ui_required_fields_note</i18n>

                                <button id="gravatar_test_form_submit" name="gravatar_test_form_submit" type="submit" class="btn btn-primary btn-lg">

                                    Get Gravatar Info
                                </button>

                        <?php echo form_close(); ?>

<?php

if ($this->input->method() == 'post' && empty($error_message)) {

?>

Result:

                            <img class="img-thumbnail" src="<?php echo $gravatar; ?>" />

                        <?php echo print_d($profile); ?>

                        <?php echo print_d($last_error); ?>

<?php

}

?>


text:
package brooklyn.rest.domain;

import static com.yammer.dropwizard.testing.JsonHelpers.asJson;
import static com.yammer.dropwizard.testing.JsonHelpers.fromJson;
import static com.yammer.dropwizard.testing.JsonHelpers.jsonFixture;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;

import brooklyn.rest.domain.EntitySpec;

import java.io.IOException;

public class EntitySpecTest {

  final EntitySpec entitySpec = new EntitySpec("Vanilla Java App", "brooklyn.entity.java.VanillaJavaApp");

  @Test
  public void testSerializeToJSON() throws IOException {
    assertEquals(asJson(new EntitySpec[]{entitySpec}), jsonFixture("fixtures/entity.json"));
  }

  @Test
  public void testDeserializeFromJSON() throws IOException {
    assertEquals(fromJson(jsonFixture("fixtures/entity.json"), EntitySpec[].class), new EntitySpec[]{entitySpec});
  }

  @Test
  public void testDeserializeFromJSONOnlyWithType() throws IOException {
    EntitySpec actual = fromJson(jsonFixture("fixtures/entity-only-type.json"), EntitySpec.class);
    assertEquals(actual.getName(), actual.getType());
    assertEquals(actual.getConfig().size(), 0);
  }
}


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

<title>AuditLogListenerUtil (Groovy Documentation)</title>
<meta name="date" content="2010-06-24">
<link href="../../../../../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../../../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">

      Overview

      Package
    Class

      Deprecated
      Index
      Help

Groovy Documentation

  FRAMES
 NO FRAMES

  All Classes

SUMMARY: NESTED | FIELD | PROPERTY | CONSTR | METHOD

DETAIL: FIELD | PROPERTY | CONSTR | METHOD

src.groovy.org.codehaus.groovy.grails.plugins.orm.auditable

Class AuditLogListenerUtil

java.lang.Object
  src.groovy.org.codehaus.groovy.grails.plugins.orm.auditable.AuditLogListenerUtil

class AuditLogListenerUtil

    Property Summary

        static groovy.lang.Closure

            actorDefaultGetter

 The original getActor method transplanted to the utility class as
 a closure.

    Constructor Summary

            AuditLogListenerUtil()

    Method Summary

            static def

            resolve(def attr, def str, def log)

 The resolve method was my attempt at being clever.

                Methods inherited from class java.lang.Object

wait, wait, wait, equals, toString, hashCode, getClass, notify, notifyAll

    Property Detail

actorDefaultGetter

static groovy.lang.Closure actorDefaultGetter

 The original getActor method transplanted to the utility class as
 a closure. The closure takes two arguments one a RequestAttributes object
 the other is an HttpSession object.

 These are strongly typed here for the purpose of documentation.

    Constructor Detail

        AuditLogListenerUtil

AuditLogListenerUtil()

    Method Detail

        resolve

public static def resolve(def attr, def str, def log)

 The resolve method was my attempt at being clever. It would attempt to
 resolve the attribute you wanted from the RequestAttributes object passed
 to it. This did not always work for people since on some designs
 users are not *always* logged in to the system.

 It was originally assumed that if you *were* generating events then you
 were logged in so the problem of null session.user did not come up in testing.

Groovy Documentation


text:
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace NAudio.Wave
{
    /// <summary>
    /// A buffer of Wave samples for streaming to a Wave Output device
    /// </summary>
    class WaveOutBuffer : IDisposable
    {
        private readonly WaveHeader header;
        private readonly Int32 bufferSize; // allocated bytes, may not be the same as bytes read
        private readonly byte[] buffer;
        private readonly IWaveProvider waveStream;
        private readonly object waveOutLock;
        private GCHandle hBuffer;
        private IntPtr hWaveOut;
        private GCHandle hHeader; // we need to pin the header structure
        private GCHandle hThis; // for the user callback

        /// <summary>
        /// creates a new wavebuffer
        /// </summary>
        /// <param name="hWaveOut">WaveOut device to write to</param>
        /// <param name="bufferSize">Buffer size in bytes</param>
        /// <param name="bufferFillStream">Stream to provide more data</param>
        /// <param name="waveOutLock">Lock to protect WaveOut API's from being called on >1 thread</param>
        public WaveOutBuffer(IntPtr hWaveOut, Int32 bufferSize, IWaveProvider bufferFillStream, object waveOutLock)
        {
            this.bufferSize = bufferSize;
            this.buffer = new byte[bufferSize];
            this.hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            this.hWaveOut = hWaveOut;
            this.waveStream = bufferFillStream;
            this.waveOutLock = waveOutLock;

            header = new WaveHeader();
            hHeader = GCHandle.Alloc(header, GCHandleType.Pinned);
            header.dataBuffer = hBuffer.AddrOfPinnedObject();
            header.bufferLength = bufferSize;
            header.loops = 1;
            hThis = GCHandle.Alloc(this);
            header.userData = (IntPtr)hThis;
            lock (waveOutLock)
            {
                MmException.Try(WaveInterop.waveOutPrepareHeader(hWaveOut, header, Marshal.SizeOf(header)), "waveOutPrepareHeader");
            }
        }

        #region Dispose Pattern

        /// <summary>
        /// Finalizer for this wave buffer
        /// </summary>
        ~WaveOutBuffer()
        {
            Dispose(false);
            System.Diagnostics.Debug.Assert(true, "WaveBuffer was not disposed");
        }

        /// <summary>
        /// Releases resources held by this WaveBuffer
        /// </summary>
        public void Dispose()
        {
            GC.SuppressFinalize(this);
            Dispose(true);
        }

        /// <summary>
        /// Releases resources held by this WaveBuffer
        /// </summary>
        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                // free managed resources
            }
            // free unmanaged resources
            if (hHeader.IsAllocated)
                hHeader.Free();
            if (hBuffer.IsAllocated)
                hBuffer.Free();
            if (hThis.IsAllocated)
                hThis.Free();
            if (hWaveOut != IntPtr.Zero)
            {
                lock (waveOutLock)
                {
                    WaveInterop.waveOutUnprepareHeader(hWaveOut, header, Marshal.SizeOf(header));
                }
                hWaveOut = IntPtr.Zero;
            }
        }

        #endregion

        /// this is called by the WAVE callback and should be used to refill the buffer
        internal bool OnDone()
        {
            int bytes;
            lock (waveStream)
            {
                bytes = waveStream.Read(buffer, 0, buffer.Length);
            }
            if (bytes == 0)
            {
                return false;
            }
            else
            {
                for (int n = bytes; n < buffer.Length; n++)
                {
                    buffer[n] = 0;
                }
            }
            WriteToWaveOut();
            return true;
        }

        /// <summary>
        /// Whether the header's in queue flag is set
        /// </summary>
        public bool InQueue
        {
            get
            {
                return (header.flags & WaveHeaderFlags.InQueue) == WaveHeaderFlags.InQueue;
            }
        }

        /// <summary>
        /// The buffer size in bytes
        /// </summary>
        public Int32 BufferSize
        {
            get
            {
                return bufferSize;
            }
        }

        private void WriteToWaveOut()
        {
            MmResult result;

            lock (waveOutLock)
            {
                result = WaveInterop.waveOutWrite(hWaveOut, header, Marshal.SizeOf(header));
            }
            if (result != MmResult.NoError)
            {
                throw new MmException(result, "waveOutWrite");
            }

            GC.KeepAlive(this);
        }

    }
}


text:
namespace Khala.EventSourcing.Sql
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Khala.Messaging;

    public class SqlEventSourcedRepository<T> : ISqlEventSourcedRepository<T>
        where T : class, IEventSourced
    {
        private readonly ISqlEventStore _eventStore;
        private readonly ISqlEventPublisher _eventPublisher;
        private readonly IMementoStore _mementoStore;
        private readonly Func<Guid, IEnumerable<IDomainEvent>, T> _entityFactory;
        private readonly Func<Guid, IMemento, IEnumerable<IDomainEvent>, T> _mementoEntityFactory;

        public SqlEventSourcedRepository(
            ISqlEventStore eventStore,
            ISqlEventPublisher eventPublisher,
            Func<Guid, IEnumerable<IDomainEvent>, T> entityFactory)
        {
            _eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore));
            _eventPublisher = eventPublisher ?? throw new ArgumentNullException(nameof(eventPublisher));
            _entityFactory = entityFactory ?? throw new ArgumentNullException(nameof(entityFactory));
        }

        public SqlEventSourcedRepository(
            ISqlEventStore eventStore,
            ISqlEventPublisher eventPublisher,
            IMementoStore mementoStore,
            Func<Guid, IEnumerable<IDomainEvent>, T> entityFactory,
            Func<Guid, IMemento, IEnumerable<IDomainEvent>, T> mementoEntityFactory)
            : this(eventStore, eventPublisher, entityFactory)
        {
            _mementoStore = mementoStore ?? throw new ArgumentNullException(nameof(mementoStore));
            _mementoEntityFactory = mementoEntityFactory ?? throw new ArgumentNullException(nameof(mementoEntityFactory));
        }

        public SqlEventSourcedRepository(
            Func<EventStoreDbContext> dbContextFactory,
            IMessageSerializer serializer,
            IMessageBus messageBus,
            Func<Guid, IEnumerable<IDomainEvent>, T> entityFactory)
            : this(
                  new SqlEventStore(
                      dbContextFactory,
                      serializer),
                  new SqlEventPublisher(
                      dbContextFactory,
                      serializer,
                      messageBus),
                  entityFactory)
        {
        }

        public IEventPublisher EventPublisher => _eventPublisher;

        private bool MementoSupported => _mementoStore != null && _mementoEntityFactory != null;

        public Task SaveAndPublish(
            T source,
            string operationId = default,
            Guid? correlationId = default,
            string contributor = default,
            CancellationToken cancellationToken = default)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            return RunSaveAndPublish(source, operationId, correlationId, contributor, cancellationToken);
        }

        private async Task RunSaveAndPublish(
            T source,
            string operationId,
            Guid? correlationId,
            string contributor,
            CancellationToken cancellationToken)
        {
            await SaveEvents(source, operationId, correlationId, contributor, cancellationToken).ConfigureAwait(false);
            await FlushEvents(source, cancellationToken).ConfigureAwait(false);
            await SaveMementoIfPossible(source, cancellationToken).ConfigureAwait(false);
        }

        private Task SaveEvents(
            T source,
            string operationId,
            Guid? correlationId,
            string contributor,
            CancellationToken cancellationToken)
        {
            return _eventStore.SaveEvents<T>(
                source.FlushPendingEvents(),
                operationId,
                correlationId,
                contributor,
                cancellationToken);
        }

        private Task FlushEvents(T source, CancellationToken cancellationToken)
        {
            return _eventPublisher
                .FlushPendingEvents<T>(source.Id, cancellationToken);
        }

        private Task SaveMementoIfPossible(T source, CancellationToken cancellationToken)
        {
            if (_mementoStore != null &&
                source is IMementoOriginator mementoOriginator)
            {
                IMemento memento = mementoOriginator.SaveToMemento();
                return _mementoStore.Save<T>(source.Id, memento, cancellationToken);
            }

            return Task.FromResult(true);
        }

        public Task<T> Find(Guid sourceId, CancellationToken cancellationToken = default)
        {
            if (sourceId == Guid.Empty)
            {
                throw new ArgumentException(
                    $"{nameof(sourceId)} cannot be empty.", nameof(sourceId));
            }

            return RunFind(sourceId, cancellationToken);
        }

        private async Task<T> RunFind(Guid sourceId, CancellationToken cancellationToken)
        {
            if (MementoSupported)
            {
                IMemento memento = await FindMemento(sourceId, cancellationToken).ConfigureAwait(false);
                if (memento != null)
                {
                    return await RehydrateWithMemento(sourceId, memento, cancellationToken).ConfigureAwait(false);
                }
            }

            return await FindSource(sourceId, cancellationToken).ConfigureAwait(false);
        }

        private Task<IMemento> FindMemento(Guid sourceId, CancellationToken cancellationToken)
        {
            return _mementoStore.Find<T>(sourceId, cancellationToken);
        }

        private async Task<T> RehydrateWithMemento(Guid sourceId, IMemento memento, CancellationToken cancellationToken)
        {
            IEnumerable<IDomainEvent> domainEvents = await
                _eventStore.LoadEvents<T>(sourceId, memento.Version, cancellationToken).ConfigureAwait(false);
            return _mementoEntityFactory.Invoke(sourceId, memento, domainEvents);
        }

        private async Task<T> FindSource(
            Guid sourceId, CancellationToken cancellationToken)
        {
            IEnumerable<IDomainEvent> domainEvents = await
                _eventStore.LoadEvents<T>(sourceId, default, cancellationToken).ConfigureAwait(false);
            return domainEvents.Any() ? _entityFactory.Invoke(sourceId, domainEvents) : null;
        }

        public Task<Guid?> FindIdByUniqueIndexedProperty(
            string name, string value, CancellationToken cancellationToken = default)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            return _eventStore.FindIdByUniqueIndexedProperty<T>(name, value, cancellationToken);
        }
    }
}


text:
require "spec_helper"

describe HitList::RailsModelExtension do

  describe "#module methods" do
    subject { HitList::RailsModelExtension }
    describe "#redis_connection" do
      context "when not specifying any specific connection" do
        it "returns Redis connection with default configuration" do
          expect(subject.redis_connection).to be_a_kind_of(Redis)
        end
      end
    end

    describe "#redis_connection=" do
      it "allows to set Redis connection" do
        subject.redis_connection= 'fake connection'
        expect(subject.redis_connection).to eq('fake connection')
      end
    end
  end

  describe "Class with RailsModelExtension included" do

    SomethingModelish = Struct.new(:id) do
      include HitList::RailsModelExtension
    end

    describe "class methods" do
      subject { SomethingModelish }

      describe "#top_records" do
        it "calls counter top_records method" do
          expect_any_instance_of(HitList::Counter).to receive(:top_records).with(3)
          subject.top_records(3)
        end
      end
    end

    describe "instance methods" do
      subject { SomethingModelish.new(:the_id) }

      describe "#total_hits" do
        it "calls counter total_hits method with model id" do
          expect_any_instance_of(HitList::Counter).to receive(:total_hits).with(:the_id)
          subject.total_hits
        end
      end

      describe "#increment_hit_counter!" do
        it "calls counter hit! method with record id" do
          expect_any_instance_of(HitList::Counter).to receive(:hit!).with(:the_id)
          subject.increment_hit_counter!
        end
      end

      describe "#increment_only_total_hits!" do
        it "calls counter hit! method with record id" do
          expect_any_instance_of(HitList::Counter).to receive(:increment_total_hits!).with(:the_id)
          subject.increment_only_total_hits!
        end
      end

      describe "#increment_only_rank!" do
        it "calls counter hit! method with record id" do
          expect_any_instance_of(HitList::Counter).to receive(:increment_rank!).with(:the_id)
          subject.increment_only_rank!
        end
      end
    end
  end
end


text:
from __future__ import absolute_import

from oslo_config import cfg, types

from st2common import config as st2cfg
from st2common.constants.sensors import DEFAULT_PARTITION_LOADER
from st2common.constants.system import VERSION_STRING
from st2common.constants.system import DEFAULT_CONFIG_FILE_PATH

CONF = cfg.CONF

def parse_args(args=None):
    cfg.CONF(
        args=args,
        version=VERSION_STRING,
        default_config_files=[DEFAULT_CONFIG_FILE_PATH],
    )

def register_opts(ignore_errors=False):
    _register_common_opts(ignore_errors=ignore_errors)
    _register_sensor_container_opts(ignore_errors=ignore_errors)

def get_logging_config_path():
    return cfg.CONF.sensorcontainer.logging

def _register_common_opts(ignore_errors=False):
    st2cfg.register_opts(ignore_errors=ignore_errors)

def _register_sensor_container_opts(ignore_errors=False):
    logging_opts = [
        cfg.StrOpt(
            "logging",
            default="/etc/st2/logging.sensorcontainer.conf",
            help="location of the logging.conf file",
        )
    ]

    st2cfg.do_register_opts(
        logging_opts, group="sensorcontainer", ignore_errors=ignore_errors
    )

    # Partitioning options
    partition_opts = [
        cfg.StrOpt(
            "sensor_node_name", default="sensornode1", help="name of the sensor node."
        ),
        cfg.Opt(
            "partition_provider",
            type=types.Dict(value_type=types.String()),
            default={"name": DEFAULT_PARTITION_LOADER},
            help="Provider of sensor node partition config.",
        ),
    ]

    st2cfg.do_register_opts(
        partition_opts, group="sensorcontainer", ignore_errors=ignore_errors
    )

    # Other options
    other_opts = [
        cfg.BoolOpt(
            "single_sensor_mode",
            default=False,
            help="Run in a single sensor mode where parent process exits when a sensor crashes / "
            "dies. This is useful in environments where partitioning, sensor process life "
            "cycle and failover is handled by a 3rd party service such as kubernetes.",
        )
    ]

    st2cfg.do_register_opts(
        other_opts, group="sensorcontainer", ignore_errors=ignore_errors
    )

    # CLI options
    cli_opts = [
        cfg.StrOpt(
            "sensor-ref",
            help="Only run sensor with the provided reference. Value is of the form "
            "<pack>.<sensor-name> (e.g. linux.FileWatchSensor).",
        ),
        cfg.BoolOpt(
            "single-sensor-mode",
            default=False,
            help="Run in a single sensor mode where parent process exits when a sensor crashes / "
            "dies. This is useful in environments where partitioning, sensor process life "
            "cycle and failover is handled by a 3rd party service such as kubernetes.",
        ),
    ]

    st2cfg.do_register_cli_opts(cli_opts, ignore_errors=ignore_errors)

register_opts(ignore_errors=True)


text:
import path from 'path';
import fs from 'fs';
import should from 'should';
import convertFactory from '../src/index';

const tmpDir = path.join(__dirname, 'temp');

function createConversion(strategy) {
  return convertFactory({
    converterPath: convertFactory.converters.PDF,
    timeout: 10000,
    tmpDir,
    portLeftBoundary: 10000,
    portRightBoundary: 15000,
    strategy
  });
}

function rmDir(dirPath) {
  let files;

  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
  }

  try {
    files = fs.readdirSync(dirPath);
  } catch (err) {
    return;
  }

  if (files.length > 0) {
    for (let ix = 0; ix < files.length; ix++) {
      let filePath = `${dirPath}/${files[ix]}`;

      if (fs.statSync(filePath).isFile()) {
        fs.unlinkSync(filePath);
      }
    }
  }
}

/* eslint-disable padded-blocks */
/* eslint-disable prefer-arrow-callback */
describe('electron html to pdf', () => {
  describe('dedicated-process', () => {
    common('dedicated-process');
  });

  describe('electron-server', () => {
    common('electron-server');
  });

  describe('electron-ipc', () => {
    common('electron-ipc');
  });

  function common(strategy) {
    let conversion = createConversion(strategy);

    after(() => {
      rmDir(tmpDir);
    });

    it('should set number of pages correctly', function(done) {
      conversion('
aa

bb
', (err, res) => {
        if (err) {
          return done(err);
        }

        res.numberOfPages.should.be.eql(2);
        res.stream.close();
        done();
      });
    });

    it('should create a pdf file', function(done) {
      conversion('
foo
', (err, res) => {
        if (err) {
          return done(err);
        }

        should(res.numberOfPages).be.eql(1);
        should(res.stream).have.property('readable');
        res.stream.close();
        done();
      });
    });

    it('should create a pdf file with header');

    it('should create a pdf file with footer');

    it('should create a pdf file with header and footer');

    it('should create a pdf file ignoring ssl errors', function(done) {
      conversion({
        url: 'https://sygris.com'
      }, (err, res) => {
        if (err) {
          return done(err);
        }

        should(res.numberOfPages).be.eql(1);
        should(res.stream).have.property('readable');
        res.stream.close();
        done();
      });
    });

    it('should wait for page js execution', function(done) {
      conversion({
        html: '
aa
',
        waitForJS: true
      }, function(err, res) {
        if (err) {
          return done(err);
        }

        should(res.numberOfPages).be.eql(1);
        should(res.stream).have.property('readable');
        res.stream.close();
        done();
      });
    });

    it('should wait for page async js execution', function(done) {
      conversion({
        html: '
aa
',
        waitForJS: true
      }, function(err, res) {
        if (err) {
          return done(err);
        }

        should(res.numberOfPages).be.eql(1);
        should(res.stream).have.property('readable');
        res.stream.close();
        done();
      });
    });

    it('should allow define a custom var name for page js execution', function(done) {
      conversion({
        html: '
aa
',
        waitForJS: true,
        waitForJSVarName: 'ready'
      }, function(err, res) {
        if (err) {
          return done(err);
        }

        should(res.numberOfPages).be.eql(1);
        should(res.stream).have.property('readable');
        res.stream.close();
        done();
      });
    });

    it('should throw timeout when waiting for page js execution', function(done) {
      conversion({
        html: '
aa
',
        timeout: 500,
        waitForJS: true
      }, function(err) {
        if (!err) {
          return done(new Error('the conversion doesn\'t throw error'));
        }

        if (err.electronTimeout !== undefined) {
          should(err.electronTimeout).be.eql(true);
          done();
        } else {
          done(err);
        }
      });
    });

    it('should work with javascript disabled in web page', function(done) {
      conversion({
        html: '
foo
',
        browserWindow: {
          webPreferences: {
            javascript: false
          }
        }
      }, function(err, res) {
        if (err) {
          return done(err);
        }

        should(res.numberOfPages).be.eql(1);
        should(res.stream).have.property('readable');
        res.stream.close();
        done();
      });
    });

    it('should collect logs in page', function(done) {
      conversion({
        html: `

aa

        `
      }, function(err, res) {
        if (err) {
          return done(err);
        }

        should(res.logs.length).be.aboveOrEqual(3);

        should(res.numberOfPages).be.eql(1);
        should(res.stream).have.property('readable');
        res.stream.close();
        done();
      });
    });
  }

  describe('failing to start workers', () => {
    it('should not accumulate error callbacks', (done) => {
      let conversion = convertFactory({
        converterPath: convertFactory.converters.PDF,
        pathToElectron: 'invalid',
        timeout: 10000,
        tmpDir,
        portLeftBoundary: 10000,
        portRightBoundary: 15000,
        strategy: 'electron-ipc'
      });

      let cbCounter = 0;

      conversion({
        html: 'test'
      }, function() {
        cbCounter++;

        conversion({
          html: 'test'
        }, function() {
          cbCounter++;
          setTimeout(function() {
            cbCounter.should.be.eql(2);
            done();
          }, 0);
        });
      });
    });
  });
});


text:
package edu.hku.sdb.catalog;

import static org.junit.Assert.assertEquals;

import java.math.BigInteger;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import edu.hku.sdb.crypto.SDBEncrypt;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Test the MetaStore using derby.
 */
public class MetaStoreTest {

  private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
  private PersistenceManagerFactory pmf;
  private PersistenceManager pm;

  /**
   * Prepare a in-memory database for testing
   */
  @Before
  public void prepareTestDB() {
    try {
      Class.forName(driver).newInstance();
    } catch (InstantiationException | IllegalAccessException
            | ClassNotFoundException e) {
      e.printStackTrace();
    }

    Properties properties = new Properties();
    properties.setProperty("javax.jdo.option.ConnectionURL",
            "jdbc:derby:memory:test_db;create=true");
    properties.setProperty("javax.jdo.option.ConnectionDriverName",
            "org.apache.derby.jdbc.EmbeddedDriver");
    properties.setProperty("javax.jdo.option.ConnectionUserName", "");
    properties.setProperty("javax.jdo.option.ConnectionPassword", "");
    properties.setProperty("datanucleus.schema.autoCreateSchema", "true");
    properties.setProperty("datanucleus.schema.autoCreateTables", "true");
    properties.setProperty("datanucleus.schema.validateTables", "false");
    properties.setProperty("datanucleus.schema.validateConstraints", "false");

    pmf = JDOHelper.getPersistenceManagerFactory(properties);
    pm = pmf.getPersistenceManager();
  }

  /**
   * Drop the in-memory database after test.
   */
  @After
  public void clearTestDB() {
    try {
      pm.close();
      DriverManager.getConnection("jdbc:derby:memory:test_db;drop=true");
    } catch (SQLException se) {
      if (!se.getSQLState().equals("08006")) {
        // SQLState 08006 indicates a success
        se.printStackTrace();
      }
    }
  }

  @Test
  public void testInsertDB() {
    MetaStore metaDB = new MetaStore(pm);

    String dbName1 = "dummy_db1";
    String dbName2 = "dummy_db2";

    DBMeta db1 = new DBMeta(dbName1);
    DBMeta db2 = new DBMeta(dbName2.toUpperCase());
    BigInteger p = SDBEncrypt.generateRandPrime();
    BigInteger q = SDBEncrypt.generateRandPrime();
    db1.setPrime1(p.toString());
    db1.setPrime2(q.toString());
    metaDB.addDB(db1);
    metaDB.addDB(db2);

    String tblName1 = "dummy_tbl1";
    String tblName2 = "dummy_tbl2";
    String tblName3 = "dummy_tbl3";

    TableMeta tbl1 = new TableMeta(dbName1, tblName1.toUpperCase());
    TableMeta tbl2 = new TableMeta(dbName2.toUpperCase(), tblName2);
    TableMeta tbl3 = new TableMeta(dbName2, tblName3);
    metaDB.addTbl(tbl1);
    metaDB.addTbl(tbl2);
    metaDB.addTbl(tbl3);

    db1.getTbls().add(tbl1);
    db2.getTbls().add(tbl2);
    db2.getTbls().add(tbl3);

    metaDB.addDB(db1);
    metaDB.addDB(db2);

    assertEquals(db1, metaDB.getDB(dbName1.toUpperCase()));
    assertEquals(db2, metaDB.getDB(dbName2));
    assertEquals(p.toString(), metaDB.getDB(dbName1.toUpperCase()).getPrime1());
    assertEquals(2, metaDB.getAllDBs().size());

    String colName1 = "dummy_col1";
    String colName2 = "dummy_col2";

    ColumnMeta col1 = new ColumnMeta(dbName1.toUpperCase(),
            tblName1.toUpperCase(), colName1);
    ColumnMeta col2 = new ColumnMeta(dbName2, tblName2.toUpperCase(),
            colName2.toUpperCase(), ScalarType.createCharType(8).toString(), true,"2", "2");

    metaDB.addCol(col1);
    metaDB.addCol(col2);

    tbl1.getCols().add(col1);
    tbl2.getCols().add(col2);

    metaDB.addTbl(tbl1);
    metaDB.addTbl(tbl2);
    metaDB.addTbl(tbl3);

    assertEquals(tbl1, metaDB.getTbl(dbName1.toUpperCase(), tblName1));
    assertEquals(tbl2, metaDB.getTbl(dbName2, tblName2.toUpperCase()));
    assertEquals(tbl3, metaDB.getTbl(dbName2, tblName3));

    assertEquals(col1,
            metaDB.getCol(dbName1, tblName1.toUpperCase(), colName1.toUpperCase()));
    assertEquals(col2,
            metaDB.getCol(dbName2.toUpperCase(), tblName2.toUpperCase(), colName2));

    assertEquals(1, metaDB.getTbl(dbName2, tblName2).getCols().size());

    ColumnMeta testColMeta = metaDB.getCol(dbName2.toUpperCase(), tblName2
            .toUpperCase(), colName2);

    assertEquals(new SdbColumnKey(testColMeta.getM(), testColMeta.getX()), new SdbColumnKey("2", "2"));
    assertEquals(metaDB.getDB("dummy_db1").getTbls().size(), 1);
    assertEquals(metaDB.getDB("dummy_db1").getTbls().get(0).getCols().size(), 1);
  }

}


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

<mappings xmlns="http://dozer.sourceforge.net"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozer.sourceforge.net http://dozer.sourceforge.net/schema/beanmapping.xsd">

    <mapping map-id="null" wildcard="false">
        <class-a>java.util.HashMap</class-a>
        <class-b>org.dozer.vo.A</class-b>
        <field>
            this
            b
        </field>
    </mapping>

  <mapping map-id="not-null" map-null="false" wildcard="false">
      <class-a>java.util.HashMap</class-a>
      <class-b>org.dozer.vo.A</class-b>
      <field>
          this
          b
      </field>
  </mapping>

  <mapping map-id="null-set" wildcard="false">
      <class-a>org.dozer.vo.set.NamesArray</class-a>
      <class-b>org.dozer.vo.set.NamesSet</class-b>
      <field>
          names
          names
          java.util.HashSet
      </field>
  </mapping>

  <mapping map-id="null-list" wildcard="false">
      <class-a>org.dozer.vo.set.NamesArray</class-a>
      <class-b>org.dozer.vo.set.NamesList</class-b>
      <field>
          names
          names
          java.util.LinkedList
      </field>
  </mapping>

</mappings>


text:
using Piranha.Extend.Fields;

namespace Piranha.Manager.Models;

/// <summary>
/// Page edit model.
/// </summary>
public class PageEditModel : Content.ContentEditModel
{
    /// <summary>
    /// Gets/sets the mandatory site id.
    /// </summary>
    public Guid SiteId { get; set; }

    /// <summary>
    /// Gets/sets the optional parent id. This determines the
    /// hierarchical position of the page.
    /// </summary>
    public Guid? ParentId { get; set; }

    /// <summary>
    /// Gets/sets the id of the original page if this is a copy.
    /// </summary>
    public Guid? OriginalId { get; set; }

    /// <summary>
    /// Gets/sets the sort order of the page in its
    /// hierarchical position.
    /// </summary>
    public int SortOrder { get; set; }

    /// <summary>
    /// Gets/sets the optional navigation title.
    /// </summary>
    public string NavigationTitle { get; set; }

    /// <summary>
    /// Gets/sets the unique slug.
    /// </summary>
    public string Slug { get; set; }

    /// <summary>
    /// Gets/sets the optional meta title.
    /// </summary>
    public string MetaTitle { get; set; }

    /// <summary>
    /// Gets/sets the optional meta keywords.
    /// </summary>
    public string MetaKeywords { get; set; }

    /// <summary>
    /// Gets/sets the optional meta description.
    /// </summary>
    public string MetaDescription { get; set; }

    /// <summary>
    /// Gets/sets the meta index.
    /// </summary>
    public bool MetaIndex { get; set; }

    /// <summary>
    /// Gets/sets the meta follow.
    /// </summary>
    public bool MetaFollow { get; set; }

    /// <summary>
    /// Gets/sets the meta priority.
    /// </summary>
    public double MetaPriority { get; set; }

    /// <summary>
    /// Gets/sets the optional og title.
    /// </summary>
    public string OgTitle { get; set; }

    /// <summary>
    /// Gets/sets the optional og description.
    /// </summary>
    public string OgDescription { get; set; }

    /// <summary>
    /// Gets/sets the optional og image.
    /// </summary>
    public ImageField OgImage { get; set; }

    /// <summary>
    /// Gets/sets if the page should be hidden in the menu structure.
    /// </summary>
    public bool IsHidden { get; set; }

    /// <summary>
    /// Gets/sets the published date.
    /// </summary>
    public string Published { get; set; }

    /// <summary>
    /// Gets/sets the published time.
    /// </summary>
    public string PublishedTime { get; set; }

    /// <summary>
    /// Gets/sets the optional redirect url.
    /// </summary>
    public string RedirectUrl { get; set; }

    /// <summary>
    /// Gets/sets the redirect type.
    /// </summary>
    public string RedirectType { get; set; } = "permanent";

    /// <summary>
    /// Gets/sets the optional primary image.
    /// </summary>
    public ImageField PrimaryImage { get; set; }

    /// <summary>
    /// Gets/sets the optional excerpt.
    /// </summary>
    public string Excerpt { get; set; }

    /// <summary>
    /// Gets/sets if comments should be enabled.
    /// </summary>
    public bool EnableComments { get; set; }

    /// <summary>
    /// Gets/sets after how many days after publish date comments
    /// should be closed. A value of 0 means never.
    /// </summary>
    public int CloseCommentsAfterDays { get; set; }

    /// <summary>
    /// Gets/sets the total comment count.
    /// </summary>
    public int CommentCount { get; set; }

    /// <summary>
    /// Gets/sets the number of pending comments.
    /// </summary>
    /// <value></value>
    public int PendingCommentCount { get; set; }

    /// <summary>
    /// Gets/sets the content status.
    /// </summary>
    public string State { get; set; }

    /// <summary>
    /// Gets/sets if this is a copy.
    /// </summary>
    public bool IsCopy { get { return OriginalId.HasValue; } }

    /// <summary>
    /// Gets/sets the available routes.
    /// </summary>
    public List<RouteModel> Routes { get; set; } = new List<RouteModel>();

    /// <summary>
    /// Gets/sets the selected route.
    /// </summary>
    public RouteModel SelectedRoute { get; set; }

    /// <summary>
    /// Gets/sets the currently selected permissions.
    /// </summary>
    public IList<string> SelectedPermissions { get; set; } = new List<string>();

    /// <summary>
    /// Gets/sets all of the available permissions.
    /// </summary>
    public IList<KeyValuePair<string, string>> Permissions { get; set; } = new List<KeyValuePair<string, string>>();

    /// <summary>
    /// Gets/sets if primary image should be used for the
    /// post type. The default value is true.
    /// </summary>
    public bool UsePrimaryImage { get; set; } = true;

    /// <summary>
    /// Gets/sets if excerpt should be used for the
    /// post type. The default value is true.
    /// </summary>
    public bool UseExcerpt { get; set; } = true;

    /// <summary>
    /// Gets/sets if excerpt should in HTML-format. The
    /// default value is false.
    /// </summary>
    public bool UseHtmlExcerpt { get; set; }
}