text:
package org.flywaydb.sbt

import java.util.Properties

import org.flywaydb.core.Flyway
import org.flywaydb.core.internal.info.MigrationInfoDumper
import org.flywaydb.core.internal.util.logging.{LogCreator, LogFactory}
import sbt.Keys._
import sbt._
import sbt.classpath._

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._

object FlywayPlugin extends AutoPlugin {

  override def trigger = allRequirements

  object autoImport {

    //*********************
    // common migration settings for all tasks
    //*********************

    val flywayDriver = settingKey[String]("The fully qualified classname of the jdbc driver to use to connect to the database. By default, the driver is autodetected based on the url.")
    val flywayUrl = settingKey[String]("The jdbc url to use to connect to the database.")
    val flywayUser = settingKey[String]("The user to use to connect to the database.")
    val flywayPassword = settingKey[String]("The password to use to connect to the database.")

    val flywaySchemas = settingKey[Seq[String]]("List of the schemas managed by Flyway. The first schema in the list will be automatically set as the default one during the migration. It will also be the one containing the metadata table. These schema names are case-sensitive. (default: The default schema for the datasource connection)")
    val flywayTable = settingKey[String]("The name of the metadata table that will be used by Flyway. (default: schema_version) By default (single-schema mode) the metadata table is placed in the default schema for the connection provided by the datasource. When the flyway.schemas property is set (multi-schema mode), the metadata table is placed in the first schema of the list.")
    val flywayBaselineVersion = settingKey[String]("The version to tag an existing schema with when executing baseline. (default: 1)")
    val flywayBaselineDescription = settingKey[String]("The description to tag an existing schema with when executing baseline. (default: << Flyway Baseline >>)")

    //*********************
    // common settings for migration loading tasks (used by migrate, validate, info)
    //*********************

    val flywayLocations = settingKey[Seq[String]]("Locations on the classpath to scan recursively for migrations. Locations may contain both sql and code-based migrations. (default: filesystem:src/main/resources/db/migration)")
    val flywayResolvers = settingKey[Seq[String]](" The fully qualified class names of the custom MigrationResolvers to be used in addition to the built-in ones for resolving Migrations to apply.")
    val flywaySkipDefaultResolvers = settingKey[Boolean]("Whether default built-in resolvers should be skipped. (default: false)")
    val flywayEncoding = settingKey[String]("The encoding of Sql migrations. (default: UTF-8)")
    val flywaySqlMigrationPrefix = settingKey[String]("The file name prefix for Sql migrations (default: V)")
    val flywayRepeatableSqlMigrationPrefix = settingKey[String]("The file name prefix for repeatable sql migrations (default: R)")
    val flywaySqlMigrationSeparator = settingKey[String]("The file name separator for Sql migrations (default: __)")
    val flywaySqlMigrationSuffix = settingKey[String]("The file name suffix for Sql migrations (default: .sql)")
    val flywayCleanOnValidationError = settingKey[Boolean]("Whether to automatically call clean or not when a validation error occurs. (default: {@code false})<br/> This is exclusively intended as a convenience for development. Even tough we strongly recommend not to change migration scripts once they have been checked into SCM and run, this provides a way of dealing with this case in a smooth manner. The database will be wiped clean automatically, ensuring that the next migration will bring you back to the state checked into SCM. Warning ! Do not enable in production !")
    val flywayCleanDisabled = settingKey[Boolean]("Whether to disable clean. This is especially useful for production environments where running clean can be quite a career limiting move. (default: false)")
    val flywayTarget = settingKey[String]("The target version up to which Flyway should run migrations. Migrations with a higher version number will not be  applied. (default: the latest version)")
    val flywayOutOfOrder = settingKey[Boolean]("Allows migrations to be run \"out of order\" (default: {@code false}). If you already have versions 1 and 3 applied, and now a version 2 is found, it will be applied too instead of being ignored.")
    val flywayCallbacks = settingKey[Seq[String]]("A list of fully qualified FlywayCallback implementation classnames that will be used for Flyway lifecycle notifications. (default: Empty)")
    val flywaySkipDefaultCallbacks = settingKey[Boolean]("Whether default built-in callbacks should be skipped. (default: false)")

    //*********************
    // settings for migrate
    //*********************

    val flywayIgnoreMissingMigrations = settingKey[Boolean]("Ignores missing migrations when reading the metadata table. (default: false)")
    val flywayIgnoreFutureMigrations = settingKey[Boolean]("Ignores future migrations when reading the metadata table. These are migrations that were performed by a newer deployment of the application that are not yet available in this version. For example: we have migrations available on the classpath up to version 3.0. The metadata table indicates that a migration to version 4.0 (unknown to us) has already been applied. Instead of bombing out (fail fast) with an exception, a warning is logged and Flyway continues normally. This is useful for situations where one must be able to redeploy an older version of the application after the database has been migrated by a newer one. (default: true)")
    val flywayIgnoreFailedFutureMigration = settingKey[Boolean]("Ignores failed future migrations when reading the metadata table. These are migrations that we performed by a newer deployment of the application that are not yet available in this version. For example: we have migrations available on the classpath up to version 3.0. The metadata table indicates that a migration to version 4.0 (unknown to us) has already been attempted and failed. Instead of bombing out (fail fast) with an exception, a warning is logged and Flyway terminates normally. This is useful for situations where a database rollback is not an option. An older version of the application can then be redeployed, even though a newer one failed due to a bad migration. (default: false)")
    val flywayPlaceholderReplacement = settingKey[Boolean]("Whether placeholders should be replaced. (default: true)")
    val flywayPlaceholders = settingKey[Map[String, String]]("A map of <placeholder, replacementValue> to apply to sql migration scripts.")
    val flywayPlaceholderPrefix = settingKey[String]("The prefix of every placeholder. (default: ${ )")
    val flywayPlaceholderSuffix = settingKey[String]("The suffix of every placeholder. (default: } )")
    val flywayBaselineOnMigrate = settingKey[Boolean]("Whether to automatically call baseline when migrate is executed against a non-empty schema with no metadata table. This schema will then be baselined with the {@code baselineVersion} before executing the migrations. Only migrations above {@code baselineVersion} will then be applied. This is useful for initial Flyway production deployments on projects with an existing DB. Be careful when enabling this as it removes the safety net that ensures Flyway does not migrate the wrong database in case of a configuration mistake! (default: {@code false})")
    val flywayValidateOnMigrate = settingKey[Boolean]("Whether to automatically call validate or not when running migrate. (default: true)")
    val flywayAllowMixedMigrations = settingKey[Boolean]("Whether to allow mixing transactional and non-transactional statements within the same migration. (default: false)")
    val flywayMixed = settingKey[Boolean]("Whether to allow mixing transactional and non-transactional statements within the same migration. (default: false)")
    val flywayGroup = settingKey[Boolean]("Whether to group all pending migrations together in the same transaction when applying them (only recommended for databases with support for DDL transactions). (default: false)")
    val flywayInstalledBy = settingKey[String]("The username that will be recorded in the metadata table as having applied the migration. (default: null)")

    //*********************
    // flyway tasks
    //*********************

    val flywayMigrate = taskKey[Unit]("Migrates of the configured database to the latest version.")
    val flywayValidate = taskKey[Unit]("Validate applied migrations against resolved ones (on the filesystem or classpath) to detect accidental changes that may prevent the schema(s) from being recreated exactly. Validation fails if differences in migration names, types or checksums are found, versions have been applied that aren't resolved locally anymore or versions have been resolved that haven't been applied yet")
    val flywayInfo = taskKey[Unit]("Retrieves the complete information about the migrations including applied, pending and current migrations with details and status.")
    val flywayClean = taskKey[Unit]("Drops all database objects.")
    val flywayBaseline = taskKey[Unit]("Baselines an existing database, excluding all migrations up to and including baselineVersion.")
    val flywayRepair = taskKey[Unit]("Repairs the metadata table.")
  }

  //*********************
  // convenience settings
  //*********************

  private case class ConfigDataSource(driver: String, url: String, user: String, password: String) {
    def asProps: Map[String, String] =  (driver.isEmpty match {
      case true => Map()
      case false => Map("flyway.driver" -> driver)
    }) ++ Map("flyway.url" -> url, "flyway.user" -> user, "flyway.password" -> password)
  }
  private case class ConfigBase(schemas: Seq[String], table: String, baselineVersion: String, baselineDescription: String)
  private case class ConfigMigrationLoading(locations: Seq[String], resolvers: Seq[String], skipDefaultResolvers: Boolean, encoding: String,
                                            cleanOnValidationError: Boolean, cleanDisabled: Boolean, target: String, outOfOrder: Boolean,
                                            callbacks: Seq[String], skipDefaultCallbacks: Boolean)
  private case class ConfigSqlMigration(sqlMigrationPrefix: String, repeatableSqlMigrationPrefix: String, sqlMigrationSeparator: String, sqlMigrationSuffix: String)
  private case class ConfigMigrate(ignoreMissingMigrations: Boolean, ignoreFutureMigrations: Boolean, ignoreFailedFutureMigration: Boolean,
                                   baselineOnMigrate: Boolean, validateOnMigrate: Boolean,
                                   allowMixedMigrations: Boolean, mixed: Boolean, group: Boolean, installedBy: String)
  private case class ConfigPlaceholder(placeholderReplacement: Boolean, placeholders: Map[String, String],
                                   placeholderPrefix: String, placeholderSuffix: String)
  private case class Config(dataSource: ConfigDataSource, base: ConfigBase, migrationLoading: ConfigMigrationLoading,
                            sqlMigration: ConfigSqlMigration, migrate: ConfigMigrate, placeholder: ConfigPlaceholder)

  private lazy val flywayConfigDataSource = taskKey[ConfigDataSource]("The Flyway data source configuration.")
  private lazy val flywayConfigBase = taskKey[ConfigBase]("The Flyway base configuration.")
  private lazy val flywayConfigMigrationLoading = taskKey[ConfigMigrationLoading]("The Flyway migration loading configuration.")
  private lazy val flywayConfigSqlMigration = taskKey[ConfigSqlMigration]("The Flyway sql migration configuration.")
  private lazy val flywayConfigMigrate = taskKey[ConfigMigrate]("The Flyway migrate configuration.")
  private lazy val flywayConfigPlaceholder = taskKey[ConfigPlaceholder]("The Flyway placeholder configuration.")
  private lazy val flywayConfig = taskKey[Config]("The Flyway configuration.")

  //*********************
  // flyway defaults
  //*********************

  override def projectSettings :Seq[Setting[_]] = flywayBaseSettings(Runtime) ++ inConfig(Test)(flywayBaseSettings(Test))

  def flywayBaseSettings(conf: Configuration) :Seq[Setting[_]] = {
    import org.flywaydb.sbt.FlywayPlugin.autoImport._
    val defaults = new Flyway()
    Seq[Setting[_]](
      flywayDriver := "",
      flywayUrl := "",
      flywayUser := "",
      flywayPassword := "",
      flywayLocations := List("filesystem:src/main/resources/db/migration"),
      flywayResolvers := Array.empty[String],
      flywaySkipDefaultResolvers := defaults.isSkipDefaultResolvers,
      flywaySchemas := defaults.getSchemas.toSeq,
      flywayTable := defaults.getTable,
      flywayBaselineVersion := defaults.getBaselineVersion.getVersion,
      flywayBaselineDescription := defaults.getBaselineDescription,
      flywayEncoding := defaults.getEncoding,
      flywaySqlMigrationPrefix := defaults.getSqlMigrationPrefix,
      flywayRepeatableSqlMigrationPrefix := defaults.getRepeatableSqlMigrationPrefix,
      flywaySqlMigrationSeparator := defaults.getSqlMigrationSeparator,
      flywaySqlMigrationSuffix := defaults.getSqlMigrationSuffix,
      flywayTarget := defaults.getTarget.getVersion,
      flywayOutOfOrder := defaults.isOutOfOrder,
      flywayCallbacks := new Array[String](0),
      flywaySkipDefaultCallbacks := defaults.isSkipDefaultCallbacks,
      flywayIgnoreMissingMigrations := defaults.isIgnoreMissingMigrations,
      flywayIgnoreFutureMigrations := defaults.isIgnoreFutureMigrations,
      flywayIgnoreFailedFutureMigration := false,
      flywayPlaceholderReplacement := defaults.isPlaceholderReplacement,
      flywayPlaceholders := defaults.getPlaceholders.asScala.toMap,
      flywayPlaceholderPrefix := defaults.getPlaceholderPrefix,
      flywayPlaceholderSuffix := defaults.getPlaceholderSuffix,
      flywayBaselineOnMigrate := defaults.isBaselineOnMigrate,
      flywayValidateOnMigrate := defaults.isValidateOnMigrate,
      flywayAllowMixedMigrations := defaults.isAllowMixedMigrations,
      flywayMixed := defaults.isMixed,
      flywayGroup := defaults.isGroup,
      flywayInstalledBy := "",
      flywayCleanOnValidationError := defaults.isCleanOnValidationError,
      flywayCleanDisabled := defaults.isCleanDisabled,
      flywayConfigDataSource <<= (flywayDriver, flywayUrl, flywayUser, flywayPassword) map {
        (driver, url, user, password) => ConfigDataSource(driver, url, user, password)
      },
      flywayConfigBase <<= (flywaySchemas, flywayTable, flywayBaselineVersion, flywayBaselineDescription) map {
        (schemas, table, baselineVersion, baselineDescription) =>
          ConfigBase(schemas, table, baselineVersion, baselineDescription)
      },
      flywayConfigMigrationLoading <<= (flywayLocations, flywayResolvers, flywaySkipDefaultResolvers, flywayEncoding, flywayCleanOnValidationError, flywayCleanDisabled, flywayTarget, flywayOutOfOrder, flywayCallbacks, flywaySkipDefaultCallbacks) map {
        (locations, resolvers, skipDefaultResolvers, encoding, cleanOnValidationError, cleanDisabled, target, outOfOrder, callbacks, skipDefaultCallbacks) =>
          ConfigMigrationLoading(locations, resolvers, skipDefaultResolvers, encoding, cleanOnValidationError, cleanDisabled, target, outOfOrder, callbacks, skipDefaultCallbacks)
      },
      flywayConfigSqlMigration <<= (flywaySqlMigrationPrefix, flywayRepeatableSqlMigrationPrefix, flywaySqlMigrationSeparator, flywaySqlMigrationSuffix) map {
        (sqlMigrationPrefix, repeatableSqlMigrationPrefix, sqlMigrationSeparator, sqlMigrationSuffix) =>
          ConfigSqlMigration(sqlMigrationPrefix, repeatableSqlMigrationPrefix, sqlMigrationSeparator, sqlMigrationSuffix)
      },
      flywayConfigMigrate <<= (flywayIgnoreMissingMigrations, flywayIgnoreFutureMigrations, flywayIgnoreFailedFutureMigration,
        flywayBaselineOnMigrate, flywayValidateOnMigrate, flywayAllowMixedMigrations, flywayMixed, flywayGroup, flywayInstalledBy) map {
        (ignoreMissingMigrations, ignoreFutureMigrations, ignoreFailedFutureMigration,
         baselineOnMigrate, validateOnMigrate, allowMixedMigrations, mixed, group, installedBy) =>
          ConfigMigrate(ignoreMissingMigrations, ignoreFutureMigrations, ignoreFailedFutureMigration, baselineOnMigrate, validateOnMigrate, allowMixedMigrations, mixed, group, installedBy)
      },
      flywayConfigPlaceholder <<= (flywayPlaceholderReplacement, flywayPlaceholders, flywayPlaceholderPrefix, flywayPlaceholderSuffix) map {
        (placeholderReplacement, placeholders, placeholderPrefix, placeholderSuffix) =>
          ConfigPlaceholder(placeholderReplacement, placeholders, placeholderPrefix, placeholderSuffix)
      },
      flywayConfig <<= (flywayConfigDataSource, flywayConfigBase, flywayConfigMigrationLoading, flywayConfigSqlMigration, flywayConfigMigrate, flywayConfigPlaceholder) map {
        (dataSource, base, migrationLoading, sqlMigration, migrate, placeholder) => Config(dataSource, base, migrationLoading, sqlMigration, migrate, placeholder)
      },
      flywayMigrate <<= (fullClasspath in conf, flywayConfig, streams) map {
        (cp, config, s) => withPrepared(cp, s) { Flyway(config).migrate() }
      },
      flywayValidate <<= (fullClasspath in conf, flywayConfig, streams) map {
        (cp, config, s) => withPrepared(cp, s) { Flyway(config).validate() }
      },
      flywayInfo <<= (fullClasspath in conf, flywayConfig, streams) map {
        (cp, config, s) => withPrepared(cp, s) {
          val info = Flyway(config).info()
          s.log.info(MigrationInfoDumper.dumpToAsciiTable(info.all()))
          info
        }
      },
      flywayRepair <<= (fullClasspath in conf, flywayConfig, streams) map {
        (cp, config, s) => withPrepared(cp, s) { Flyway(config).repair() }
      },
      flywayClean <<= (fullClasspath in conf, flywayConfig, streams) map {
        (cp, config, s) => withPrepared(cp, s) { Flyway(config).clean() }
      },
      flywayBaseline <<= (fullClasspath in conf, flywayConfig, streams) map {
        (cp, config, s) => withPrepared(cp, s) { Flyway(config).baseline() }
      }
    )
  }

  private def withPrepared[T](cp: Types.Id[Keys.Classpath], streams: TaskStreams)(f: => T): T = {
    registerAsFlywayLogger(streams)
    withContextClassLoader(cp)(f)
  }

  /**
   * registers sbt log as a static logger for Flyway
   */
  private def registerAsFlywayLogger(streams: TaskStreams) {
    LogFactory.setLogCreator(SbtLogCreator)
    FlywaySbtLog.streams = Some(streams)
  }

  private def withContextClassLoader[T](cp: Types.Id[Keys.Classpath])(f: => T): T = {
    val classloader = ClasspathUtilities.toLoader(cp.map(_.data), getClass.getClassLoader)
    val thread = Thread.currentThread
    val oldLoader = thread.getContextClassLoader
    try {
      thread.setContextClassLoader(classloader)
      f
    } finally {
      thread.setContextClassLoader(oldLoader)
    }
  }

  private object Flyway {
    def apply(config: Config): Flyway = {
      val flyway = new Flyway()
      flyway.configure(config)
      flyway
    }
  }

  private implicit class StringOps(val s: String) extends AnyVal {
    def emptyToNull(): String = s match {
      case ss if ss.isEmpty => null
      case _ => s
    }
  }

  private implicit class FlywayOps(val flyway: Flyway) extends AnyVal {
    def configure(config: Config): Flyway = {
      flyway
      .configure(config.base)
      .configure(config.migrationLoading)
      .configure(config.sqlMigration)
      .configure(config.migrate)
      .configure(config.placeholder)
      .configureSysProps(config.dataSource)
    }
    def configure(config: ConfigBase): Flyway = {
      flyway.setSchemas(config.schemas: _*)
      flyway.setTable(config.table)
      flyway.setBaselineVersionAsString(config.baselineVersion)
      flyway.setBaselineDescription(config.baselineDescription)
      flyway
    }
    def configure(config: ConfigMigrationLoading): Flyway = {
      flyway.setLocations(config.locations: _*)
      flyway.setEncoding(config.encoding)
      flyway.setCleanOnValidationError(config.cleanOnValidationError)
      flyway.setCleanDisabled(config.cleanDisabled)
      flyway.setTargetAsString(config.target)
      flyway.setOutOfOrder(config.outOfOrder)
      flyway.setCallbacksAsClassNames(config.callbacks: _*)
      flyway.setResolversAsClassNames(config.resolvers: _*)
      flyway.setSkipDefaultResolvers(config.skipDefaultResolvers)
      flyway.setSkipDefaultCallbacks(config.skipDefaultCallbacks)
      flyway
    }
    def configure(config: ConfigSqlMigration): Flyway = {
      flyway.setSqlMigrationPrefix(config.sqlMigrationPrefix)
      flyway.setRepeatableSqlMigrationPrefix(config.repeatableSqlMigrationPrefix)
      flyway.setSqlMigrationSeparator(config.sqlMigrationSeparator)
      flyway.setSqlMigrationSuffix(config.sqlMigrationSuffix)
      flyway
    }
    def configure(config: ConfigMigrate): Flyway = {
      flyway.setIgnoreMissingMigrations(config.ignoreMissingMigrations)
      flyway.setIgnoreFutureMigrations(config.ignoreFutureMigrations)
      if (config.ignoreFailedFutureMigration) {
        flyway.setIgnoreFailedFutureMigration(config.ignoreFailedFutureMigration)
      }
      flyway.setBaselineOnMigrate(config.baselineOnMigrate)
      flyway.setValidateOnMigrate(config.validateOnMigrate)
      if (config.allowMixedMigrations) {
        flyway.setAllowMixedMigrations(config.allowMixedMigrations)
      }
      flyway.setMixed(config.mixed)
      flyway.setGroup(config.group)
      flyway.setInstalledBy(config.installedBy)
      flyway
    }
    def configure(config: ConfigPlaceholder): Flyway = {
      flyway.setPlaceholderReplacement(config.placeholderReplacement)
      flyway.setPlaceholders(config.placeholders)
      flyway.setPlaceholderPrefix(config.placeholderPrefix)
      flyway.setPlaceholderSuffix(config.placeholderSuffix)
      flyway
    }
    def configureSysProps(config: ConfigDataSource): Flyway = {
      val props = new Properties()
      System.getProperties.filter(e => e._1.startsWith("flyway")).foreach(e => props.put(e._1, e._2))
      config.asProps.filter(e => !sys.props.contains(e._1)).foreach(e => props.put(e._1, e._2))
      flyway.configure(props)
      flyway
    }
  }

  private object SbtLogCreator extends LogCreator {
    def createLogger(clazz: Class[_]) = FlywaySbtLog
  }

  private object FlywaySbtLog extends org.flywaydb.core.internal.util.logging.Log {
    var streams: Option[TaskStreams] = None
    def debug(message: String) { streams map (_.log.debug(message)) }
    def info(message: String) { streams map (_.log.info(message)) }
    def warn(message: String) { streams map (_.log.warn(message)) }
    def error(message: String) { streams map (_.log.error(message)) }
    def error(message: String, e: Exception) { streams map (_.log.error(message)); streams map (_.log.trace(e)) }
  }
}


text:
<?php
/**
 * ErrorHandler.php
 *
 * @author  Elvyrra
 * @license http://rem.mit-license.org/ MIT
 */

namespace Hawk;

/**
 * This class defines the errors and exceptions handlers
 *
 * @package Core
 */
final class ErrorHandler extends Singleton{

    /**
     * The error handler instance
     */
    protected static $instance;

    /**
     * Handler an error
     *
     * @param int    $no      The error number
     * @param string $str     The error message
     * @param string $file    The file that throwed the error
     * @param int    $line    The line in the file where the error was throwed
     * @param array  $context All the variables in the error context
     */
    public function error($no, $str, $file, $line, $context) {
        if (!(error_reporting() & $no)) {
            // This error code is not in error_reporting
            return;
        }

        switch($no){
            case E_NOTICE :
            case E_USER_NOTICE:
                $level = "info";
                $icon = 'info-circle';
                $title = "PHP Notice";
                App::logger()->notice($str);
                break;

            case E_STRICT :
                $level = "info";
                $icon = 'info-circle';
                $title = "PHP Strict";
                App::logger()->notice($str);
                break;

            case E_DEPRECATED :
            case E_USER_DEPRECATED :
                $level = "info";
                $icon = 'info-circle';
                $title = "PHP Deprecated";
                App::logger()->notice($str);
                break;

            case E_USER_WARNING :
            case E_WARNING :
                $level = "warning";
                $icon = "exclamation-triangle";
                $title = "PHP Warning";
                App::logger()->warning($str);
                break;

            default:
                $level = "danger";
                $icon = "exclamation-circle";
                $title = "PHP Error";
                App::logger()->error($str);
                break;
        }

        $param = array(
            'level' => $level,
            'icon' => $icon,
            'title' => $title,
            'message' => $str,
            'trace' => array(
                array(
                    'file' => $file,
                    'line' => $line
                )
            )
        );

        echo View::make(Theme::getSelected()->getView('error.tpl'), $param);
    }

    /**
     * Handle an non catched exception
     *
     * @param Exception $e The throwed exception
     */
    public function exception($e){
        $param = array(
            'level' => 'danger',
            'icon' => 'excalamation-circle',
            'title' => get_class($e),
            'message' => $e->getMessage(),
            'trace' => $e->getTrace()
        );

        App::logger()->error($e->getMessage());
        if(App::request()->getWantedType() === "json") {
            throw new InternalErrorException($e->getMessage());
        }
        else{
            throw new InternalErrorException(View::make(Theme::getSelected()->getView('error.tpl'), $param));
        }

    }

    /**
     * Handle fatal errors
     */
    public function fatalError(){
        $error = error_get_last();

        if($error !== null) {
            $errno   = $error["type"];
            $errfile = $error["file"];
            $errline = $error["line"];
            $errstr  = $error["message"];

            $this->error($errno, $errstr, $errfile, $errline, array());
        }
    }

    /**
     * Start error handler
     */
    public function start() {
        if(ini_get('display_errors')) {
            set_error_handler(array($this, 'error'), error_reporting());
            register_shutdown_function(array($this, 'fatalError'));

            set_exception_handler(array($this, 'exception'));
        }
    }

    /**
     * Manage Http exceptions
     * @param  HTTPException $err The thrown exception
     * @param  Request       $req The HTTP request
     * @param  response      $res The HTTP response
     */
    public function manageHttpError(HTTPException $err, $req, $res) {
        $res->setStatus($err->getStatusCode());

        $response = array(
            'message' => $err->getMessage(),
            'details' => $err->getDetails()
        );

        if($req->getWantedType() === 'json') {
            $res->setContentType('json');
            $res->setBody($response);
        }
        else {
            $res->setBody($response['message']);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.company.model;

public class SongArtist {

    private String artistName;
    private String albumName;
    private int track;

    public String getArtistName() {
        return artistName;
    }

    public void setArtistName(String artistName) {
        this.artistName = artistName;
    }

    public String getAlbumName() {
        return albumName;
    }

    public void setAlbumName(String albumName) {
        this.albumName = albumName;
    }

    public int getTrack() {
        return track;
    }

    public void setTrack(int track) {
        this.track = track;
    }
}


text:
module ImageLibrary
  class ApplicationController < ActionController::Base
    before_filter :image_library_authorize!
  end
end


text:
insert into states(state) values ('one');

insert into categories(category) values ('one');

insert into attachments(attachment) values ('one');

insert into commentaries(commentary) values ('one');

insert into items(commentaries, attachments, category, state, username) values (1, 1, 1, 1, 'first');

insert into rules(rule) values ('one');

insert into roles(role, rule) values ('one', 1);

insert into users(name, item, role) values ('FirstUser' ,1, 1);


text:
class BaseDownload:
    def __init__(self):
        super(BaseDownload, self).__init__();

    def excuteRequest(self, rq):
        pass;


text:
@class DataController;

@protocol DataControllerDelegate
- (void)gotNearData:(NSArray*)arObjects;
- (void)gotAllData:(NSArray*)arObjects;

- (void)gotUpdatedData;

@end

@interface DataController : NSObject <SCNetworkReachabilityDelegate> {
    DBController *dbController;
    SCNetworkReachability *reachability;

    // -- Reachability -- //
    BOOL siteIsReachable;
    int tries;

    BOOL fetching;
}

@property (weak, nonatomic) id <DataControllerDelegate> delegate;

-(void)getNearARObjects:(CLLocationCoordinate2D)coordinates;
-(void)getAllARObjects:(CLLocationCoordinate2D)coordinates;

-(void)fetchUpdatedARObjects;

@end


text:
<form>

<input type="checkbox" id="hold0">
<input type="checkbox" id="hold1">
<input type="checkbox" id="hold2">
<input type="checkbox" id="hold3">
<input type="checkbox" id="hold4">

<input type="button" accesskey="r" value="Roll Dice!" onClick="roll()">
Count:

</form>

row	when	scoring
 score

1's	anytime
 the sum of 1's only.

2's	anytime
 the sum of 2's only.

3's	anytime
 the sum of 3's only.

4's	anytime
 the sum of 4's only.

5's	anytime
 the sum of 5's only.

6's
anytime
 the sum of 6's only.

3 of a kind
 at least 3 dice the same

the total of all dice

4 of a kind
at least 4 dice the same
 the total of all dice

Full house
 3 the same and 2 the same

25

Sm straight
 4 in a row  	  30

Lg straight
 5 in a row
40

Yahtzee
 5 the same
50

Chance
 anytime
 the total of all dice

Total score

<input type="button" value="New Game" onClick="window.location.reload()">


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/vision/v1/web_detection.proto

namespace Google\Cloud\Vision\V1\WebDetection;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Entity deduced from similar images on the Internet.
 *
 * Generated from protobuf message google.cloud.vision.v1.WebDetection.WebEntity
 */
class WebEntity extends \Google\Protobuf\Internal\Message
{
    /**
     * Opaque entity ID.
     *
     * Generated from protobuf field string entity_id = 1;
     */
    private $entity_id = '';
    /**
     * Overall relevancy score for the entity.
     * Not normalized and not comparable across different image queries.
     *
     * Generated from protobuf field float score = 2;
     */
    private $score = 0.0;
    /**
     * Canonical description of the entity, in English.
     *
     * Generated from protobuf field string description = 3;
     */
    private $description = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $entity_id
     *           Opaque entity ID.
     *     @type float $score
     *           Overall relevancy score for the entity.
     *           Not normalized and not comparable across different image queries.
     *     @type string $description
     *           Canonical description of the entity, in English.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Vision\V1\WebDetection::initOnce();
        parent::__construct($data);
    }

    /**
     * Opaque entity ID.
     *
     * Generated from protobuf field string entity_id = 1;
     * @return string
     */
    public function getEntityId()
    {
        return $this->entity_id;
    }

    /**
     * Opaque entity ID.
     *
     * Generated from protobuf field string entity_id = 1;
     * @param string $var
     * @return $this
     */
    public function setEntityId($var)
    {
        GPBUtil::checkString($var, True);
        $this->entity_id = $var;

        return $this;
    }

    /**
     * Overall relevancy score for the entity.
     * Not normalized and not comparable across different image queries.
     *
     * Generated from protobuf field float score = 2;
     * @return float
     */
    public function getScore()
    {
        return $this->score;
    }

    /**
     * Overall relevancy score for the entity.
     * Not normalized and not comparable across different image queries.
     *
     * Generated from protobuf field float score = 2;
     * @param float $var
     * @return $this
     */
    public function setScore($var)
    {
        GPBUtil::checkFloat($var);
        $this->score = $var;

        return $this;
    }

    /**
     * Canonical description of the entity, in English.
     *
     * Generated from protobuf field string description = 3;
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Canonical description of the entity, in English.
     *
     * Generated from protobuf field string description = 3;
     * @param string $var
     * @return $this
     */
    public function setDescription($var)
    {
        GPBUtil::checkString($var, True);
        $this->description = $var;

        return $this;
    }

}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(WebEntity::class, \Google\Cloud\Vision\V1\WebDetection_WebEntity::class);


text:
@implementation UIView (infiniteScrollRemoveAllSubviews)

- (void)is_removeAllSubviews
{
    for (UIView *view in [self.subviews copy])
        [view removeFromSuperview];
}

@end

static UIImage *is_blockFailedImage = 0;
static CGFloat is_infinityScrollingTriggerOffset = 0;

@interface UIScrollView (infiniteScrollingPrivate)

@property (nonatomic, copy) void(^is_topBlock)();
@property (nonatomic, copy) void(^is_bottomBlock)();

@property (nonatomic) BOOL is_topBlockInProgress;
@property (nonatomic) BOOL is_topDisabled;
@property (nonatomic) BOOL is_topUndisablingInProgress;
@property (nonatomic) BOOL is_bottomBlockInProgress;
@property (nonatomic) BOOL is_bottomDisabled;
@property (nonatomic) BOOL is_bottomUndisablingInProgress;

@property (nonatomic) NSValue *is_contentSize;
@property (nonatomic) NSValue *is_contentInset;

@property (nonatomic) UIView *is_topBox;
@property (nonatomic) UIView *is_bottomBox;

@end

//--------------------------------------------------------------------------------------------------------------------------------------------

@implementation UIScrollView (infiniteScrollingPrivate)
@dynamic is_topBlock, is_topBlockInProgress, is_topDisabled, is_topBox, is_topUndisablingInProgress;
@dynamic is_bottomBlock, is_bottomBlockInProgress, is_bottomDisabled, is_bottomBox, is_bottomUndisablingInProgress;
@dynamic is_contentSize, is_contentInset;
@end

//--------------------------------------------------------------------------------------------------------------------------------------------

@implementation UIScrollView (infiniteScrolling)
@dynamic infiniteScrollingCustomView, infiniteScrollingCustomFailedView;
@dynamic infiniteScrollingDisabled, infiniteScrollingBlockFailed, infinityScrollingTriggerOffset;
@dynamic topInfiniteScrollingCustomView, topInfiniteScrollingCustomFailedView;
@dynamic bottomInfiniteScrollingCustomView, bottomInfiniteScrollingCustomFailedView;

+ (void)setInfinityScrollingCustomBlockFailedImage:(UIImage *)image
{
    is_blockFailedImage = image;
}

+ (void)setInfinityScrollingTriggerOffset:(CGFloat)triggerOffset
{
    is_infinityScrollingTriggerOffset = triggerOffset;
}

- (UIView *)is_createDefaultInfiniteScrollingView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    view.backgroundColor = [UIColor clearColor];
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activity.center = view.center;
    [activity startAnimating];
    [view addSubview:activity];
    return view;
}

- (void)addTopInfiniteScrollingWithActionHandler:(void (^)())actonHandler
{
    self.is_topBlock = actonHandler;

    if (!self.topInfiniteScrollingCustomView)
        self.topInfiniteScrollingCustomView = self.infiniteScrollingCustomView ?: [self is_createDefaultInfiniteScrollingView];
    if (!self.infiniteScrollingCustomView)
        self.infiniteScrollingCustomView = self.topInfiniteScrollingCustomView;
    if (!self.is_topBox)
        self.is_topBox = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.topInfiniteScrollingCustomView.height)];

    [self.is_topBox is_removeAllSubviews];

    [self addView:self.topInfiniteScrollingCustomView toView:self.is_topBox];
}

- (void)addBottomInfiniteScrollingWithActionHandler:(void (^)())actonHandler
{
    self.is_bottomBlock = actonHandler;

    if (!self.bottomInfiniteScrollingCustomView)
        self.bottomInfiniteScrollingCustomView = self.infiniteScrollingCustomView ?: [self is_createDefaultInfiniteScrollingView];
    if (!self.infiniteScrollingCustomView)
        self.infiniteScrollingCustomView = self.bottomInfiniteScrollingCustomView;
    if (!self.is_bottomBox)
        self.is_bottomBox = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.bottomInfiniteScrollingCustomView.height)];

    [self.is_bottomBox is_removeAllSubviews];

    [self addView:self.bottomInfiniteScrollingCustomView toView:self.is_bottomBox];
}

//---------------------------------------------------------------------------------------------------------

+ (void)load
{
    [self jr_swizzleMethod:@selector(setContentOffset:) withMethod:@selector(is_setContentOffset:) error:nil];
    [self jr_swizzleMethod:@selector(setContentSize:) withMethod:@selector(is_setContentSize:) error:nil];
    [self jr_swizzleMethod:@selector(contentSize) withMethod:@selector(is_ContentSize) error:nil];
    [self jr_swizzleMethod:@selector(setContentInset:) withMethod:@selector(is_setContentInset:) error:nil];
    [self jr_swizzleMethod:@selector(contentInset) withMethod:@selector(is_ContentInset) error:nil];
}

- (void)infiniteScrollViewContentUpdated
{
    self.is_topBlockInProgress = NO;
    self.is_bottomBlockInProgress = NO;
}

- (CGFloat)is_infinityScrollingTriggerOffset
{
    return self.infinityScrollingTriggerOffset ?: (is_infinityScrollingTriggerOffset ?: self.height);
}

- (BOOL)is_checkContentOffset:(BOOL *)top
{
    if ([self is_checkForEmptyContent])
        return NO;
    CGFloat infinityScrollingTriggerOffset = MIN(self.is_infinityScrollingTriggerOffset, self.contentHeight - self.is_infinityScrollingTriggerOffset);
    if (top)
        *top = self.is_topBlock != 0 && self.contentOffsetY < infinityScrollingTriggerOffset;

    return (self.is_bottomBlock != 0 && self.contentOffsetY > self.contentHeight - self.height - infinityScrollingTriggerOffset) ||
    (self.is_topBlock != 0 && self.contentOffsetY < infinityScrollingTriggerOffset);
}

- (BOOL)is_checkForEmptyContent
{
    return (self.height == 0 || self.contentHeight < 1);
}

- (void)is_setContentOffset:(CGPoint)contentOffset
{
    [self is_setContentOffset:contentOffset];
    if (!self.is_topBlock && !self.is_bottomBlock)
        return;
    BOOL blocksEnabled = (self.is_topBlock != 0 && !self.topInfiniteScrollingDisabled) ||
    (self.is_bottomBlock != 0 && !self.bottomInfiniteScrollingDisabled);
    if (!blocksEnabled)
        return;

    if ([self is_checkForEmptyContent])
        return;

    if ([self is_checkContentOffset:0])
    {
        double delayInSeconds = .05;
        if (self.is_topUndisablingInProgress || self.is_bottomUndisablingInProgress)
            delayInSeconds = .5;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            if (self.is_topUndisablingInProgress || self.is_bottomUndisablingInProgress)
                return;
            BOOL top;
            if (![self is_checkContentOffset:&top])
                return;
            if (top && !self.is_topBlockInProgress && !self.topInfiniteScrollingBlockFailed)
            {
                self.is_topBlockInProgress = YES;
                self.is_topBlock();
            }
            else if (!top && !self.is_bottomBlockInProgress && !self.bottomInfiniteScrollingBlockFailed)
            {
                self.is_bottomBlockInProgress = YES;
                self.is_bottomBlock();
            }
        });
    }
}

- (void)is_setContentInset:(UIEdgeInsets)contentInset
{
    self.is_contentInset = [NSValue valueWithUIEdgeInsets:contentInset];
    [self is_updateContent];
}

- (UIEdgeInsets)is_ContentInset
{
    return [self.is_contentInset UIEdgeInsetsValue];
}

- (void)is_setContentSize:(CGSize)contentSize
{
    self.is_contentSize = [NSValue valueWithCGSize:contentSize];
    [self is_updateContent];
}

- (CGSize)is_ContentSize
{
    return [self.is_contentSize CGSizeValue];
}

- (void)is_updateContent
{
    CGSize contentSize = [self.is_contentSize CGSizeValue];
    UIEdgeInsets contentInset = [self.is_contentInset UIEdgeInsetsValue];

    BOOL topISViewVisible = self.is_topBlock != 0 && !self.topInfiniteScrollingDisabled && contentSize.height > self.height;
    BOOL bottomISViewVisible = self.is_bottomBlock != 0 && !self.bottomInfiniteScrollingDisabled && contentSize.height > self.height;

    if (topISViewVisible)
    {
        contentInset.top += self.is_topBox.height;

        if (!self.is_topBox.superview)
            [self addSubview:self.is_topBox];
        self.is_topBox.maxY = 0;
    }
    else
    {
        if (self.is_topBox.superview)
            [self.is_topBox removeFromSuperview];
    }

    if (bottomISViewVisible)
    {
        contentSize.height += self.is_bottomBox.height;

        if (!self.is_bottomBox.superview)
            [self addSubview:self.is_bottomBox];
        self.is_bottomBox.maxY = contentSize.height;
    }
    else
    {
        if (self.is_bottomBox.superview)
            [self.is_bottomBox removeFromSuperview];
    }

    [self is_setContentSize:contentSize];
    [self is_setContentInset:contentInset];
}

//--------------------------------------------------------------------------------------------------------------------------------------------

- (void)setInfiniteScrollingDisabled:(BOOL)infiniteScrollingDisabled
{
    if (self.is_topBlock != 0)
        self.topInfiniteScrollingDisabled = infiniteScrollingDisabled;
    else if (self.is_bottomBlock != 0)
        self.bottomInfiniteScrollingDisabled = infiniteScrollingDisabled;
}

- (BOOL)infiniteScrollingDisabled
{
    if (self.is_topBlock != 0)
        return self.topInfiniteScrollingDisabled;
    else if (self.is_bottomBlock != 0)
        return self.bottomInfiniteScrollingDisabled;
    return NO;
}

- (void)setInfiniteScrollingBlockFailed:(BOOL)infiniteScrollingBlockFailed
{
    if (self.is_topBlock != 0)
        self.topInfiniteScrollingBlockFailed = infiniteScrollingBlockFailed;
    else if (self.is_bottomBlock != 0)
        self.bottomInfiniteScrollingBlockFailed = infiniteScrollingBlockFailed;
}

- (BOOL)infiniteScrollingBlockFailed
{
    if (self.is_topBlock != 0)
        return self.topInfiniteScrollingBlockFailed;
    else if (self.is_bottomBlock != 0)
        return self.bottomInfiniteScrollingBlockFailed;
    return NO;
}

//--------------------------------------------------------------------------------------------------------------------------------------------

- (void)setTopInfiniteScrollingDisabled:(BOOL)topInfiniteScrollingDisabled
{
    if (self.is_topDisabled && !topInfiniteScrollingDisabled)
    {
        self.is_topUndisablingInProgress = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.is_topUndisablingInProgress = NO;
        });
    }
    CGFloat contentOffsetY = self.contentOffsetY;
    CGFloat contentHeight = self.contentHeight;
    self.is_topDisabled = topInfiniteScrollingDisabled;
    [self is_updateContent];
    self.contentOffsetY = contentOffsetY + (self.contentHeight - contentHeight);
}

- (BOOL)topInfiniteScrollingDisabled
{
    return self.is_topDisabled;
}

- (void)setBottomInfiniteScrollingDisabled:(BOOL)bottomInfiniteScrollingDisabled
{
    if (self.is_bottomDisabled && !bottomInfiniteScrollingDisabled)
    {
        self.is_bottomUndisablingInProgress = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.is_bottomUndisablingInProgress = NO;
        });
    }
    self.is_bottomDisabled = bottomInfiniteScrollingDisabled;
    [self is_updateContent];
}

- (BOOL)bottomInfiniteScrollingDisabled
{
    return self.is_bottomDisabled;
}

//--------------------------------------------------------------------------------------------------------------------------------------------

- (UIView *)is_createDefaultInfiniteScrollingBlockFailedView:(BOOL)top
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    view.backgroundColor = [UIColor clearColor];
    UIButton *button = [[UIButton alloc] initWithFrame:view.bounds];
    static UIImage *podImage;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSBundle *podBundle = [NSBundle bundleForClass:DPPPropertyAttribute.class];
        podImage = [UIImage imageNamed:@"CCInfiniteScrolling.bundle/infinite_scrolling_reload" inBundle:podBundle compatibleWithTraitCollection:nil];
    });
    [button setImage:is_blockFailedImage ?: podImage forState:UIControlStateNormal];
    [button addTarget:self action:(top ? @selector(topAction) : @selector(bottomAction)) forControlEvents:UIControlEventTouchUpInside];
    [self addView:button toView:view];
    return view;
}

- (void)topAction
{
    self.topInfiniteScrollingBlockFailed = NO;
    self.is_topBlock();
}

- (void)bottomAction
{
    self.bottomInfiniteScrollingBlockFailed = NO;
    self.is_bottomBlock();
}

- (void)addView:(UIView *)viewToAdd toView:(UIView *)superview
{
    [superview is_removeAllSubviews];
    viewToAdd.translatesAutoresizingMaskIntoConstraints = YES;
    viewToAdd.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    viewToAdd.xCenter = superview.width / 2;
    [superview addSubview:viewToAdd];
}

- (void)setTopInfiniteScrollingBlockFailed:(BOOL)topInfiniteScrollingBlockFailed
{
    if (!self.topInfiniteScrollingCustomFailedView)
        self.topInfiniteScrollingCustomFailedView = (self.infiniteScrollingCustomFailedView && self.infiniteScrollingCustomFailedView != self.bottomInfiniteScrollingCustomFailedView) ? self.infiniteScrollingCustomFailedView : [self is_createDefaultInfiniteScrollingBlockFailedView:YES];
    if (!self.infiniteScrollingCustomFailedView)
        self.infiniteScrollingCustomFailedView = self.topInfiniteScrollingCustomFailedView;
    [self addView:topInfiniteScrollingBlockFailed ? self.topInfiniteScrollingCustomFailedView : self.topInfiniteScrollingCustomView toView:self.is_topBox];
}

- (BOOL)topInfiniteScrollingBlockFailed
{
    return [self.is_topBox subviews].count && [self.is_topBox subviews][0] == self.topInfiniteScrollingCustomFailedView;
}

- (void)setBottomInfiniteScrollingBlockFailed:(BOOL)bottomInfiniteScrollingBlockFailed
{
    if (!self.bottomInfiniteScrollingCustomFailedView)
        self.bottomInfiniteScrollingCustomFailedView = (self.infiniteScrollingCustomFailedView && self.infiniteScrollingCustomFailedView != self.topInfiniteScrollingCustomFailedView) ? self.infiniteScrollingCustomFailedView : [self is_createDefaultInfiniteScrollingBlockFailedView:NO];
    if (!self.infiniteScrollingCustomFailedView)
        self.infiniteScrollingCustomFailedView = self.bottomInfiniteScrollingCustomFailedView;
    [self addView:bottomInfiniteScrollingBlockFailed ? self.bottomInfiniteScrollingCustomFailedView : self.bottomInfiniteScrollingCustomView toView:self.is_bottomBox];
}

- (BOOL)bottomInfiniteScrollingBlockFailed
{
    return [self.is_bottomBox subviews].count && [self.is_bottomBox subviews][0] == self.bottomInfiniteScrollingCustomFailedView;
}

//--------------------------------------------------------------------------------------------------------------------------------------------

- (void)scrollToBottom
{
    self.contentOffsetY = MAX(-self.contentInsetTop, self.contentInsetBottom + self.contentHeight - self.height);
}

@end

@implementation UITableView (infiniteScrollingHelper)

+ (void)load
{
    [self jr_swizzleMethod:@selector(reloadData) withMethod:@selector(is_reloadData) error:nil];
}

- (void)is_reloadData
{
    [self is_reloadData];
    [self infiniteScrollViewContentUpdated];
}

- (void)reloadDataKeepBottomOffset
{
    CGFloat contentOffsetY = self.contentOffsetY;
    CGFloat contentHeight = self.contentHeight;
    [self reloadData];
    self.contentOffsetY = contentOffsetY + (self.contentHeight - contentHeight);
}

@end

@implementation UICollectionView (infiniteScrollingHelper)

+ (void)load
{
    [self jr_swizzleMethod:@selector(reloadData) withMethod:@selector(is_reloadData) error:nil];
}

- (void)is_reloadData
{
    [self is_reloadData];
    [self infiniteScrollViewContentUpdated];
}

- (void)reloadDataKeepBottomOffset
{
    CGFloat contentOffsetY = self.contentOffsetY;
    CGFloat contentHeight = self.contentHeight;
    [self reloadData];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.contentOffsetY = contentOffsetY + (self.contentHeight - contentHeight);
    });
}

@end


text:
import json
import re
from typing import Any, Callable, Optional

from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import gettext as _

import attr
import jsonfield

import corehq.motech.auth
from corehq.motech.auth import (
    AuthManager,
    BasicAuthManager,
    BearerAuthManager,
    DigestAuthManager,
    OAuth1Manager,
    OAuth2ClientGrantManager,
    OAuth2PasswordGrantManager,
    api_auth_settings_choices,
    oauth1_api_endpoints,
    oauth2_api_settings,
)
from corehq.motech.const import (
    ALGO_AES,
    AUTH_TYPES,
    BASIC_AUTH,
    BEARER_AUTH,
    DIGEST_AUTH,
    OAUTH1,
    OAUTH2_CLIENT,
    OAUTH2_PWD,
    PASSWORD_PLACEHOLDER,
)
from corehq.motech.utils import b64_aes_decrypt, b64_aes_encrypt
from corehq.util import as_json_text, as_text

@attr.s(auto_attribs=True, frozen=True, kw_only=True)
class RequestLogEntry:
    domain: str
    payload_id: str
    method: str
    url: str
    headers: dict
    params: dict
    data: Any
    error: str
    response_status: int
    response_headers: dict
    response_body: str

class ConnectionSoftDeleteManager(models.Manager):

    def get_queryset(self):
        return super().get_queryset().filter(is_deleted=False)

class ConnectionSettings(models.Model):
    """
    Stores the connection details of a remote API.

    Used for DHIS2 aggregated data / DataSet integration. Intended also
    to be used for Repeaters and OpenMRS Importers.
    """
    domain = models.CharField(max_length=126, db_index=True)
    name = models.CharField(max_length=255)
    url = models.CharField(max_length=255)
    auth_type = models.CharField(
        max_length=16, null=True, blank=True,
        choices=(
            (None, "None"),
            *AUTH_TYPES,
        )
    )
    api_auth_settings = models.CharField(
        max_length=64, null=True, blank=True,
        choices=api_auth_settings_choices,
    )
    username = models.CharField(max_length=255, null=True, blank=True)
    password = models.CharField(max_length=255, blank=True)
    # OAuth 2.0 Password Grant needs username, password, client_id & client_secret
    client_id = models.CharField(max_length=255, null=True, blank=True)
    client_secret = models.CharField(max_length=255, blank=True)
    skip_cert_verify = models.BooleanField(default=False)
    token_url = models.CharField(max_length=255, blank=True, null=True)
    refresh_url = models.CharField(max_length=255, blank=True, null=True)
    pass_credentials_in_header = models.BooleanField(default=None, null=True)
    notify_addresses_str = models.CharField(max_length=255, default="")
    # last_token is stored encrypted because it can contain secrets
    last_token_aes = models.TextField(blank=True, default="")
    is_deleted = models.BooleanField(default=False, db_index=True)

    objects = ConnectionSoftDeleteManager()
    all_objects = models.Manager()

    def __str__(self):
        return self.name

    @property
    def plaintext_password(self):
        if self.password.startswith(f'${ALGO_AES}$'):
            ciphertext = self.password.split('$', 2)[2]
            return b64_aes_decrypt(ciphertext)
        return self.password

    @plaintext_password.setter
    def plaintext_password(self, plaintext):
        if plaintext != PASSWORD_PLACEHOLDER:
            ciphertext = b64_aes_encrypt(plaintext)
            self.password = f'${ALGO_AES}${ciphertext}'

    @property
    def plaintext_client_secret(self):
        if self.client_secret.startswith(f'${ALGO_AES}$'):
            ciphertext = self.client_secret.split('$', 2)[2]
            return b64_aes_decrypt(ciphertext)
        return self.client_secret

    @plaintext_client_secret.setter
    def plaintext_client_secret(self, plaintext):
        if plaintext != PASSWORD_PLACEHOLDER:
            ciphertext = b64_aes_encrypt(plaintext)
            self.client_secret = f'${ALGO_AES}${ciphertext}'

    @property
    def last_token(self) -> Optional[dict]:
        if self.last_token_aes:
            plaintext = b64_aes_decrypt(self.last_token_aes)
            return json.loads(plaintext)
        return None

    @last_token.setter
    def last_token(self, token: Optional[dict]):
        if token is None:
            self.last_token_aes = ''
        else:
            plaintext = json.dumps(token)
            self.last_token_aes = b64_aes_encrypt(plaintext)

    @property
    def notify_addresses(self):
        return [addr for addr in re.split('[, ]+', self.notify_addresses_str) if addr]

    def get_requests(
        self,
        payload_id: Optional[str] = None,
        logger: Optional[Callable] = None,
    ):
        from corehq.motech.requests import Requests

        auth_manager = self.get_auth_manager()
        return Requests(
            self.domain,
            self.url,
            verify=not self.skip_cert_verify,
            auth_manager=auth_manager,
            notify_addresses=self.notify_addresses,
            payload_id=payload_id,
            logger=logger,
        )

    def get_auth_manager(self):
        # Auth types that don't require a username:
        if self.auth_type is None:
            return AuthManager()
        if self.auth_type == OAUTH1:
            return OAuth1Manager(
                client_id=self.client_id,
                client_secret=self.plaintext_client_secret,
                api_endpoints=self._get_oauth1_api_endpoints(),
                connection_settings=self,
            )
        if self.auth_type == OAUTH2_CLIENT:
            return OAuth2ClientGrantManager(
                self.url,
                client_id=self.client_id,
                client_secret=self.plaintext_client_secret,
                token_url=self.token_url,
                refresh_url=self.refresh_url,
                connection_settings=self,
            )

        # Auth types that require a username:
        if not isinstance(self.username, str):
            return AuthManager()
        if self.auth_type == BASIC_AUTH:
            return BasicAuthManager(
                self.username,
                self.plaintext_password,
            )
        if self.auth_type == DIGEST_AUTH:
            return DigestAuthManager(
                self.username,
                self.plaintext_password,
            )
        if self.auth_type == BEARER_AUTH:
            return BearerAuthManager(
                self.username,
                self.plaintext_password,
            )
        if self.auth_type == OAUTH2_PWD:
            return OAuth2PasswordGrantManager(
                self.url,
                self.username,
                self.plaintext_password,
                client_id=self.client_id,
                client_secret=self.plaintext_client_secret,
                token_url=self.token_url,
                refresh_url=self.refresh_url,
                pass_credentials_in_header=self.pass_credentials_in_header,
                connection_settings=self,
            )
        raise ValueError(f'Unknown auth type {self.auth_type!r}')

    def _get_oauth1_api_endpoints(self):
        if self.api_auth_settings in dict(oauth1_api_endpoints):
            return getattr(corehq.motech.auth, self.api_auth_settings)
        raise ValueError(_(
            f'Unable to resolve API endpoints {self.api_auth_settings!r}. '
            'Please select the applicable API auth settings for the '
            f'{self.name!r} connection.'
        ))

    @cached_property
    def used_by(self):
        """
        Returns the names of kinds of things that are currently using
        this instance. Used for informing users, and determining whether
        the instance can be deleted.
        """
        from corehq.motech.repeaters.models import Repeater

        kinds = set()
        if self.incrementalexport_set.exists():
            kinds.add(_('Incremental Exports'))
        if self.sqldatasetmap_set.exists():
            kinds.add(_('DHIS2 DataSet Maps'))
        if any(r.connection_settings_id == self.id
                for r in Repeater.by_domain(self.domain)):
            kinds.add(_('Data Forwarding'))

        # TODO: Check OpenmrsImporters (when OpenmrsImporters use ConnectionSettings)

        return kinds

    def soft_delete(self):
        self.is_deleted = True
        self.save()

class RequestLog(models.Model):
    """
    Store API requests and responses to analyse errors and keep an audit trail
    """
    domain = models.CharField(max_length=126, db_index=True)
    timestamp = models.DateTimeField(auto_now_add=True, db_index=True)
    log_level = models.IntegerField(null=True)
    # payload_id is set for requests that are caused by a payload (e.g.
    # a form submission -- in which case payload_id will have the value
    # of XFormInstance.form_id). It also uniquely identifies a Repeat
    # Record, so it can be used to link a Repeat Record with the
    # requests to send its payload.
    payload_id = models.CharField(max_length=126, blank=True, null=True, db_index=True)
    request_method = models.CharField(max_length=12)
    request_url = models.CharField(max_length=255, db_index=True)
    request_headers = jsonfield.JSONField(blank=True)
    request_params = jsonfield.JSONField(blank=True)
    request_body = models.TextField(blank=True, null=True)
    request_error = models.TextField(null=True)
    response_status = models.IntegerField(null=True, db_index=True)
    response_headers = jsonfield.JSONField(blank=True, null=True)
    response_body = models.TextField(blank=True, null=True)

    class Meta:
        db_table = 'dhis2_jsonapilog'

    @staticmethod
    def log(level: int, log_entry: RequestLogEntry):
        return RequestLog.objects.create(
            domain=log_entry.domain,
            log_level=level,
            payload_id=log_entry.payload_id,
            request_method=log_entry.method,
            request_url=log_entry.url,
            request_headers=log_entry.headers,
            request_params=log_entry.params,
            request_body=as_json_text(log_entry.data),
            request_error=log_entry.error,
            response_status=log_entry.response_status,
            response_headers=log_entry.response_headers,
            response_body=as_text(log_entry.response_body),
        )


text:
package org.ayo.fringe.ui.main;

import android.app.Activity;
import android.view.View;

import org.ayo.component.MasterFragment;
import org.ayo.component.indicator.TypicalPageInfo;
import org.ayo.fringe.R;
import org.ayo.fringe.ui.fragment.MMListFragment;
import org.ayo.fringe.ui.prompt.Poper;
import org.ayo.fringe.ui.prompt.TitleBarUtils;
import org.ayo.view.widget.TitleBar;

/**
 * Created by qiaoliang on 2017/9/7.
 */

public class MmListPageProvider implements PageProvider {

    private String title = "私照";

    @Override
    public MasterFragment createFragment(Activity activity) {
        return new MMListFragment();
    }

    @Override
    public void handleTitleBar(final Activity activity, TitleBar titleBar) {
        TitleBarUtils.setTitleBar(titleBar, title);
        titleBar.leftButton(0)
                .clearRightButtons()
                .rightButton(1, R.drawable.ic_add)
                .rightButton(2, R.drawable.ic_more)
                .callback(new TitleBar.Callback() {

                    @Override
                    public void onLeftButtonClicked(View v) {

                    }

                    @Override
                    public void onRightButtonClicked(int index, View v) {
                        if(index == 1){
                            Poper.showCreateSheet(activity);
                        }else if(index == 2){
                        }
                    }
                });
    }

    @Override
    public TypicalPageInfo createTabItemView(Activity activity) {
        TypicalPageInfo itemView = new TypicalPageInfo(R.drawable.typical_ic_weixin_normal, R.drawable.typical_ic_weixin_pressed, title);
        return itemView;
    }
}


text:
/**
 * Toast插件,需要配合css
 */
;(function($){
	$.extend({
		'toast': function(message, type, params){
			//初始化参数
			type = type || 'success';
			params = params || {};
			var settings = {
				'closeButton': true,
				'positionClass': 'toast-top-right',
				'timeOut': 5000,//为0则不自动消失
				'click': ''
			};
			for(var key in params){
				settings[key] = params[key];
			}

			//如果div不存在,则插入div
			if(!$('.toast-container.' + settings.positionClass).length){
				$('body').append('

');
			}

			var $container = $('.toast-container.' + settings.positionClass);

			$container.append(['
',
				(function(){
					if(settings.closeButton){
						return '×';
					}else{
						return '';
					}
				}()),
				'
', message, '
',
			'
'].join(''));

			var $message = $container.find('.toast:last');

			if(settings.timeOut){
				var timeout = setTimeout((function($message){
					return function(){
						$message.fadeOut(function(){
							$(this).remove();
						});
					}
				})($message), settings.timeOut);

				$message.on('mouseover', function(){
					clearTimeout(timeout);
				}).on('mouseout', function(){
					timeout = setTimeout((function($message){
						return function(){
							$message.fadeOut(function(){
								$(this).remove();
							});
						}
					})($message), settings.timeOut);
				});
			}

			if(settings.closeButton){
				$message.find('.toast-close-link').on('click', function(){
					$(this).parent().fadeOut(function(){
						$(this).remove();
					});
				});
			}

			if(settings.click){
				$message.on('click', function(){
					if(typeof settings.click == 'function'){
						settings.click($(this));
					}else if(settings.click == 'hide' || settings.click == 'remove'){
						$(this).remove();
					}else if(settings.click == 'fadeOut'){
						$(this).fadeOut();
					}
				});
			}
		}
	})
})(jQuery);


text:
from diofant import exp, log, sign
from diofant.abc import x
from diofant.calculus.singularities import singularities

__all__ = ()

def test_singularities():
    assert singularities(x**2, x) == set()
    assert singularities(x/(x**2 + 3*x + 2), x) == {-2, -1}
    assert singularities(1/(1 + x), x) == {-1}
    assert singularities(sign(x), x) == {0}

def test_singularities_non_rational():
    assert singularities(exp(1/x), x) == {0}
    assert singularities(log((x - 2)**2), x) == {2}
    assert singularities(exp(1/x) + log(x + 1), x) == {-1, 0}
    assert singularities(exp(1/log(x + 1)), x) == {0}


text:
package org.dhamma.sg.model;

import java.util.Date;

import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "sessions")
public class Sessions {

    public static final String ID_FIELD = "id";

	@DatabaseField(generatedId = true)
	private int id = -1; // set to -1 to indicate not added to db yet

    public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public static final String ENTRY_FIELD = "entry";
	@DatabaseField
	private String entry; // as entered by user

    public String getEntry() {
		return entry;
	}

	public void setEntry(String entry) {
		this.entry = entry;
	}

	public static final String COMPLETED_FIELD = "completed";
	@DatabaseField(index = true)
	private boolean completed; // whether this is completed (fully completed or paused...)

	 public boolean isCompleted() {
		return completed;
	}

	public void setCompleted(boolean completed) {
		this.completed = completed;
	}

	public static final String DURATION_FIELD = "duration";
	@DatabaseField
	private long duration;

    public long getDuration() {
		return duration;
	}

	public void setDuration(long duration) {
		this.duration = duration;
	}

	public static final String ENTRYDATE_FIELD = "entryDate";
	@DatabaseField(dataType = DataType.DATE_LONG)
	private Date entryDate;

    public Date getEntryDate() {
		return entryDate;
	}

	public void setEntryDate(Date entryDate) {
		this.entryDate = entryDate;
	}

	public static final String UPDATED_FIELD = "updated";
	@DatabaseField(version = true, dataType = DataType.DATE_LONG)
	private Date updated;

	public Date getUpdated() {
		return updated;
	}

	public void setUpdated(Date updated) {
		this.updated = updated;
	}

	@Override
	public String toString(){
		return "Merits" + '@' + Integer.toHexString(hashCode()) +
				"[id(" + id + ")][entry(" + entry + ")][isCompleted(" + completed + ")][duration(" + duration + ")][entryDate(" + entryDate + ")][updated(" + updated + ")]";
	}

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.synapse.models;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;

/** Resource collection API of SqlPoolWorkloadGroups. */
public interface SqlPoolWorkloadGroups {
    /**
     * Get a Sql pool's workload group.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param sqlPoolName SQL pool name.
     * @param workloadGroupName The name of the workload group.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a Sql pool's workload group.
     */
    WorkloadGroup get(String resourceGroupName, String workspaceName, String sqlPoolName, String workloadGroupName);

    /**
     * Get a Sql pool's workload group.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param sqlPoolName SQL pool name.
     * @param workloadGroupName The name of the workload group.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a Sql pool's workload group along with {@link Response}.
     */
    Response<WorkloadGroup> getWithResponse(
        String resourceGroupName, String workspaceName, String sqlPoolName, String workloadGroupName, Context context);

    /**
     * Remove Sql pool's workload group.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param sqlPoolName SQL pool name.
     * @param workloadGroupName The name of the workload group.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void delete(String resourceGroupName, String workspaceName, String sqlPoolName, String workloadGroupName);

    /**
     * Remove Sql pool's workload group.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param sqlPoolName SQL pool name.
     * @param workloadGroupName The name of the workload group.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void delete(
        String resourceGroupName, String workspaceName, String sqlPoolName, String workloadGroupName, Context context);

    /**
     * Get list of Sql pool's workload groups.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param sqlPoolName SQL pool name.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of Sql pool's workload groups as paginated response with {@link PagedIterable}.
     */
    PagedIterable<WorkloadGroup> list(String resourceGroupName, String workspaceName, String sqlPoolName);

    /**
     * Get list of Sql pool's workload groups.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param sqlPoolName SQL pool name.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of Sql pool's workload groups as paginated response with {@link PagedIterable}.
     */
    PagedIterable<WorkloadGroup> list(
        String resourceGroupName, String workspaceName, String sqlPoolName, Context context);

    /**
     * Get a Sql pool's workload group.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a Sql pool's workload group along with {@link Response}.
     */
    WorkloadGroup getById(String id);

    /**
     * Get a Sql pool's workload group.
     *
     * @param id the resource ID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a Sql pool's workload group along with {@link Response}.
     */
    Response<WorkloadGroup> getByIdWithResponse(String id, Context context);

    /**
     * Remove Sql pool's workload group.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void deleteById(String id);

    /**
     * Remove Sql pool's workload group.
     *
     * @param id the resource ID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void deleteByIdWithResponse(String id, Context context);

    /**
     * Begins definition for a new WorkloadGroup resource.
     *
     * @param name resource name.
     * @return the first stage of the new WorkloadGroup definition.
     */
    WorkloadGroup.DefinitionStages.Blank define(String name);
}


text:
package May2021GoogLeetcode;

public class _0494TargetSum {

	public static void main(String[] args) {
		System.out.println(findTargetSumWays(new int[] { 1, 1, 1, 1, 1 }, 3));
	}

	public static int findTargetSumWays(int[] nums, int S) {

	}

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: alberto
 * Date: 26/01/15
 * Time: 12:56
 */

namespace IES2Mares\TutoresBundle\Entity;

use Doctrine\ORM\EntityRepository;

class UsuarioRepository extends EntityRepository{

}


text:
`buttons.js` contains the css directly lifted from [Bootstrap](http://getbootstrap.com), and transformed into simple JavaScript objects.

`primaryButton.js` is the equivalent of `btn-primary`. It's just a `button` with new properties merged in.

  1. `npm install`.
  2. `npm run build`.

Goodbye CSS preprocessors.


text:
class AddTypeToDesks < ActiveRecord::Migration
  def change
    add_column :desks, :type, :string, limit: 32
  end
end


text:
from . import notification_settings
from . import employee_work_status
from . import improve_leave
from . import improve_payroll


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Dbus.CodeGenerator
{
    public static partial class Generator
    {
        private static StringBuilder consumeEventImplementation(EventInfo eventInfo)
        {
            if (eventInfo.EventHandlerType == null)
                throw new InvalidOperationException("EventInfo has no handler type");

            var parameters = new List<(string name, DecoderGenerator decoder)>();
            if (eventInfo.EventHandlerType.IsConstructedGenericType)
            {
                var arguments = eventInfo.EventHandlerType.GenericTypeArguments;
                for (var i = 0; i < arguments.Length; ++i)
                {
                    var invocationParameter = "decoded" + i + "_" + eventInfo.Name;
                    var decoder = DecoderGenerator.Create(invocationParameter, arguments[i]);
                    parameters.Add((invocationParameter, decoder));
                }
            }

            var builder = new StringBuilder()
                .Append(@"
        public event ")
                .Append(BuildTypeString(eventInfo.EventHandlerType))
                .Append(" ")
                .Append(eventInfo.Name)
                .AppendLine(";")
             ;

            foreach (var (_, decoder) in parameters)
                builder.Append(decoder.Delegates);

            builder.Append(@"
        private void handle")
                .Append(eventInfo.Name)
                .Append(@"(global::Dbus.Decoder decoder)
        {
            decoder.AssertSignature(""")
                .AppendJoin("", parameters.Select(parameter => parameter.decoder.Signature))
                .Append(@""");")
            ;
            foreach (var (invocationParameter, decoder) in parameters)
                builder.Append(@"
            var ")
                    .Append(invocationParameter)
                    .Append(" = ")
                    .Append(decoder.DelegateName)
                    .Append("(decoder);")
                ;
            builder
                .AppendLine()
                .Append(Indent)
                .Append(eventInfo.Name)
                .Append("?.Invoke(")
                .AppendJoin(", ", parameters.Select(parameter => parameter.name))
                .AppendLine(@");
        }");
            ;

            return builder;
        }
    }
}


text:
cookbook_file '/opt/elastalert/rules/test_rule.yml' do
  source 'rules/test_rule.yml'
  owner 'elastalert'
  group 'elastalert'
  mode '0755'
  action :create
end


text:
import { handleActions } from 'redux-actions';
import { List, Map, OrderedMap} from 'immutable';
import _ from 'lodash';
import moment from 'moment';

export default handleActions({
	GENRES_FETCH: (state, action) => {

		let genres = OrderedMap();

		action.genres.map(genre => {
			genres = genres.set(parseInt(genre.id), genre);
		});

		return {
			...state,
			genres: genres
		}
	}

}, {genres: OrderedMap()});


text:
All my presentations for meetups, powered by [Shower](http://shwr.me).

- [Virtualization for list](./virtualization) [ru]
- [CSS Grid Layout](./css-grid-layout)

---
Licensed under [MIT License](LICENSE.md).


text:
namespace Fixtures.MirrorSequences.Models
{
    using System.Linq;

    public partial class ErrorModel
    {
        /// <summary>
        /// Initializes a new instance of the ErrorModel class.
        /// </summary>
        public ErrorModel() { }

        /// <summary>
        /// Initializes a new instance of the ErrorModel class.
        /// </summary>
        public ErrorModel(int code, string message)
        {
            Code = code;
            Message = message;
        }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "code")]
        public int Code { get; set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "message")]
        public string Message { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Message == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Message");
            }
        }
    }
}


text:
package me.tatarka.support.internal;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;

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

import me.tatarka.support.job.JobInfo;
import me.tatarka.support.job.JobScheduler;
import me.tatarka.support.os.PersistableBundle;

/** @hide */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class JobSchedulerLollipopDelegate extends JobScheduler {
    private Context context;
    private android.app.job.JobScheduler jobScheduler;

    private static JobSchedulerLollipopDelegate INSTANCE;
    public static synchronized JobSchedulerLollipopDelegate getLollipopInstance(Context context) {
        if (INSTANCE == null) INSTANCE = new JobSchedulerLollipopDelegate(context);
        return INSTANCE;
    }

    private JobSchedulerLollipopDelegate(Context context) {
        this.context = context.getApplicationContext();
        jobScheduler = (android.app.job.JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    }

    @Override
    public void cancel(int jobid) {
        jobScheduler.cancel(jobid);
    }

    @Override
    public void cancelAll() {
        jobScheduler.cancelAll();
    }

    @Override
    public List<JobInfo> getAllPendingJobs() {
        List<android.app.job.JobInfo> jobs = jobScheduler.getAllPendingJobs();
        List<JobInfo> result = new ArrayList<JobInfo>(jobs.size());
        for (android.app.job.JobInfo job : jobs) {
            result.add(convertFromJobInfo(job));
        }
        return result;
    }

    @Override
    public int schedule(JobInfo job) {
        return jobScheduler.schedule(convertJobInfo(job));
    }

    private static android.app.job.JobInfo convertJobInfo(JobInfo job) {
        android.app.job.JobInfo.Builder builder = new android.app.job.JobInfo.Builder(job.getId(), job.getService());

        builder.setExtras((android.os.PersistableBundle) job.getExtras().getRealBundle());
        builder.setRequiresCharging(job.isRequireCharging());
        builder.setRequiresDeviceIdle(job.isRequireDeviceIdle());
        builder.setRequiredNetworkType(job.getNetworkType());
        builder.setPersisted(job.isPersisted());

        if (job.getMinLatencyMillis() != 0 && !job.isPeriodic()) {
            builder.setMinimumLatency(job.getMinLatencyMillis());
        }

        if (job.getMaxExecutionDelayMillis() != 0 && !job.isPeriodic()) {
            builder.setOverrideDeadline(job.getMaxExecutionDelayMillis());
        }

        if (job.isPeriodic()) {
            builder.setPeriodic(job.getIntervalMillis());
        }

        if (!job.isRequireDeviceIdle()) {
            builder.setBackoffCriteria(job.getInitialBackoffMillis(), job.getBackoffPolicy());
        }

        return builder.build();
    }

    private static JobInfo convertFromJobInfo(android.app.job.JobInfo job) {
        JobInfo.Builder builder = new JobInfo.Builder(job.getId(), job.getService());

        builder.setExtras(new PersistableBundle(job.getExtras()));
        builder.setRequiresCharging(job.isRequireCharging());
        builder.setRequiresDeviceIdle(job.isRequireDeviceIdle());
        builder.setRequiredNetworkType(job.getNetworkType());
        builder.setPersisted(job.isPersisted());

        if (job.getMinLatencyMillis() != 0 && !job.isPeriodic()) {
            builder.setMinimumLatency(job.getMinLatencyMillis());
        }

        if (job.getMaxExecutionDelayMillis() != 0 && !job.isPeriodic()) {
            builder.setOverrideDeadline(job.getMaxExecutionDelayMillis());
        }

        if (job.isPeriodic()) {
            builder.setPeriodic(job.getIntervalMillis());
        }

        if (!job.isRequireDeviceIdle()) {
            builder.setBackoffCriteria(job.getInitialBackoffMillis(), job.getBackoffPolicy());
        }

        return builder.build();
    }
}


text:
@interface TXCycleCollectionViewCell : UICollectionViewCell

@property (nonatomic,weak) UIImage *placeholderImage;
@property (nonatomic,assign) UIViewContentMode contentMode;
@property (nonatomic,strong) id itemData;

@end


text:
using System;

namespace csMACnz.SeaOrDew
{
    public class CommandError
    {
        public static int DefaultErrorCode { get; set; } = 500;

        public CommandError(string message)
            : this(DefaultErrorCode, message, null)
        {
        }

        public CommandError(string message, Exception ex)
            : this(DefaultErrorCode, message, ex)
        {
        }

        public CommandError(int errorCode, string message)
            : this(errorCode, message, null)
        {
        }

        public CommandError(int errorCode, string message, Exception ex)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                throw new ArgumentException($"`{nameof(message)}` is required. It must not be null or whitespace.", nameof(message));
            }

            ErrorCode = errorCode;
            Message = message;
            Ex = ex;
        }

        public int ErrorCode { get; }
        public string Message { get; }
        public Exception Ex { get; }
    }
}


text:
NSString *const VENTouchLockEnterPasscodeUserDefaultsKeyNumberOfConsecutivePasscodeAttempts = @"VENTouchLockEnterPasscodeUserDefaultsKeyNumberOfConsecutivePasscodeAttempts";

@implementation VENTouchLockEnterPasscodeViewController

#pragma mark - Class Methods

+ (void)resetPasscodeAttemptHistory
{
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    [standardDefaults removeObjectForKey:VENTouchLockEnterPasscodeUserDefaultsKeyNumberOfConsecutivePasscodeAttempts];
    [standardDefaults synchronize];
}

#pragma mark - Instance Methods

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = [self.touchLock appearance].enterPasscodeViewControllerTitle;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.passcodeView.title = [self.touchLock appearance].enterPasscodeInitialLabelText;
}

- (void)enteredPasscode:(NSString *)passcode
{
    [super enteredPasscode:passcode];
    if ([self.touchLock isPasscodeValid:passcode]) {
        [[self class] resetPasscodeAttemptHistory];
        [self finishWithResult:YES animated:YES];
    }
    else {
        [self.passcodeView shakeAndVibrateCompletion:^{
            self.passcodeView.title = [self.touchLock appearance].enterPasscodeIncorrectLabelText;
            [self clearPasscode];
            if ([self parentSplashViewController]) {
                [self recordIncorrectPasscodeAttempt];
            }
        }];

    }
}

- (void)recordIncorrectPasscodeAttempt
{
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    NSUInteger numberOfAttemptsSoFar = [standardDefaults integerForKey:VENTouchLockEnterPasscodeUserDefaultsKeyNumberOfConsecutivePasscodeAttempts];
    numberOfAttemptsSoFar ++;
    [standardDefaults setInteger:numberOfAttemptsSoFar forKey:VENTouchLockEnterPasscodeUserDefaultsKeyNumberOfConsecutivePasscodeAttempts];
    [standardDefaults synchronize];
    if (numberOfAttemptsSoFar >= [self.touchLock passcodeAttemptLimit]) {
        [self callExceededLimitActionBlock];
    }
}

- (void)callExceededLimitActionBlock
{
    [[self parentSplashViewController] dismissWithUnlockSuccess:NO
                                                     unlockType:VENTouchLockSplashViewControllerUnlockTypeNone
                                                       animated:NO];
}

- (VENTouchLockSplashViewController *)parentSplashViewController
{
    VENTouchLockSplashViewController *splashViewController = nil;
    UIViewController *presentingViewController = self.presentingViewController;
    if (self.touchLock.appearance.splashShouldEmbedInNavigationController) {
        UIViewController *rootViewController = ([presentingViewController isKindOfClass:[UINavigationController class]]) ? [((UINavigationController *)presentingViewController).viewControllers firstObject] : nil;
        if ([rootViewController isKindOfClass:[VENTouchLockSplashViewController class]]) {
            splashViewController = (VENTouchLockSplashViewController *)rootViewController;
        }
    }
    else if ([presentingViewController isKindOfClass:[VENTouchLockSplashViewController class]]) {
        splashViewController = (VENTouchLockSplashViewController *)presentingViewController;
    }
    return splashViewController;
}

@end


text:
package cc.bialy.ade;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import bialy.cc.ade.R;

enum FileType {XML, TXT, DB, UNSUPPORTED}

public class FilesExplorerActivity extends AppCompatActivity {

	private ArrayList<MyApplication.MyAppInfo> appInfos;
	private List<MyFile> files;
	private MyFile currentDir;
	private MyFile appDir;
	private ListView filesList;
	private boolean goUpDirIsAvaible = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app_details);

		appInfos = ((MyApplication) getApplicationContext()).getAppInfos();

		appDir = new MyFile(getIntent().getStringExtra("path"));
		currentDir = new MyFile(getIntent().getStringExtra("path"));

		files = lsCmd(currentDir);

		buildLayout();

	}

	private void buildLayout() {
		filesList = (ListView) findViewById(R.id.lv1);

		filesList.setDivider(null);

		filesList.setAdapter(new BaseAdapter() {

			@Override
			public int getCount() {
				return files.size();
			}

			@Override
			public Object getItem(int i) {
				return i;
			}

			@Override
			public long getItemId(int i) {
				return i;
			}

			@Override
			public View getView(int i, View view, ViewGroup viewGroup) {
				if (view == null) {
					LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

					view = inflater.inflate(R.layout.file_row, viewGroup, false);
				}

				if (i == 0 && goUpDirIsAvaible) {
					((TextView) view.findViewById(R.id.fileName)).setText("..");

					return view;
				}

				ImageView icon = (ImageView) view.findViewById(R.id.icon);

				if (files.get(i).isDirectory()) {
					icon.setImageDrawable(getResources().getDrawable(R.drawable.ic_folder_white_24dp));
					icon.setBackgroundResource(R.drawable.light_orange_circle);
				}

				if (files.get(i).isFile()) {
					icon.setImageDrawable(getResources().getDrawable(R.drawable.ic_insert_drive_file_white_24dp));

					if (files.get(i).getFileType() == FileType.XML)
						icon.setBackgroundResource(R.drawable.light_green_circle);

					else if (files.get(i).getFileType() == FileType.DB)
						icon.setBackgroundResource(R.drawable.light_red_circle);

					else if (files.get(i).getFileType() == FileType.TXT)
						icon.setBackgroundResource(R.drawable.dark_gray_circle);

					else
						icon.setBackgroundResource(R.drawable.light_gray_circle);
				}

				TextView fileName = (TextView) view.findViewById(R.id.fileName);
				fileName.setTypeface(((MyApplication) getApplication()).getRobotoRegular());
				fileName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
				fileName.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.appsListTitle));
				fileName.setText(files.get(i).getName());

				return view;
			}

		});

		filesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

				String fileName = files.get(i).getName();

				if (files.get(i).isDirectory()) { //Selected file is dir
					currentDir = new MyFile(files.get(i).getAbsolutePath());
					files = lsCmd(currentDir);

					if (currentDir.getParentFile().getAbsolutePath().toLowerCase().contains(appDir.getPath().toLowerCase())) {
						MyFile tmp = currentDir.getParentFile().getAbsoluteFile();
						tmp.setIsFD(false, true);
						files.add(0, tmp); //up dir
						goUpDirIsAvaible = true;
					} else {
						goUpDirIsAvaible = false;
					}

					((BaseAdapter) filesList.getAdapter()).notifyDataSetChanged();

				} else if (fileName.endsWith(".xml")) { //Selected file isn't dir
					Intent intent = new Intent(getApplicationContext(), XmlEditActivity.class);
					intent.putExtra("path", files.get(i).getAbsolutePath());
					startActivity(intent);

				} else if (fileName.endsWith(".txt")) { //Selected file isn't dir
					Intent intent = new Intent(getApplicationContext(), TxtEditActivity.class);
					intent.putExtra("path", files.get(i).getAbsolutePath());
					startActivity(intent);

				} else if (fileName.endsWith(".db")) {
					Intent intent = new Intent(getApplicationContext(), DataBaseEditActivity.class);
					intent.putExtra("path", files.get(i).getAbsolutePath());
					startActivity(intent);

				} else { //Selected file isn't dir
					Toast.makeText(getApplicationContext(), "Tylko xml, txt i db", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	private List<MyFile> lsCmd(MyFile file) {
		List<MyFile> result = new LinkedList<>();

		try {
			List<String> filesList = BBls(file);
			for (int i = 2; i < filesList.size(); ++i) {
				MyFile tmp = new MyFile(file.getPath() + "/" + filesList.get(i));
				if (filesList.get(i).substring(filesList.get(i).length() - 1, filesList.get(i).length()).equals("/")) {
					tmp.setDirectory(true);
					tmp.setFile(false);
				} else {
					tmp.setDirectory(false);
					tmp.setFile(true);
				}

				result.add(tmp);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		Collections.sort(result, new Comparator<MyFile>() {
			@Override
			public int compare(MyFile a, MyFile b) {
				return a.getName().compareToIgnoreCase(b.getName());
			}
		});

		return result;
	}

	public ArrayList<String> BBls(MyFile file) throws IOException, InterruptedException {

		ArrayList<String> result = new ArrayList<>();

		Process process = Runtime.getRuntime().exec("su");
		OutputStream stdin = process.getOutputStream();
		InputStream stdout = process.getInputStream();

		stdin.write(("busybox ls -ap " + file.getAbsolutePath() + "\n").getBytes());

		//after you exec everything that you want exit shell
		stdin.write("exit\n".getBytes());

		stdin.flush();   //flush stream
		stdin.close(); //close stream

		String line;

		BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
		while ((line = br.readLine()) != null) {
			result.add(line);
		}
		br.close();

		process.waitFor();
		process.destroy();

		return result;
	}

	class MyFile extends File {

		private boolean isDirectory = false;
		private boolean isFile = false;
		private FileType fileType;

		public MyFile(String pathname) {
			super(pathname);
			this.fileType = determineFileType(pathname);
		}

		public FileType getFileType() {
			return fileType;
		}

		public void setIsFD(boolean isFile, boolean isDirectory) {
			this.isFile = isFile;
			this.isDirectory = isDirectory;
		}

		private FileType determineFileType(String path) {

			try {
				String fileName = path.substring(path.lastIndexOf('/'));
				String extension = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
				if (extension.equals(".xml")) return FileType.XML;
				if (extension.equals(".txt")) return FileType.TXT;
				if (extension.equals(".db")) return FileType.DB;

			} catch (StringIndexOutOfBoundsException e) {
				return FileType.UNSUPPORTED;
			}

			return FileType.UNSUPPORTED;
		}

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

		public void setFile(boolean file) {
			isFile = file;
		}

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

		public void setDirectory(boolean directory) {
			isDirectory = directory;
		}

		@Override
		public MyFile getParentFile() {
			return new MyFile(super.getParentFile().getAbsolutePath());
		}

		@Override
		public MyFile getAbsoluteFile() {
			return this;
		}
	}
}