text:
/**
 *
 */
package com.kacofidoo.srm.orm.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author weiwei.cai
 *
 */
@Entity
@Table(name = "srm_permission")
public class Permission implements Serializable {

	private static final long serialVersionUID = 2351298823864846617L;
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;
	@Column(name = "name", length = 30, nullable = false, unique = true)
	private String name;
	@Column(name = "description", length = 300, nullable = true)
	private String description;

	public String getDescription() {
		return description;
	}

	public long getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setDescription(String description) {
		this.description = description;
	}

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

	public void setName(String name) {
		this.name = name;
	}

}


text:
[![Build Status](https://travis-ci.org/myfreecomm/nexaas-async-collector.svg?branch=master)](https://travis-ci.org/myfreecomm/nexaas-async-collector)
[![Test Coverage](https://codeclimate.com/github/myfreecomm/nexaas-async-collector/badges/coverage.svg)](https://codeclimate.com/github/myfreecomm/nexaas-async-collector/coverage)
[![Code Climate](https://codeclimate.com/github/myfreecomm/nexaas-async-collector/badges/gpa.svg)](https://codeclimate.com/github/myfreecomm/nexaas-async-collector)

Agnostic collector and generator of async content for Rails apps. Used in production in a few [Nexaas](www.nexaas.com) systems.

This gems is compatible with Ruby 2.3+ (we do not ensure it works in previous versions) and Rails 3.2+.

## Prerequisites
The prerequisites of this project are:
  - Sidekiq 4+
  - Redis
  - JQuery 1.0+

## Installation
Add this line to your application's Gemfile:

```ruby
gem 'nexaas-async-collector'
```

And then run:

```bash
$ bundle install
```

Or install it yourself as:

```bash
$ gem install nexaas-async-collector
```

## Usage
1) Create the file `config/initializers/nexaas-async-collector.rb` with the following content (edit as you need):

```ruby
  Nexaas::Async::Collector.configure do |config|
    # Your redis URL. The default value will be the value of yout REDIS_URL env var
    config.redis_url = "redis://test.local"

    # The namespace where you want to store you data within Redis
    config.redis_namespace = 'nexaas_async'

    # The name of the sidekiq queue to be used
    config.queue_name = :high_fast

    # The method that returns the user object (or any other object you want. It must respond to id method)
    config.scope = :current_user

    # The parent class of all nexaas-async-collector controller
    config.parent_controller = "::ActionController::Base"

    # The expiration of the data in seconds
    config.expiration = 600
  end
```

2) Add this to your *config/routes.rb* file:

```ruby
Rails.application.routes.draw do
  # ...
  mount Nexaas::Async::Collector::Engine => '/nexaas_async_collect'
  # ...
end
```

3) Use the view helper to do all the process:

```ruby
<%= nexaas_async_collect({
  scope_id: scope.id, # (required) the ID of the scope. It ensures only the scope who requested the data will be able to fetch it
  class_name: ModelService, # (required) name of the class
  class_method: :model_method, # (required) name of the class method responsible to generate data
  args: [arg1, arg2], # (optional) arguments to be passed to class method
  instrumentation_context: 'my.custom.instrumentation', # (optional) context of the instrumentation name. It will generate two instrumentation: 'my.custom.instrumentation.start' and 'my.custom.instrumentation.finish'
  expiration: 180 # (optional) this local expiration will overwrite global expiration for this particular data generation
}) %>
```

### Download file

Instead of rendering text or HTML, you can use `nexaas-async-collect` to generate files, so the user can download it.

If you want to export something to `xls` file, for example:

```ruby
<%= nexaas_async_collect({
  scope_id: scope.id, # (required)
  class_name: ModelService, # (required)
  class_method: :model_method, # (required)
  args: [arg1, arg2], # (optional)
  file: {
    content_type: 'application/vnd.ms-excel', # (required) content type of the file
    name: 'reports', # (required) name of the file
    extension: 'xls' # (require) extension of the file
  }
}) %>
```

This will generate the spinner and it will redirect the user to download the file when it is ready.

## Redis configuration

If you are sharing your Redis server between important information (e.g., Sidekiq data) and temporary information (e.g., `nexaas-async-collector` data), we suggest you to set the [`maxmemory-policy` eviction policy in Redis](https://redis.io/topics/lru-cache) to `volatile-lru` or `volatile-ttl`.

## Contributing
Bug reports and pull requests are welcome on GitHub at [https://github.com/myfreecomm/nexaas-async-collector](https://github.com/myfreecomm/nexaas-async-collector). This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

After downloading the project and install all gems (through `bundler`) don't forget to install appraisal gems dependencies:

```
$ appraisal install
```

This is necessary to test the code in different versions of Ruby and Rails. To run the full suite of tests:

```
$ appraisal rake spec
```

## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

redpajama_set_name: RedPajamaGithub


text:
/*! Penelope v0.0.0 - MIT license */

'use strict';

var _ = require('underscore'),
    clc = require('cli-color');

// formats output as human-friendly text
exports.human = function (metrics, results) {
    var logo = clc.red('PEN') + clc.yellow('EL') + clc.green('OPE') + '-JS' + "\n";
    return logo + _.reduce(metrics, function (str, metric) {
        return str + metric.name + ': ' + results[metric.id] + '\n';
    }, '');
};

// formats output as JSON
exports.json = function (metrics, results) {
    var ids = _.map(metrics, function (metric) {
        return metric.id;
    });
    var obj = _.reduce(ids, function (obj, id) {
        obj[id] = results[id];
        return obj;
    }, {});
    return JSON.stringify(obj, null, 4);
};

exports.csv = function (metrics, results) {
    var lineItems = [];
    _.each(metrics, function (metric) {
        lineItems.push('"' + results[metric.id] + '"');
    });

    return lineItems.join(',');
}


text:
subroutine sort_mat_idx_col_real(mat,col)
  real, intent(in out) :: mat(:,:)
  integer, intent(in) :: col
  real :: vec(size(mat,1))
  integer :: map(size(mat,1))
  if (col > size(mat,2) .or. col < 1) then
     write(error_unit,'("Error: Column number is out of bounds.")')
     stop
  end if
  call SCOPY(size(mat,1), mat(:,col), 1, vec, 1)
  call sort(vec,map)
  call permute(map,mat)
end subroutine sort_mat_idx_col_real


text:
package com.feigdev.fragmentex;

import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.ActionBar;
import android.support.v4.app.FragmentActivity;
import android.widget.ArrayAdapter;

public class FragmentExampleActivity extends FragmentActivity implements ActionBar.OnNavigationListener{
	Point imgSize;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(this, R.array.locations, R.layout.abs__simple_spinner_item);
        list.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        getSupportActionBar().setListNavigationCallbacks(list, this);

    }

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		switch ((int)itemId){
		case 0:
			getSupportFragmentManager()
			.beginTransaction()
			.replace(android.R.id.content, GridFragment.newInstance(itemPosition))
			.commit();
			break;
		case 1:
			getSupportFragmentManager()
			.beginTransaction()
			.replace(android.R.id.content, WebFragment.newInstance(itemPosition))
			.commit();
			break;
		}
		return true;
	}

}


text:
<!DOCTYPE html>

		<title>AudioRange</title>
		<link rel="stylesheet" type="text/css" href="style.css">

AudioRange

AudioRange values are between [-1, 1].


text:
<?php
namespace app\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use Yii;

/**
 * ArticleSearch represents the model behind the search form about `app\models\Article`.
 */
class ArticleSearch extends Article
{
    /**
     * Returns the validation rules for attributes.
     *
     * @return array
     */
    public function rules()
    {
        return [
            [['id', 'user_id', 'status', 'category', 'created_at', 'updated_at'], 'integer'],
            [['title', 'summary', 'content'], 'safe'],
        ];
    }

    /**
     * Returns a list of scenarios and the corresponding active attributes.
     *
     * @return array
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array   $params
     * @param integer $pageSize  The number of results to be displayed per page.
     * @param boolean $published Whether or not articles have to be published.
     *
     * @return ActiveDataProvider
     */
    public function search($params, $pageSize = 3, $published = false)
    {
        $query = Article::find();

        // this means that editor is trying to see articles
        // we will allow him to see published ones and drafts made by him
        if ($published === true)
        {
            $query->where(['status' => Article::STATUS_PUBLISHED]);
            $query->orWhere(['user_id' => Yii::$app->user->id]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort'=> ['defaultOrder' => ['id' => SORT_DESC]],
            'pagination' => [
                'pageSize' => $pageSize,
            ]
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'status' => $this->status,
            'category' => $this->category,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'summary', $this->summary])
            ->andFilterWhere(['like', 'content', $this->content]);

        return $dataProvider;
    }
}


text:
\documentclass[12pt,letterpaper]{report}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{color}
\usepackage{graphicx}
\usepackage[pdftex,bookmarksopen]{hyperref}
\usepackage{rotating}
\hypersetup{pdfauthor={John Sibert}}
\hypersetup{pdfsubject={tagest User's Manual}}
\hypersetup{pdftitle={tagest Users Manual}}
\hypersetup{pdfkeywords={tagest, tagmove, jnigraphics, tag attrition,
ADRM}}
\hypersetup{pdfpagemode=UseThumbs,bookmarksopen=true}

\markright{Sibert \hfil tagest User's Manual\hfil \today}

\newcommand\doublespacing{\baselineskip=1.6\normalbaselineskip}
\newcommand\singlespacing{\baselineskip=1.0\normalbaselineskip}
\renewcommand\deg[1]{$^\circ$#1}
\newcommand\uvD{$(uvD)$}
\newcommand\SD{SEAPODYM}
\newcommand\SDTE{SEAPODYM-TAGEST}
\newcommand\UK{uKfSST}
\newcommand\EK{ensemble Kalman filter}
\newcommand\ADMB{ADModel Builder} \title{\TT\ User's Manual}
\newcommand\help[1]{\color{red}{\it #1 }\normalcolor}
\newcommand\TT{{\tt tagest \& tagmove}}
\newcommand\TE{{\tt tagest}}
\newcommand\TM{{\tt tagmove}}
\newcommand\PAR{{\tt .par}}
\newcommand\TAG{{\tt .tag}}
\newcommand\ADRM{Advection Diffusion Reaction Model}
\newcommand\widebar[1]{\overline{#1}}

\author{
John Sibert\thanks{sibert@hawaii.edu}\\
Joint Institute of Marine and Atmospheric Research\\
University of Hawai'i at Manoa\\
Honolulu, HI  96822 U.S.A.\\[0.125in]
\date{\today}
}

\title{\TT\ User's Manual}

\begin{document}
\begin{titlepage}
\maketitle
\end{titlepage}

%~\clearpage\thispagestyle{empty}
%\begin{abstract}
%\begin{center}\help{Write Me}\end{center}
%\end{abstract}
\clearpage\thispagestyle{empty}
\clearpage\pagestyle{myheadings}
%\doublespacing
\setcounter{page}{1}

\input TagestUserManText

\end{document}


text:
package com.caozeal.practice.inter;

import java.util.Collection;
import java.util.Iterator;

/**
 * 不能同时实现TestCollection,TestCollection2这两个接口,默认方法冲突
 *
创建时间:2019/6/25 13:47
 *
com.writ.practice.inter
 * @author caozhiyong
 * @version 1.0
 */
public class TestCollection3<E> implements TestCollection<E>
//        , TestCollection2<E>
{
    @Override
    public int size() {
        return 0;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public boolean contains(Object o) {
        return false;
    }

    @Override
    public Iterator<E> iterator() {
        return null;
    }

    @Override
    public Object[] toArray() {
        return new Object[0];
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return null;
    }

    @Override
    public boolean add(E e) {
        return false;
    }

    @Override
    public boolean remove(Object o) {
        return false;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return false;
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        return false;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return false;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return false;
    }

    @Override
    public void clear() {

    }
}


text:
package daemon // import "github.com/docker/docker/daemon"

import (
	"github.com/docker/docker/container"
	specs "github.com/opencontainers/runtime-spec/specs-go"
)

func setLinuxDomainname(c *container.Container, s *specs.Spec) {
	// There isn't a field in the OCI for the NIS domainname, but luckily there
	// is a sysctl which has an identical effect to setdomainname(2) so there's
	// no explicit need for runtime support.
	s.Linux.Sysctl = make(map[string]string)
	if c.Config.Domainname != "" {
		s.Linux.Sysctl["kernel.domainname"] = c.Config.Domainname
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <committeeReports />
    <originChamber>House</originChamber>
    <cosponsors />
    <subjects>
      <billSubjects>
        <policyArea>
          <name>Sports and Recreation</name>
        </policyArea>
        <legislativeSubjects>
          <item>
            <name>Athletes</name>
          </item>
          <item>
            <name>Congressional tributes</name>
          </item>
        </legislativeSubjects>
      </billSubjects>
    </subjects>
    <createDate>2017-02-02T05:28:45Z</createDate>
    <notes />
    <actions>
      <item>
        <text>Referred to the House Committee on Financial Services.</text>
        <links />
        <sourceSystem>
          2
          <name>House floor actions</name>
        </sourceSystem>
        <actionCode>H11100</actionCode>
        <committee>
          <systemCode>hsba00</systemCode>
          <name>Financial Services Committee</name>
        </committee>
        <actionDate>2017-02-01</actionDate>
        <type>IntroReferral</type>
      </item>
      <item>
        <text>Sponsor introductory remarks on measure. (CR E122)</text>
        <links>
          <link>
            <url>https://www.congress.gov/congressional-record/volume-163/extensions-of-remarks-section/page/E122</url>
            <name>E122</name>
          </link>
        </links>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionCode>B00100</actionCode>
        <committee />
        <actionDate>2017-02-01</actionDate>
        <type>IntroReferral</type>
      </item>
      <item>
        <text>Introduced in House</text>
        <links />
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionCode>Intro-H</actionCode>
        <committee />
        <actionDate>2017-02-01</actionDate>
        <type>IntroReferral</type>
      </item>
      <item>
        <text>Introduced in House</text>
        <links />
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionCode>1000</actionCode>
        <committee />
        <actionDate>2017-02-01</actionDate>
        <type>IntroReferral</type>
      </item>
      <actionTypeCounts>
        <placeholderTextForB>1</placeholderTextForB>
        <introducedInHouse>1</introducedInHouse>
        <billReferrals>1</billReferrals>
        <introducedInTheHouse>1</introducedInTheHouse>
      </actionTypeCounts>
      <actionByCounts>
        <houseOfRepresentatives>3</houseOfRepresentatives>
      </actionByCounts>
    </actions>
    <billNumber>791</billNumber>
    <sponsors>
      <item>
        <lastName>Carson</lastName>
        <fullName>Rep. Carson, Andre [D-IN-7]</fullName>
        <firstName>Andre</firstName>
        <bioguideId>C001072</bioguideId>
        <middleName />
        <district>7</district>
        <byRequestType />
        <state>IN</state>
        <party>D</party>
        <identifiers>
          <gpoId>7946</gpoId>
          <bioguideId>C001072</bioguideId>
          <lisID>1889</lisID>
        </identifiers>
      </item>
    </sponsors>
    <amendments />
    <policyArea>
      <name>Sports and Recreation</name>
    </policyArea>
    <relatedBills />
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Mr. CARSON of Indiana:H.R. 791.Congress has the power to enact this legislation pursuantto the following:Clause 18 of section 8 of Article I of the Constitution.[Page H878]
]]></constitutionalAuthorityStatementText>
    <recordedVotes />
    <cboCostEstimates />
    <title>To posthumously award a Congressional gold medal to Muhammad Ali, in recognition of his contributions to the Nation.</title>
    <laws />
    <committees>
      <billCommittees>
        <item>
          <systemCode>hsba00</systemCode>
          <subcommittees />
          <activities>
            <item>
              <date>2017-02-01T15:01:00Z</date>
              <name>Referred to</name>
            </item>
          </activities>
          <type>Standing</type>
          <name>Financial Services Committee</name>
          <chamber>House</chamber>
        </item>
      </billCommittees>
    </committees>
    <updateDate>2017-07-08T15:00:10Z</updateDate>
    <summaries>
      <billSummaries>
        <item>
          <actionDesc>Introduced in House</actionDesc>
          <lastSummaryUpdateDate>2017-07-08T14:52:50Z</lastSummaryUpdateDate>
          <name>Introduced in House</name>
          <text><![CDATA[
This bill directs the Speaker of the House of Representatives and the President pro tempore of the Senate to arrange for the posthumous award of a Congressional Gold Medal to Muhammad Ali.
]]></text>
          <actionDate>2017-02-01</actionDate>
          <versionCode>00</versionCode>
          <updateDate>2017-02-01T05:00:00Z</updateDate>
        </item>
      </billSummaries>
    </summaries>
    <introducedDate>2017-02-01</introducedDate>
    <billType>HR</billType>
    <calendarNumbers />
    <titles>
      <item>
        <chamberName />
        <parentTitleType />
        <chamberCode />
        <titleType>Official Title as Introduced</titleType>
        <title>To posthumously award a Congressional gold medal to Muhammad Ali, in recognition of his contributions to the Nation.</title>
      </item>
      <item>
        <chamberName />
        <parentTitleType />
        <chamberCode />
        <titleType>Display Title</titleType>
        <title>To posthumously award a Congressional gold medal to Muhammad Ali, in recognition of his contributions to the Nation.</title>
      </item>
    </titles>
    <version>1.0.0</version>
    <congress>115</congress>
    <latestAction>
      <actionDate>2017-02-01</actionDate>
      <text>Referred to the House Committee on Financial Services.</text>
      <links />
    </latestAction>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
<?php

/**
 * Setup base class
 *
 * @author      @radixmo
 * @since       version 3.01
 * @package     Xerte Online Toolkits
 * @subpackage  Setup
 */
class Setup {

    // Full URL to installation
    public $xot_url = '';
    // DOCUMENT_ROOT 'WITH' trailing slash
    public $root_path = '';

    public function __construct() {
        $this->root_path    = substr(getcwd(), 0, strlen(getcwd()) - 5);

        $http =  $this->getProtocol();

        $this->xot_url = $http . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }

    public function isSecure() {
        return
            (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || $_SERVER['SERVER_PORT'] == 443;
    }

    public function getProtocol()
    {
        return ($this->isSecure() ?  'https://' : 'http://');
    }

    public function getRootPath() {
        // $this->root_path     = str_replace('setup/index.php', '', $_SERVER['SCRIPT_FILENAME']);
        return $this->root_path;
    }

    public function getXotUrl() {

        $this->xot_url = str_replace('setup/', '', $this->xot_url);
        $this->xot_url = str_replace('requirements.php?', '', $this->xot_url);

        return $this->xot_url;
    }
}

class SetupRequirements {

  public static $php_version = '5.2.0';

    static function phpVersion() {
        $check                  = new stdClass();
        $check->version = phpversion();

        // uncomment next line to test a version that fails
        // $check->version = '4.2';

        if (version_compare($check->version, self::$php_version, "<")) {
            $check->passed = false;
            $check->css = 'error';
            $check->message = 'older than ' . self::$php_version . ' ('. $check->version . ')';
        } else {
            $check->passed = true;
            $check->css = 'ok';
            $check->message = ' ' . $check->version . ' - OK';
        }

        return $check;
    }

    static function MysqlCheck() {
        $check                  = new stdClass();
        $check->passed  = false;

        if (extension_loaded ('PDO' ) // returns boolean
            && extension_loaded('pdo_mysql'))
        {
            $check->passed = true;
        }

        // uncomment next line to simulate failure
        // $check->passed = false;

        return $check;
    }

    static function folders($setup = '') {
        $check                  = new stdClass();
        $root                   = dirname($setup);
        $check->folders = array(
            'Root'              => $root,
            'Setup'             => $setup,
            'User files'    => $root . "/USER-FILES",
            'Error log'     => $root . "/error_logs",
            'Import'            => $root . "/import"
        );

        return $check;
    }

    static function fileSystem($path = '') {
        $check                  = new stdClass();
        $check->passed  = false;
        $error_message = 'Please fix by changing the permission to 0777 or
            changing the ownership to the user account that runs the webserver.';

        if (_is_writable($path)) {
            $check->passed = true;
            $check->css = 'ok';
            $check->message = 'OK';
        } else {
            $check->passed = false;
            $check->css = 'error';
            $check->message = $error_message;
        }

        // uncomment next line to simulate failure
        // $check->passed = false;

        return $check;
    }
}

class SetupDatabase {

    public $connection      = '';
    public $settings        = '';
    public $error_msg       = 'Sorry, the attempt to connect to the host
        has failed. MySQL reports the following error -';
    public $debug           = 'No error message defined.';
    public $conn_error      = '';

    public function __construct( $post = array(), $session = array() ) {
        $this->settings = new stdClass();
        $this->settings->database_type     = "mysql";

        if (isset($post['host'])) {
            // On windows connecting to a MySQL server through localhost is extremely slow, as IPv6 is tried first
            // That connection times out, and then IPv4 is used, so use 127.0.0.1 instead of localhost
            if ($post['host'] == 'localhost') {
                $this->settings->database_host = '127.0.0.1';
            } else {
                $this->settings->database_host = $post['host'];
            }
        }

        if (isset($post['database_prefix'])) {
            $this->settings->database_prefix = $post['database_prefix'];
        }

        if (isset($post['username']) && isset($post['password']))
        {
            $this->settings->database_username = $post['username'];
            $this->settings->database_password = $post['password'];
        }

        $this->updateSettings($post, $session);
    }

    private function updateSettings($post, $session) {
        if ( isset($post['type']) ) {
            $this->settings->database_type = $post['type'];
        }

        if ( isset($session['DATABASE_HOST']) ) {
            $this->settings->database_host = $session['DATABASE_HOST'];
        }

        if ( isset($session['DATABASE_NAME']) ) {
            $this->settings->database_name = $session['DATABASE_NAME'];
        }

        if ( isset($session['DATABASE_PREFIX']) ) {
            $this->settings->database_prefix = $session['DATABASE_PREFIX'];
        }

        if ( isset($post['account']) ) {
            $this->settings->database_username = $post['account'];
        }

        if ( isset($post['account']) ) {
            $this->settings->database_password = $post['accountpw'];
        }
    }

    public function getSettings() {
        return $this->settings;
    }

    public function setName( $name = '' ) {
        $this->settings->database_name = $name;
    }

    /**
     * Create PDO connection to the database.
     * @return PDO instance
     * @throws PDOException if it's not setup / working etc.
     */
    public function connect()
    {
        global $xerte_toolkits_site, $dberr;
        /*
         * Try to connect
         */

        $dsn = false;

        if ($xerte_toolkits_site->database_type == 'sqlite') {
            $dsn = "sqlite:{$xerte_toolkits_site->database_location}";
            /* not relevant parameters */
            $xerte_toolkits_site->database_username = null;
            $xerte_toolkits_site->database_password = null;
        }

        if ($dsn == false) {
            // default to MySQL.
            if (isset($xerte_toolkits_site->database_name))
            {
                $dsn = "mysql:dbname={$xerte_toolkits_site->database_name};host={$xerte_toolkits_site->database_host}";
            }
            else if (isset($xerte_toolkits_site->database_host))
            {
                $dsn = "mysql:host={$xerte_toolkits_site->database_host}";
            }
            else
            {
                return false;
            }
        }

        $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);

        try
        {
            $db_connection = new PDO($dsn, $xerte_toolkits_site->database_username, $xerte_toolkits_site->database_password, $options);
        }
        catch(PDOException $e) {
            $this->conn_error = $e->getMessage();
            // _debug("Failed to connect to db: {$e->getMessage()}");
            return false;
        }
        $db_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);

        return $db_connection;
    }

    public function runQuery( $query = false ) {
        return db_query($query);
    }

    static public function getError( $error_msg = '' ) {
        return $error_msg;
    }

    public function create($connection = '', $query = '') {
        // Sets an attribute on the database handle.
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        try {
            // Executes an SQL statement, returning a result set (if any) as a PDOStatement object
            $statement = $connection->query($query);
        }
        catch(PDOException $e) {
            $this->_debug("Failed to connect to db: {$e->getMessage()}");
            return false;
        }

        return true;
    }

    public function _debug( $string = '' ) {
        if ($string) {
            $this->debug = $string;
        }
    }

    public function getDebug() {
        return $this->debug;
    }

    public function getSQL($file = 'basic.sql') {
        $sql = file_get_contents($file);
        // replace database_prefix with placeholder in basic.sql
        if ( $_POST['database_prefix'] != "" ) {
          $sql = str_replace("$",$_POST['database_prefix'],$sql);
        } else {
          // strip database_prefix placeholder from basic.sql
          $sql = str_replace("$","",$sql);
        }

        // replace <databasename> placeholder with database_name in basic.sql
        $sql = str_replace("<databasename>",$_POST['database_name'],$sql);

        return $sql;
    }

    static public function setSession($post, $xerte_toolkits_site) {
        $_SESSION['DATABASE_HOST']      = $xerte_toolkits_site->database_host;
        $_SESSION['DATABASE_NAME']      = $post['database_name'];
        $_SESSION['DATABASE_PREFIX']    = $post['database_prefix'];
        if (isset($post['username']) && isset($post['password']))
        {
            $_SESSION['MYSQL_DBA']          = $post['username'];
            $_SESSION['MYSQL_DBAPASSWORD']  = $post['password'];
        }
    }
}

/**
 * Setup page class
 *
 * @author      @radixmo
 * @since       version 3.01
 * @package     Xerte Online Toolkits
 * @subpackage  Setup
 */
class SetupPage extends Setup {

    protected $login = '';
    protected $page  = array(); // holds page variables

    public function getPage() {
        $this->page['name'] = 'settings'; // default if not logged in
        // $this->login = new ManagementLogin( $this->settings );

        $msg = $this->login->getLoginMessage();
        if ( !empty($msg) ) {
            $this->page['name']          = 'login';
            $this->page['login_message'] = $msg;
        }

        return $this->showPage();
    }

    protected function showPage() {
        $method_name = 'get' . ucwords($this->page['name']) . 'Page';

        if ( method_exists( $this, $method_name) ) {
            // set path to template files
            $this->file_path = $this->settings->root_file_path . '/'
                . $this->settings->php_library_path . '/' . $this->view_path . '/';
            return $this->{$method_name}();
        } else {
            die( "Error: ManagementPage::" . $this->page['name'] . " method does not exist.\n" );
        }
    }

    protected function getLoginPage() {

        $this->page['isAdmin'] = '';

        return $this->pageDisplayHelper();
    }

    protected function getSettingsPage() {

        if (($this->login->getUsername() == $this->settings->admin_username)
            && ($this->login->getPassword() == $this->settings->admin_password)) {

            $_SESSION['toolkits_logon_id'] = "site_administrator";
            $mysql_id = database_connect("management.php database connect success",
                "management.php database connect fail");
            $this->page['isAdmin'] = true;
        } else {
            $this->getLoginPage();
            return;
        }

        return $this->pageDisplayHelper();
    }

    private function pageDisplayHelper() {
        // Set default header branding images
        $this->page['header_img_right'] = 'website_code/images/apereoLogo.png';
        $this->page['header_img_left']  = 'website_code/images/logo.png';

        if (file_exists($this->settings->root_file_path . "branding/logo_right.png")) {
            $this->page['header_img_right'] = 'branding/logo_right.png';
        }

        if (file_exists($this->settings->root_file_path . "branding/logo_left.png")) {
            $this->page['header_img_left'] = 'branding/logo_left.png';
        }

        require_once ( $this->file_path . 'html/' . $this->page['name'] . '.php');
    }
}

// /setup/setup_class_library.php


text:
using ACBr.Net.DFe.Core.Attributes;
using ACBr.Net.DFe.Core.Collection;
using ACBr.Net.DFe.Core.Serializer;
using System.ComponentModel;
using System.Linq;
using ACBr.Net.Core.Generics;

namespace ACBr.Net.Sat
{
    /// <summary>
    /// Class CFeInfAdic. This class cannot be inherited.
    /// </summary>
    public sealed class CFeInfAdic : DFeParentItem<CFeInfAdic, CFe>, INotifyPropertyChanged
    {
        #region Events

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion Events

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="CFeInfAdic"/> class.
        /// </summary>
        public CFeInfAdic()
        {
            ObsFisco = new DFeCollection<CFeObsFisco>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CFeInfAdic"/> class.
        /// </summary>
        public CFeInfAdic(CFe parent) : this()
        {
            Parent = parent;
        }

        #endregion Constructors

        #region Propriedades

        /// <summary>
        /// Gets or sets the inf CPL.
        /// </summary>
        /// <value>The inf CPL.</value>
        [DFeElement(TipoCampo.Str, "infCpl", Id = "Z02", Min = 1, Max = 5000, Ocorrencia = Ocorrencia.NaoObrigatoria)]
        public string InfCpl { get; set; }

        /// <summary>
        /// Gets or sets the obs fisco.
        /// </summary>
        /// <value>The obs fisco.</value>
        [DFeCollection("obsFisco", Id = "Z03", MinSize = 0, MaxSize = 10, Ocorrencia = Ocorrencia.NaoObrigatoria)]
        public DFeCollection<CFeObsFisco> ObsFisco { get; set; }

        #endregion Propriedades

        #region Methods

        private bool ShouldSerializeObsFisco()
        {
            return Parent.InfCFe.Versao < 0.08M && ObsFisco.Any();
        }

        #endregion Methods
    }
}


text:
SCM

Marketing

Domestic Marketing

Domestic Marketing

                        <a class="list-group-item active" href="<?= base_url()?>marketing">Domestic Marketing
                        <a class="list-group-item" href="<?= base_url()?>marketing/im">International Market
                        <a class="list-group-item" href="<?= base_url()?>marketing/s">Standard
                        <a class="list-group-item" href="<?= base_url()?>marketing/fi">Food Industry (Processed Food)
                        <a class="list-group-item" href="<?= base_url()?>marketing/pi">Promoting the Industry

Beef

Soybean

Milk

Sugar

Bulog is ready to stabilize the beef price hikes through market operations. Bulog use the remaining stock of four thousand head of cattle to market operations in 2016. Market operations focused on areas of Jakarta and its surroundings. The reason, 70 percent of the national consumption of beef is in Jakarta. And the Capital region is considered to be the most affected by the price hikes than other regions. Market operations is intended to lower the price of beef after the last spike in prices due to charge VAT policy cow.

In the operation of the market, Bulog sell cattle at a price of Rp. 40,000 – 41,000 per kilogram of live cattle. In the form of carcasses, beef prices was Rp. 82,000 per kilogram. So at the consumer level, Bulog beef prices are around Rp. 100,000 per kilogram.

Soybean prices tend to increase. At the level of processing industry, commodity prices have touched Rp. 9,000-12,000 per kilogram. Higher than the normal price Rp. 7,000-8,000 per kilogram. The price increase is considered as the effect of the weakening of the rupiah against the US dollar. Soybean imports have affected prices in the market.

Ministry of Agriculture said the Indonesian soy consumption in 2012 reached 2.5 million tons. In fact, the soybean production in the country averaged only 700-800 thousand tons per year. Conditions then it would trigger a number of tofu and tempe production strike. In addition, the market share by four to five major private suppliers can make prices soar. Market domination by a small group of traders (oligopolies) and the practice of cartel is already a fact in soybean market.

Director of Business Development and Investment Ministry of Agriculture Jamil Musanif said that until now the national cow's milk needs greater than domestic production capacity.

The demand has reached 6 million liters of milk per day, whereas the national production capacity is 1.5 million liters per day. The same thing is said Alim Iqbal, the head of the Directorate of Dairy Cattle and Buffalo Cultivation Livestock Ministry of Agriculture, which revealed that 80 per cent of national milk demand can be fulfilled by imports.

Indonesia will potentially become the world sugar producers for support agro-ecosystem, land, labor. Besides, the prospect of the

                                sugar market in Indonesia is promising with a consumption of 4.2 - 4,7juta ton/yr. Sugar is one of the basic needs for the community

                                and the industry is still continuing to be a problem due to lack of domestic production, while needs continue to increase. Some sugar

                                mills are located in Java, technical relatively old age, so less productive, almost all sugar factories is highly dependent on sugarcane

                                farmers and the limited land on the island of Java. While refined sugar factories which there is as yet produce optimally (capacity

                                utilization of about 40% - 60% in 2008). The rapid development of sugar while increasing production needs relatively not balanced to

                                make Indonesia as an importer of sugar both for raw crystal sugar (raw sugar) as well as industrial sugar (refined sugar). The

                                development of the sugar industry (sugar cane processing) must be integrated from plantations, processing, marketing and

                                distributions supported by stakeholders, including supporting agencies such as R & D, human resources, finance / banking and

                                transport


text:
import './index.css'; // apply styling
import Promise from 'promise-polyfill'; //promise polyfill
import 'whatwg-fetch'; //fetch polyfill

import './app'; // run app

if (!window.Promise) {
    window.Promise = Promise;
}


text:
#if WITH_EDITOR

#include "IDetailCustomization.h"
#include "IPropertyTypeCustomization.h"
#include "PropertyHandle.h"

namespace rs2 { class device_list; }

class FRealSenseDetailCustomization
{
public:
	static void Register();
	static void Unregister();
};

class FRealSenseInspectorCustomization : public IDetailCustomization
{
public:
	static TSharedRef<IDetailCustomization> MakeInstance();

	FRealSenseInspectorCustomization();
	virtual void CustomizeDetails(class IDetailLayoutBuilder& DetailLayout) override;

private:
	void UpdateDevices();
	bool PickFile(FString& OutPath, const void* ParentWindow, const FString& Title, const FString& Filter, bool SaveFlag = false);

	IDetailLayoutBuilder* DetailLayoutPtr;
	TUniquePtr<class rs2::device_list> RsDevices;
	TMap<FString, float> ValueCache;
};

#endif // WITH_EDITOR


text:
from datetime import datetime
import os
import signal
import sys
import traceback

from gunicorn import util
from gunicorn.workers.workertmp import WorkerTmp
from gunicorn.http.errors import InvalidHeader, InvalidHeaderName, \
InvalidRequestLine, InvalidRequestMethod, InvalidHTTPVersion, \
LimitRequestLine, LimitRequestHeaders
from gunicorn.http.errors import InvalidProxyLine, ForbiddenProxyRequest
from gunicorn.http.wsgi import default_environ, Response
from gunicorn.six import MAXSIZE

class Worker(object):

    SIGNALS = [getattr(signal, "SIG%s" % x) \
            for x in "HUP QUIT INT TERM USR1 USR2 WINCH CHLD".split()]

    PIPE = []

    def __init__(self, age, ppid, sockets, app, timeout, cfg, log):
        """\
        This is called pre-fork so it shouldn't do anything to the
        current process. If there's a need to make process wide
        changes you'll want to do that in ``self.init_process()``.
        """
        self.age = age
        self.ppid = ppid
        self.sockets = sockets
        self.app = app
        self.timeout = timeout
        self.cfg = cfg
        self.booted = False

        self.nr = 0
        self.max_requests = cfg.max_requests or MAXSIZE
        self.alive = True
        self.log = log
        self.debug = cfg.debug
        self.tmp = WorkerTmp(cfg)

    def __str__(self):
        return "<Worker %s>" % self.pid

    @property
    def pid(self):
        return os.getpid()

    def notify(self):
        """\
        Your worker subclass must arrange to have this method called
        once every ``self.timeout`` seconds. If you fail in accomplishing
        this task, the master process will murder your workers.
        """
        self.tmp.notify()

    def run(self):
        """\
        This is the mainloop of a worker process. You should override
        this method in a subclass to provide the intended behaviour
        for your particular evil schemes.
        """
        raise NotImplementedError()

    def init_process(self):
        """\
        If you override this method in a subclass, the last statement
        in the function should be to call this method with
        super(MyWorkerClass, self).init_process() so that the ``run()``
        loop is initiated.
        """

        # set enviroment' variables
        if self.cfg.env:
            for k, v in self.cfg.env.items():
                os.environ[k] = v

        util.set_owner_process(self.cfg.uid, self.cfg.gid)

        # Reseed the random number generator
        util.seed()

        # For waking ourselves up
        self.PIPE = os.pipe()
        for p in self.PIPE:
            util.set_non_blocking(p)
            util.close_on_exec(p)

        # Prevent fd inherientence
        [util.close_on_exec(s) for s in self.sockets]
        util.close_on_exec(self.tmp.fileno())

        self.log.close_on_exec()

        self.init_signals()

        self.wsgi = self.app.wsgi()

        self.cfg.post_worker_init(self)

        # Enter main run loop
        self.booted = True
        self.run()

    def init_signals(self):
        # reset signaling
        [signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS]
        # init new signaling
        signal.signal(signal.SIGQUIT, self.handle_quit)
        signal.signal(signal.SIGTERM, self.handle_exit)
        signal.signal(signal.SIGINT, self.handle_exit)
        signal.signal(signal.SIGWINCH, self.handle_winch)
        signal.signal(signal.SIGUSR1, self.handle_usr1)
        # Don't let SIGQUIT and SIGUSR1 disturb active requests
        # by interrupting system calls
        if hasattr(signal, 'siginterrupt'):  # python >= 2.6
            signal.siginterrupt(signal.SIGQUIT, False)
            signal.siginterrupt(signal.SIGUSR1, False)

    def handle_usr1(self, sig, frame):
        self.log.reopen_files()

    def handle_quit(self, sig, frame):
        self.alive = False

    def handle_exit(self, sig, frame):
        self.alive = False
        sys.exit(0)

    def handle_error(self, req, client, addr, exc):
        request_start = datetime.now()
        addr = addr or ('', -1)  # unix socket case
        if isinstance(exc, (InvalidRequestLine, InvalidRequestMethod,
            InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,
            LimitRequestLine, LimitRequestHeaders,
            InvalidProxyLine, ForbiddenProxyRequest,)):

            status_int = 400
            reason = "Bad Request"

            if isinstance(exc, InvalidRequestLine):
                mesg = "
Invalid Request Line '%s'
" % str(exc)
            elif isinstance(exc, InvalidRequestMethod):
                mesg = "
Invalid Method '%s'
" % str(exc)
            elif isinstance(exc, InvalidHTTPVersion):
                mesg = "
Invalid HTTP Version '%s'
" % str(exc)
            elif isinstance(exc, (InvalidHeaderName, InvalidHeader,)):
                mesg = "
%s
" % str(exc)
                if not req and hasattr(exc, "req"):
                    req = exc.req  # for access log
            elif isinstance(exc, LimitRequestLine):
                mesg = "
%s
" % str(exc)
            elif isinstance(exc, LimitRequestHeaders):
                mesg = "
Error parsing headers: '%s'
" % str(exc)
            elif isinstance(exc, InvalidProxyLine):
                mesg = "
'%s'
" % str(exc)
            elif isinstance(exc, ForbiddenProxyRequest):
                reason = "Forbidden"
                mesg = "
Request forbidden
"
                status_int = 403

            self.log.debug("Invalid request from ip={ip}: {error}"\
                           "".format(ip=addr[0],
                                     error=str(exc),
                                    )
                          )
        else:
            self.log.exception("Error handling request")

            status_int = 500
            reason = "Internal Server Error"
            mesg = ""

        if req is not None:
            request_time = datetime.now() - request_start
            environ = default_environ(req, client, self.cfg)
            environ['REMOTE_ADDR'] = addr[0]
            environ['REMOTE_PORT'] = str(addr[1])
            resp = Response(req, client, self.cfg)
            resp.status = "%s %s" % (status_int, reason)
            resp.response_length = len(mesg)
            self.log.access(resp, req, environ, request_time)

        if self.debug:
            tb = traceback.format_exc()
            mesg += "
Traceback:
\n
%s
" % tb

        try:
            util.write_error(client, status_int, reason, mesg)
        except:
            self.log.debug("Failed to send error message.")

    def handle_winch(self, sig, fname):
        # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD.
        return


text:
<?php
namespace Concrete\Core\Entity\Attribute;

use Concrete\Core\Attribute\View;
use Concrete\Core\Entity\PackageTrait;
use Concrete\Core\Export\ExportableInterface;
use Concrete\Core\Export\Item\AttributeType;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="AttributeTypes", indexes={@ORM\Index(name="pkgID", columns={"pkgID", "atID"})})
 */
class Type implements ExportableInterface
{
    use PackageTrait;

    protected $controller;

    public function __construct()
    {
        $this->categories = new ArrayCollection();
    }

    /**
     * @ORM\Id @ORM\Column(type="integer", options={"unsigned":true})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $atID;

    /**
     * @ORM\Column(type="string", unique=true)
     */
    protected $atHandle;

    /**
     * @ORM\ManyToMany(targetEntity="Category", mappedBy="types")
     */
    protected $categories;

    /**
     * @ORM\Column(type="string")
     */
    protected $atName;

    /**
     * @return mixed
     */
    public function getAttributeTypeID()
    {
        return $this->atID;
    }

    /**
     * @return mixed
     */
    public function getAttributeTypeHandle()
    {
        return $this->atHandle;
    }

    /**
     * @param mixed $atHandle
     */
    public function setAttributeTypeHandle($atHandle)
    {
        $this->atHandle = $atHandle;
    }

    /**
     * @return mixed
     */
    public function getAttributeTypeName()
    {
        return $this->atName;
    }

    /**
     * @param mixed $atName
     */
    public function setAttributeTypeName($atName)
    {
        $this->atName = $atName;
    }

    /**
     * @return mixed
     */
    public function getAttributeCategories()
    {
        return $this->categories;
    }

    /**
     * @param mixed $categories
     */
    public function setAttributeCategories($categories)
    {
        $this->categories = $categories;
    }

    public function isAssociatedWithCategory(Category $category)
    {
        return $this->categories->contains($category);
    }

    public function getAttributeTypeDisplayName($format = 'html')
    {
        $value = tc('AttributeTypeName', $this->getAttributeTypeName());
        switch ($format) {
            case 'html':
                return h($value);
            case 'text':
            default:
                return $value;
        }
    }

    public function getExporter()
    {
        return new AttributeType();
    }

    public function getController()
    {
        // Note, you can't cache this against the type class itself –it needs to return
        // a new instance every time because sometimes attribute specific keys get
        // bound to the controller and then if it caches against type the wrong controller
        // key combination gets returned with this call.
        //if (!isset($this->controller)) {
        $env = \Environment::get();
        $r = $env->getRecord(DIRNAME_ATTRIBUTES . '/' . $this->atHandle . '/' . FILENAME_CONTROLLER);
        $prefix = $r->override ? true : $this->getPackageHandle();
        $atHandle = \Core::make('helper/text')->camelcase($this->atHandle);
        $class = core_class('Attribute\\' . $atHandle . '\\Controller', $prefix);
        $controller = \Core::make($class);
        $controller->setAttributeType($this);
        return $controller;
    }

    /**
     * @deprecated
     */
    public function render($view, $ak = false, $value = false, $return = false)
    {
        // local scope
        if ($value) {
            $av = new View($value);
        } else {
            if ($ak) {
                $av = new View($ak);
            } else {
                $av = new View($this);
            }
        }
        ob_start();
        $av->render($view);
        $contents = ob_get_contents();
        ob_end_clean();
        if ($return) {
            return $contents;
        } else {
            echo $contents;
        }
    }

    /**
     * @deprecated
     * You shouldnt have to call this, the package uninstaller itself will take care of this
     */
    public function delete()
    {
        $em = \Database::connection()->getEntityManager();
        $em->remove($this);
        $em->flush();
    }

}


text:
package com.crazyhitty.chdev.ks.munch.article;

import com.crazyhitty.chdev.ks.munch.models.FeedItem;

/**
 * Created by Kartik_ch on 12/2/2015.
 */
public interface IArticlePresenter {
    void attemptArticleLoading(String url);

    void archiveArticle(FeedItem feedItem, String article);

    void removeArticle(FeedItem feedItem);
}


text:
package com.study.spring.mapper;

import com.study.spring.entity.UserInfo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

/**
 * Created on 2018-01-07
 *
 * @author liuzhaoyuan
 */
@Repository
public interface UserInfoDao {

    UserInfo findUserInfoByAccount(String account);

    UserInfo findUserInfoById(Long id);

    List<UserInfo> findUserInfosByIds(@Param("ids") List<Long> ids);

    Long deleteUserInfoByAccount(String account);

    Long saveUserInfo(UserInfo userInfo);

}


text:
package org.airpnp.upnp;

import org.airpnp.plumbing.Dynamic._
import java.io.IOException
import java.net.InetAddress
import java.net.MulticastSocket
import net.pms.network.UPNPHelper
import java.util.regex.Pattern
import java.util.Locale

object UPNP {
  val IPV4_UPNP_HOST = "239.255.255.250"
  val UPNP_PORT = 1900

  private val durationPattern = Pattern.compile("^[+-]?(?<hour>\\d+):(?<minute>\\d{2,2}):(?<second>\\d{2,2})(.(?<msec>\\d+)|.(?<F0>\\d+)/(?<F1>\\d+))?$")

  //    public static MulticastSocket getNewMulticastSocket() {
  //        MulticastSocket multicastSocket = (MulticastSocket) IgnoreMemberAccessibility
  //                .invokeStatic(UPNPHelper.class, "getNewMulticastSocket");
  //        return multicastSocket;
  //    }
  //
  def getUPNPAddress() = classOf[UPNPHelper].callStatic("getUPNPAddress").asInstanceOf[InetAddress]
  //
  //    public static void cleanupMulticastSocket(MulticastSocket socket) {
  //        // Clean up the multicast socket nicely
  //        try {
  //            socket.leaveGroup(getUPNPAddress());
  //        } catch (IOException e) {
  //        }
  //
  //        socket.disconnect();
  //        socket.close();
  //    }

  /**
   * Parses a string in duration format and returns as number of seconds. Format:
   *
   *  ['+'|'-']H+:MM:SS[.F0+|.F0/F1]
   */
  def parseDuration(duration: String): Double = {
    val m = durationPattern.matcher(duration)
    if (!m.matches) {
      throw new IllegalArgumentException("Invalid duration format.")
    }
    val hour = Integer.parseInt(m.group("hour"))
    val minute = Integer.parseInt(m.group("minute"))
    val second = Integer.parseInt(m.group("second"))

    if (minute >= 60 || second >= 60) {
      throw new IllegalArgumentException("Invalid duration format (minute/second too large).")
    }

    val msec = {
      val g = m.group("msec")
      if (g != null) {
        java.lang.Double.parseDouble("0." + g)
      } else {
        val f1g = m.group("F1")
        if (f1g != null) {
          val f1 = java.lang.Double.parseDouble(f1g)
          if (f1 == 0) {
            throw new IllegalArgumentException("Invalid duration format (millisecond divisor is 0).")
          }
          val f0 = java.lang.Double.parseDouble(m.group("F0"))
          if (f0 >= f1) {
            throw new IllegalArgumentException("Invalid duration format (milliseconds greater than 1).")
          }
          f0 / f1
        } else {
          0.0
        }
      }
    }

    val sign = if (duration(0) == '-') -1 else 1
    sign * (((hour * 60 + minute) * 60) + second + msec)
  }

  def toDuration(secs: Double): String = {
    def toHms(secs: Double) = {
	    val hour = (secs / 3600).toInt
	    val min = ((secs.toInt % 3600) / 60).toInt
	    val sec = (secs.toInt % 60) + secs - secs.toInt
	    "%d:%02d:%06.3f".formatLocal(Locale.US, hour, min, sec)
    }
    val hms = toHms(Math.abs(secs))
    if (secs < 0) "-" + hms else hms
  }
}


text:
namespace Crunch { namespace Containers {

CRUNCH_CONTAINERS_API CRUNCH_NORETURN void ThrowInvalidArgument(char const* message);
CRUNCH_CONTAINERS_API CRUNCH_NORETURN void ThrowLengthError(char const* message);
CRUNCH_CONTAINERS_API CRUNCH_NORETURN void ThrowOutOfRange(char const* message);
CRUNCH_CONTAINERS_API CRUNCH_NORETURN void ThrowOverflowError(char const* message);
CRUNCH_CONTAINERS_API CRUNCH_NORETURN void ThrowRuntimeError(char const* message);

}}

#endif


text:
{% from "alignviewers/utils.html" import igv_script %}

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Scout: Integrative Genomics Viewer</title>

    <link rel="stylesheet" type="text/css"
          href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css"/>

    <link rel="stylesheet" type="text/css"
          href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css"/>

    {{ igv_script() }}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

    <com.github.piasy.handywidgets.centertitlesidebuttonbar.CenterTitleSideButtonBar
            android:id="@+id/mTitleBar"
            style="@style/LeftBackSearchTitleBar"
            app:closeSearchViewText="cancel"
            app:closeSearchViewId="@+id/mCloseSearchViewButton"
            app:hasRightButton="false"
            app:hasLeftButton="false"
            app:rightButtonClickToSearch="false"
            app:searchViewDefaultShown="true"
            />

    <Button
            android:id="@+id/mBtnSendResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="send result"
            />

    <Button
            android:id="@+id/mBtnSendResult2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="hide search and send result"
            />
</LinearLayout>


text:
var Fort = {
    clean: function clean() {
        var forms = document.querySelectorAll(".form");
        for (var i = forms.length; i--;) {
            var nonemptyelements = forms[i].querySelectorAll("input, textarea, select");
            Array.prototype.forEach.call(nonemptyelements, function(el){
              if (el.value.length != 0 )
                if (el.classList)
                    el.classList.add('ignore');
                else
                    el.className += ' ' + 'ignore';
            });
            var hiddenInputs = forms[i].querySelectorAll('input[type=hidden]')
            Array.prototype.forEach.call(hiddenInputs, function(el){
                if (el.classList)
                  el.classList.add('ignore');
                else
                  el.className += ' ' + 'ignore';
            });
        };
    },

    solid: function solid(hex) {
        Fort.clean();
        document.body.innerHTML = '

' + document.body.innerHTML;

        function cback(e) {
            var t = [];
            for (var n = inputs.length; n--;) {
                if (!inputs[n].value.length) t.push(inputs[n]);
            }
            var r = t.length;
            var i = inputs.length;
            var s = document.querySelectorAll(".top-one");
            for (var o = s.length; o--;) {
                s[o].style.width = 100 - r / i * 100 + "%";
            }

            //Set color of bar as solid
            document.getElementById("top1").style.background = hex;
        }
        var forms = document.querySelectorAll(".form"),
            inputs = [];
        for (var i = forms.length; i--;) {
            var els = forms[i].querySelectorAll("input, textarea, select");
            for (var j = els.length; j--;) {
                classes = els[j].className.replace(/\s+/g, ' ').split(' ');
                ignore = false;
                for (var k = classes.length; k--;) {
                    if (classes[k] == "ignore") {
                        ignore = true;
                        break;
                    }
                }
                if (els[j].type != "button" && els[j].type != "submit" && !ignore) {
                    inputs.push(els[j]);
                    els[j].addEventListener("input", cback, false);
                }
            }
        }
    },

    gradient: function(firstColor, secondColor) {
        Fort.clean();
        document.body.innerHTML = '

' + document.body.innerHTML;

        function cback(e) {
            var t = [];
            for (var n = inputs.length; n--;) {
                if (!inputs[n].value.length) t.push(inputs[n]);
            }
            var r = t.length;
            var i = inputs.length;
            var s = document.querySelectorAll(".top-one");
            for (var o = s.length; o--;) {
                s[o].style.width = 100 - r / i * 100 + "%";
            }
            orientation = 'to right';
            var string = 'linear-gradient(' + orientation + ', ' + firstColor + ', ' + secondColor + ')';
            document.getElementById("top1").style.background = string;
        }
        var forms = document.querySelectorAll(".form"),
            inputs = [];
        for (var i = forms.length; i--;) {
            var els = forms[i].querySelectorAll("input, textarea, select");
            for (var j = els.length; j--;) {
                classes = els[j].className.replace(/\s+/g, ' ').split(' ');
                ignore = false;
                for (var k = classes.length; k--;) {
                    if (classes[k] == "ignore") {
                        ignore = true;
                        break;
                    }
                }
                if (els[j].type != "button" && els[j].type != "submit" && !ignore) {
                    inputs.push(els[j]);
                    els[j].addEventListener("input", cback, false);
                }
            }
        }
    },

    sections: function() {
        Fort.clean();
        for (var i = 0; i < arguments.length; ++i) {
            var args = Array.prototype.slice.call(arguments);
        }

        document.body.innerHTML = '

' + document.body.innerHTML;

        function cback(e) {
            var t = [];
            for (var n = inputs.length; n--;) {
                if (!inputs[n].value.length) t.push(inputs[n]);
            }
            var r = t.length;
            var i = inputs.length;
            var s = document.querySelectorAll(".top-one");
            for (var o = s.length; o--;) {
                s[o].style.width = 100 - r / i * 100 + "%";
            }
        }
        var forms = document.querySelectorAll(".form"),
            inputs = [];
        for (var i = forms.length; i--;) {
            var els = forms[i].querySelectorAll("input, textarea, select");
            for (var j = els.length; j--;) {
                classes = els[j].className.replace(/\s+/g, ' ').split(' ');
                ignore = false;
                for (var k = classes.length; k--;) {
                    if (classes[k] == "ignore") {
                        ignore = true;
                        break;
                    }
                }
                if (els[j].type != "button" && els[j].type != "submit" && !ignore) {
                    inputs.push(els[j]);
                    els[j].addEventListener("input", cback, false);
                }
            }
        }

        function colDistr(input) {
            var result = [],
                step = 0;
            for (i = 0; i < input.length * 2; i++) {
                if (i % 2) step++;
                var perc = Math.floor(step * 1000 / input.length) / 10;
                result.push([input[i - step], perc + "%"]);
            }
            return result;
        }

        function generateCSSGradient(colours) {
            var l = colours.length,
                i;
            for (i = 0; i < l; i++) colours[i] = colours[i].join(" ");
            return "linear-gradient( to right, " + colours.join(", ") + ")";
        }

        document.getElementsByClassName('top-one').innerHTML = '

';
        document.querySelector(".colors").style.background = generateCSSGradient(colDistr(args.sort()));

        var window_width = window.innerWidth + "px";
        document.querySelector(".colors").style.width = window_width;
    },

    flash: function() {
        Fort.clean();
        for (var i = 0; i < arguments.length; ++i) {
            var totalSections = arguments.length;
            var totalColors = arguments[i];
        }
        var args = Array.prototype.slice.call(arguments);
        var cols = args.sort();

        document.body.innerHTML = '

' + document.body.innerHTML;

        function cback(e) {
            var t = [];
            for (var n = inputs.length; n--;) {
                if (!inputs[n].value.length) t.push(inputs[n]);
            }
            var r = t.length;
            var i = inputs.length;
            var s = document.querySelectorAll(".top-one");
            for (var o = s.length; o--;) {
                s[o].style.width = 100 - r / i * 100 + "%";
                s[o].style.background = cols[i - r - 1];
            }
        }
        var forms = document.querySelectorAll(".form"),
            inputs = [];
        for (var i = forms.length; i--;) {
            var els = forms[i].querySelectorAll("input, textarea, select");
            for (var j = els.length; j--;) {
                classes = els[j].className.replace(/\s+/g, ' ').split(' ');
                ignore = false;
                for (var k = classes.length; k--;) {
                    if (classes[k] == "ignore") {
                        ignore = true;
                        break;
                    }
                }
                if (els[j].type != "button" && els[j].type != "submit" && !ignore) {
                    inputs.push(els[j]);
                    els[j].addEventListener("input", cback, false);
                }

            }
        }
    },

    merge: function(hex) {
        Fort.clean();
        document.body.innerHTML = '

' + document.body.innerHTML;
        document.body.innerHTML = '

' + document.body.innerHTML;

        function cback(e) {
            var t = [];
            for (var n = inputs.length; n--;) {
                if (!inputs[n].value.length) t.push(inputs[n]);
            }
            var r = t.length;
            var i = inputs.length;
            var s = document.querySelectorAll("#top1");

            for (var o = s.length; o--;) {
                precalct = 100 - r / i * 100;
                var precalct2 = precalct / 2;
                s[o].style.width = precalct2 + "%";
            }

            var r = t.length;
            var i = inputs.length;
            var s = document.querySelectorAll("#top2");

            for (var o = s.length; o--;) {
                precalct = 100 - r / i * 100;
                var precalct2 = precalct / 2;
                s[o].style.width = precalct2 + "%";
            }

            document.getElementById("top1").style.background = hex;
            document.getElementById("top2").style.background = hex;

        }
        var forms = document.querySelectorAll(".form"),
            inputs = [];
        for (var i = forms.length; i--;) {
            var els = forms[i].querySelectorAll("input, textarea, select");
            for (var j = els.length; j--;) {
                classes = els[j].className.replace(/\s+/g, ' ').split(' ');
                ignore = false;
                for (var k = classes.length; k--;) {
                    if (classes[k] == "ignore") {
                        ignore = true;
                        break;
                    }
                }
                if (els[j].type != "button" && els[j].type != "submit" && !ignore) {
                    inputs.push(els[j]);
                    els[j].addEventListener("input", cback, false);
                }
            }
        }
    },
    config: function(settings) {
        var t1 = document.querySelector('#top1');
        var t2 = document.querySelector('#top2') || {style:{}};
        if (settings.height) {
            t1.style.height = settings.height;
            t2.style.height = settings.height;
        }
        if (settings.alignment) {
            if (settings.alignment === 'top') {
                t1.style.top = 0;
                t1.style.bottom = 'auto';
                t2.style.top = 0;
                t2.style.bottom = 'auto';
            } else {
                t1.style.top = 'auto';
                t1.style.bottom = 0;
                t2.style.top = 'auto';
                t2.style.bottom = 0;
            }
        }
        if (settings.duration) {
            t1.style.transitionDuration = settings.duration;
            t2.style.transitionDuration = settings.duration;
        }
    }
};


text:
package org.treeleafj.xmax.http.basic;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.treeleafj.xmax.http.HttpException;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

/**
 * 封装HttpPost, 提供更精简的Api操作
 *
 * @author leaf
 * @date 2016-06-21 16:32
 */
public class Post extends Http<Post> {

    private static Logger log = LoggerFactory.getLogger(Post.class);

    /**
     * http post报文体中的参数数据
     */
    private String body;

    /**
     * 构建http请求对象
     *
     * @param address 请求地址,可以是http或者https
     */
    public Post(String address) {
        super(address);
    }

    @Override
    public String send() {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        this.send(out);
        try {
            return out.toString(this.encoding);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("将返回数据转移为" + this.encoding + "失败", e);
        }
    }

    @Override
    public void send(OutputStream out) {

        String paramStr = "";

        if (StringUtils.isNotBlank(this.body)) {
            paramStr = this.body;
        } else if (this.param != null) {
            paramStr = param2UrlParam(this.param);
        }

        InputStream in = null;
        OutputStream out2 = null;
        HttpURLConnection conn = null;

        try {

            try {

                URL url = new URL(this.address);
                // 打开和URL之间的连接
                conn = this.buildHttpURLConnection(url);

                conn.setAllowUserInteraction(false);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setConnectTimeout(this.connectTimeout);
                conn.setReadTimeout(this.readTimeout);
                conn.setDoOutput(true);
                conn.setDoInput(true);

                // 设置的请求属性
                for (String name : this.header) {
                    conn.setRequestProperty(name, this.header.getHeader(name));
                }

                out2 = conn.getOutputStream();

                IOUtils.write(paramStr, out2, this.encoding);

                in = conn.getInputStream();

                IOUtils.copy(in, out);
            } catch (SocketTimeoutException ste) {
                if (this.retry) {
                    log.warn("调用{}失败:{},进行重复尝试", this.address, ste.getMessage());

                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out2);

                    URL url = new URL(this.address);
                    // 打开和URL之间的连接
                    conn = buildHttpURLConnection(url);

                    conn.setAllowUserInteraction(false);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(this.connectTimeout);
                    conn.setReadTimeout(this.readTimeout);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);

                    // 设置的请求属性
                    for (String name : this.header) {
                        conn.setRequestProperty(name, this.header.getHeader(name));
                    }

                    out2 = conn.getOutputStream();

                    IOUtils.write(paramStr, out2, this.encoding);

                    in = conn.getInputStream();

                    IOUtils.copy(in, out);
                } else {
                    throw ste;
                }
            }

        } catch (Exception e) {
            throw new HttpException("post方式请求远程地址" + this.address + "失败", e);
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(out2);
            IOUtils.closeQuietly(in);
            if (conn != null) {
                try {
                    conn.disconnect();
                } catch (Exception e) {
                    log.warn("关闭HttpURLConnection失败.", e);
                }
            }
        }
    }

    /**
     * 设置Post请求的Body
     *
     * @param body 请求体
     * @return Get对象
     */
    public Post body(String body) {
        this.body = body;
        return this;
    }
}


text:
<?php

/**
 * Plugin Dir
 * Returns plugin directory path
 */
function plugin_dir() {
    return ROOT_DIR . '/site/_plugins';
}

/**
 * Plugin Exists
 */
function plugin_exists( $plugin ) {
    return is_dir(plugin_dir() .'/'. $plugin);
}

/**
 * Plugin Is Active
 */
function plugin_is_active( $plugin ) {
    return file_exists(plugin_dir() .'/'. $plugin .'/plugin.php');
}

/**
 * Plugin Load Config
 * Load a plugins' YAML config file.
 */
function plugin_load_config( $plugin ) {
    $config = Spyc::YAMLLoad(ROOT_DIR . '/site/_plugins/' . $plugin . '/_config.yml');
    return apply_filters($plugin . '_load_config', $config);
}


text:
<?xml version="1.0"?>
<!--
  ~ Copyright (c) 2010-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<objects>
    <user>
        <name>u1</name>
    </user>
    <user>
        <name-error>u2</name-error>
    </user>
    <role>
        <name>r1</name>
    </role>
</objects>


text:
function(add_quickstart_test TEST_NAME SOURCE_FILE)
  cmake_parse_arguments(PARSE_ARGV 2 ARGS "NO_EXCEPTIONS;NATIVE_ARCH" "" "CXX_STANDARD;LABELS")

  # Standard compiler flags
  if (MSVC)
    list(APPEND QUICKSTART_FLAGS /WX)
  else()
    list(APPEND QUICKSTART_FLAGS -Werror)
  endif()

  # Native architecture compiler flag
  if (ARGS_NATIVE_ARCH)
    if (MSVC)
      message(ERROR "MSVC quickstart native compile not supported because we don't know the right flag to pass to MSVC yet")
    else()
      list(APPEND QUICKSTART_FLAGS -march=native)
    endif()
  endif()

  # C++ standard compiler flag
  if (MSVC)
    if (ARGS_CXX_STANDARD)
      list(APPEND QUICKSTART_FLAGS /std:${ARGS_CXX_STANDARD})
    endif()
  else()
    if (ARGS_CXX_STANDARD)
      list(APPEND QUICKSTART_FLAGS -std=${ARGS_CXX_STANDARD})
    endif()
  endif()

  # No Exceptions compiler flag
  if (ARGS_NO_EXCEPTIONS)
    if (NOT MSVC)
      list(APPEND QUICKSTART_FLAGS -fno-exceptions)
    endif()
  endif()

  add_test(
    NAME ${TEST_NAME}
    COMMAND ${CMAKE_CXX_COMPILER} ${QUICKSTART_FLAGS} -I${PROJECT_SOURCE_DIR}/include -I${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/src/simdjson.cpp ${SOURCE_FILE}
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/examples/quickstart
  )
  list(APPEND ARGS_LABELS quickstart compile no_mingw)
  set_property(TEST ${TEST_NAME} APPEND PROPERTY LABELS ${ARGS_LABELS})
  set_property(
    TEST ${TEST_NAME}
    APPEND PROPERTY DEPENDS simdjson-source ${PROJECT_SOURCE_DIR}/examples/quickstart/${SOURCE_FILE}
  )
endfunction(add_quickstart_test)


text:
import { Operation, Tag } from "swagger-schema-official";

export type Endpoint = {
  httpMethod: string;
  path: string;
  method: Operation;
};

export type EndpointSummary = {
  httpMethod: string;
  path: string;
  summary: string;
  anchor: string;
  tags: string[];
};

export type EndpointSummarySet = { [key: string]: string[] };

// Extensions to the Swagger tag schema
export type SuperTag = Tag & {
  // Indicates if a tag is meta-only
  "x-meta": boolean;

  // Indicates is a tag is deprecated
  "x-deprecated": boolean;
};

export const HTTP_METHODS = [
  "get",
  "put",
  "post",
  "delete",
  "options",
  "head",
  "patch",
] as const;
type ElementType<T extends ReadonlyArray<unknown>> = T extends ReadonlyArray<
  infer ElementType
>
  ? ElementType
  : never;
type HttpMethod = ElementType<typeof HTTP_METHODS>;


text:
enum ops {
  hOpAnd,
  hOpOr,
  hOpLt,
  hOpLte,
  hOpEq,
  hOpNeq,
  hOpGt,
  hOpGte,
  hOpAdd,
  hOpSub,
  hOpMul,
  hOpDiv,
  hOpPow,
  hOpFval,
  hOpBval,
  hOpId,
  hOpNone
 };

typedef enum ops ops_t;

typedef enum PreDefModTypes {

  // Some necessary internal definitions
  mtStartString,
  mtEndString,
  // a wildcard ( whee! )
  mtAny,
  // and all the turtle commands
  mtForward  ,
  mtTiptoe   ,
  mtCircle   ,
  mtSphere   ,
  mtRollLeft ,
  mtRollRight,
  mtLeft     ,
  mtRight    ,
  mtUp       ,
  mtDown     ,
  mtAboutFace,
  mtWidth    ,
  mtColor    ,
  mtColorHue ,
  mtColorSat ,
  mtColorVal ,
  mtPush     ,
  mtPop      ,
  mtUnPush   ,
  mtRePush   ,
  mtTriStart ,
  mtTriEnd   ,
  mtTriPoint ,
  NUM_PREDEF_MOD_TYPES // keep this last
} PreDefModTypes;

typedef char* Id;

typedef float* Bindings;

bool isBinaryOp(ops_t);

// These guys need to get packed into the lstring
typedef unsigned short IModType;
#define GARBAGE_IMODTYPE 0xffff

// These are used as indexes when writing
// to arrays of bound variables
typedef unsigned int IParamId;

#endif


text:
package com.lsilberstein.googleimages.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.lsilberstein.googleimages.R;
import com.lsilberstein.googleimages.adapters.ImageResultAdapter;
import com.lsilberstein.googleimages.fragments.SettingsDialog;
import com.lsilberstein.googleimages.model.ImageResult;
import com.lsilberstein.googleimages.network.GoogleImageClient;
import com.lsilberstein.googleimages.utils.EndlessRecyclerOnScrollListener;

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

public class ImagesActivity extends AppCompatActivity implements SettingsDialog.SettingsDialogListener {

    private static final String SETTINGS_DIALOG_TAG = "settings_dialog";
    public static final String IMAGE_RESULT = "image_result";
    private RecyclerView rvImages;
    private ImageResultAdapter aImages;
    private List<ImageResult> images;
    private GoogleImageClient client;
    private EndlessRecyclerOnScrollListener onScrollListener;
    private SettingsDialog settingsDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_images);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        settingsDialog =  SettingsDialog.newInstance();

        // Set up the data source
        images = new ArrayList<>();

        // create the adapter
        aImages = new ImageResultAdapter(images);
        aImages.setItemClickListener(new ImageResultAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                ImageResult result = images.get(position);
                Intent intent = new Intent(ImagesActivity.this, DetailActivity.class);
                intent.putExtra(IMAGE_RESULT, result);
                startActivity(intent);
            }
        });

        // create our client which will handle the data retrieval
        client = new GoogleImageClient(aImages);

        StaggeredGridLayoutManager layoutManager =
                new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
        // set up the recycler view
        rvImages = (RecyclerView) findViewById(R.id.rvImages);
        rvImages.setAdapter(aImages);
        rvImages.setLayoutManager(layoutManager);

        onScrollListener = new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore(int page) {
                client.getMoreResults();
            }
        };
        rvImages.addOnScrollListener(onScrollListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_images, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                onScrollListener.reset();
                // perform query here
                client.searchGoogleFor(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        // open the settings dialog
        if (id == R.id.action_settings) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            settingsDialog.show(fragmentManager, SETTINGS_DIALOG_TAG);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFiltersSaved(String size, String colour, String type, String site) {
        client.setSize(size);
        client.setColour(colour);
        client.setType(type);
        client.setSite(site);
    }
}


text:
var Formium;

(function ($) {
    function WinFormium() {
        const CMD_ATTR_PREFIX = "formium-command";
        const RAISE_FUNC_NAME = "__formium_raiseHostWindowEvent";
        const GLOBAL_CLICK_HANDLER_REGISTERED =
            "__formium_global_click_handler_registered";

        let isDocumentReady = false;
        let isContextReady = false;

        const readyCallbacks = [];
        const contextReadyCallbacks = [];

        const dataMessageHandlers = [];

        class WinFormium {

            __setContextReady__() {

                while (contextReadyCallbacks.length > 0) {
                    contextReadyCallbacks.pop().apply(this);
                }

                isContextReady = true;

                //console.log("NanUI Context is ready!");
            };

            __setDocumentReady__() {

                const $target = this;

                window[RAISE_FUNC_NAME] = (eventName, data) => {
                    window.dispatchEvent(new CustomEvent(
                        eventName,
                        {
                            detail: data,
                            bubbles: true
                        })
                    );
                }

                if (!window.hasOwnProperty(GLOBAL_CLICK_HANDLER_REGISTERED)) {
                    window.addEventListener("click", e => {
                        let srcElement = e.target;

                        while (srcElement && !srcElement.hasAttribute(CMD_ATTR_PREFIX)) {
                            srcElement = srcElement.parentElement;
                        }

                        if (srcElement) {

                            const commandString = srcElement.getAttribute(CMD_ATTR_PREFIX).toLowerCase();

                            const commandMaps = {
                                close: "close",
                                maximize: "maximize",
                                minimize: "minimize",
                                restore: "restore",
                                close: "close",
                                fullscreen: "fullScreen"
                            };

                            if (commandMaps.hasOwnProperty(commandString)) {

                                const { hostWindow } = Formium;
                                const command = commandMaps[commandString];

                                if (command && hostWindow && hostWindow[command]) {

                                    e.stopPropagation();
                                    e.preventDefault();

                                    hostWindow[command].apply($target);
                                }
                            }

                        }
                    });

                    window[GLOBAL_CLICK_HANDLER_REGISTERED] = true;
                }

                while (readyCallbacks.length > 0) {
                    readyCallbacks.pop().apply(this);
                }

                isDocumentReady = true;

                //console.log("NanUI document object is ready!");
            };

            __onDataMessageReceived__(message, base64) {
                if (typeof base64 === "undefined" || base64 == null) {
                    while (dataMessageHandlers.length > 0) {
                        dataMessageHandlers.pop().apply(this, [message]);
                    }
                }
                else {
                    if (dataMessageHandlers.length > 0) {
                        const json = JSON.parse(window.atob(base64));
                        while (dataMessageHandlers.length > 0) {
                            dataMessageHandlers.pop().apply(this, [message, json]);
                        }
                    }
                }
            }

            onDocumentReady(callback) {

                if (isDocumentReady) {
                    callback.apply(this);
                }
                else {
                    readyCallbacks.push(callback);
                }

            };

            onContextReady(callback) {

                if (isContextReady) {
                    callback.apply(this);
                }
                else {
                    contextReadyCallbacks.push(callback);
                }

            };

            onDataMessageReceived(handler) {
                dataMessageHandlers.push(handler);
            }

            sendDataMessage(messageName, data) {
                native function SendDataMessage();
                return SendDataMessage(messageName, JSON.stringify(data));
            }

            hostWindow = new HostWindowInterface();

            version = new Version();

            network = new NetworkInterface();

            get culture() {
                native function GetCurrentCulture();
                return GetCurrentCulture();
            }

        }

        const $this = new WinFormium();

        $this["__createFormiumPromiseFunction__"] = function () {

            const result = {};

            const promise = new Promise(function (resolve, reject) {
                result.resolve = resolve;

                result.reject = reject;
            });

            result.promise = promise;

            return result;
        }

        return $this;
    }

    function HostWindowInterface() {

        class SplashScreen {
            show() {
                native function ShowSplashScreen();
                return ShowSplashScreen();
            }

            hide() {
                native function HideSplashScreen();
                return HideSplashScreen();
            }
        }

        class BorderlessWindowOptions {

            get cornerStyle() {
                native function GetCornerStyle();
                return GetCornerStyle();
            }

            set cornerStyle(config) {
                native function SetCornerStyle();
                return SetCornerStyle(config);
            }

            get shadowEffect() {
                native function GetShadowEffect();
                return GetShadowEffect();
            }
            set shadowEffect(config) {
                native function SetShadowEffect();
                return SetShadowEffect(config);
            }

            get shadowColor() {
                native function GetShadowColor();
                return GetShadowColor();
            }

            set shadowColor(value) {
                native function SetShadowColor();
                return SetShadowColor(value);
            }

            get inactiveShadowColor() {
                native function GetInactiveShadowColor();
                return GetInactiveShadowColor();
            }

            set inactiveShadowColor(value) {
                native function SetInactiveShadowColor();
                return SetInactiveShadowColor(value);
            }
        }

        class HostWindow {
            minimize() {
                native function Minimize();
                return Minimize();
            }

            maximize() {
                native function Maximize();
                return Maximize();
            }

            close() {
                native function Close();
                return Close();
            }

            restore() {
                native function Restore();
                return Restore();
            }

            fullScreen() {
                native function FullScreen();
                return FullScreen();
            }

            moveTo(x, y) {
                native function MoveTo();
                return MoveTo(x, y);
            }

            moveBy(deltaX, deltaY) {
                native function MoveBy();
                return MoveBy(deltaX, deltaY);
            }

            sizeTo(width, height) {
                native function SizeTo();
                return SizeTo(width, height);
            }

            sizeBy(deltaX, deltaY) {
                native function SizeBy();
                return SizeBy(deltaX, deltaY);
            }

            active() {
                native function Active();
                return Active();
            }

            center() {
                native function Center();
                return Center();
            }

            borderlessWindow = new BorderlessWindowOptions();

            splashScreen = new SplashScreen();

            get windowState() {
                native function GetWindowState();
                return GetWindowState();
            }

            get location() {
                native function GetWindowLocation();
                return GetWindowLocation();
            }

            get size() {
                native function GetWindowSize();
                return GetWindowSize();
            }

            get rectangle() {
                native function GetWindowRectangle();
                return GetWindowRectangle();
            }

        }

        return new HostWindow();
    }

    function NetworkInterface() {
        class Network {
            isNetworkAvailable() {
                native function GetNetworkAvailableStatus();
                return GetNetworkAvailableStatus();
            }
        }

        return new Network();
    }

    function Version() {
        class Version {
            get formium() {
                native function GetWinFormiumVersion();
                return GetWinFormiumVersion();
            }

            get chromium() {
                native function GetChromiumVersion();
                return GetChromiumVersion();
            }
        }

        return new Version();
    }

    $.Formium = new WinFormium();

})(this);


text:
import os
import sys
import traceback

# Add the pulsar path
thispath = os.path.dirname(os.path.realpath(__file__))
psrpath = os.path.join(os.path.dirname(thispath), "modules")
sys.path.insert(0, psrpath)

import pulsar as psr
from pulsar.output import *
from pulsar.testing import *
from pulsar.datastore import *
from pulsar.system import *
from pulsar.math import *

from helper.TestOptions import opttypemap, validvals
from helper.TestAtoms import nonane

def Run():
    try:
        tester = Tester("Testing Wavefunction - serialization")
        tester.print_header()

        w = Wavefunction()
        tester.test("Serialization of empty wavefunction", True,
                    TestSerialization_Wavefunction, w)

        atoms = list(nonane)
        u = AtomSetUniverse()
        for a in atoms:
            u.insert(a)

        s = System(u, True)
        s = apply_single_basis("primary", "sto-3g", s)

        w.system = s
        tester.test("Serialization with system", True,
                    TestSerialization_Wavefunction, w)

        cmat = IrrepSpinMatrixD()
        cmat.Set(Irrep.A1, 0, SimpleMatrixD(2, 2, [1, 2, 3, 4]))
        w.cmat = cmat
        tester.test("Serialization with cmat", True,
                    TestSerialization_Wavefunction, w)

        epsilon = IrrepSpinVectorD()
        epsilon.Set(Irrep.E2, 0, SimpleVectorD(2, [1, 2]))
        w.epsilon = epsilon
        tester.test("Serialization with epsilon", True,
                    TestSerialization_Wavefunction, w)

        occupations = IrrepSpinVectorD()
        occupations.Set(Irrep.A2, 0, SimpleVectorD(2, [1, 2]))
        w.occupations = occupations
        tester.test("Serialization with occupations", True,
                    TestSerialization_Wavefunction, w)

        tester.print_results()

    except Exception as e:
      print_global_output("Caught exception in main handler. Contact the developers\n")
      traceback.print_exc()
      print_global_error("\n")
      print_global_error(str(e))
      print_global_error("\n")

psr.initialize(sys.argv, color = True, debug = True)
Run()
psr.finalize()


text:
using namespace std;

namespace sj
{
typedef struct
{
    int numNeuron;
    int numActivation;
    int numWeight;
} LayerInfo;

class Net
{
public:

    bool m_firstInput;
    int m_inputNum;
    float m_eta;
    float m_alpha;
    float m_weightRange;

    float *m_input;

    float m_error;
    float m_recentAverageError;
    float m_recentAverageSmoothingFactor;

    vector<float**> m_layers;           // neuron == weights
    vector<float**> m_layers_tmp;

    vector<float**> m_layersDeltaWeight;

    vector<float*> m_layersActivation;
    vector<float*> m_layersActivation_diff;
    vector<LayerInfo*> m_layersInfo;

    Net();
    Net(int _inputNum);

    ~Net();

    void push_back_layer(int _numNeuron);
    void setWeight();

    void feedforward(float *_input);
    void backprob(float *_target);
    float activate(float _x);
    float activate_diff(float _x);

    void save(char* _filePath);
    void load(char* _filePath);
    float getRecentAverageError();
};

}

#endif // NET_H


text:
<?php
/**
 * Integer validator
 */

/**
 * Integer validator
 */
class Validation_Validator_Integer extends Validation_Validator {

	/**
	 * Checks if a value is an integer
	 *
	 * @return boolean true if an integer
	 */
	public function validate() {
		$bValid = true;

		// don't validate if we don't have a value
		if (!$this->hasValue()) {
			return true;
		}

		$bValid = $bValid && (boolean)preg_match('/^-?\d+$/', (string)$this->mValue);

		return $bValid;
	}
}


text:
#import <UIKit/UIKit.h>
#import "InAppPurchaseAppDelegate.h"

#define kBuyButtonTag   555

typedef enum {
    ButtonStateHidden,
    ButtonStateDisabled,
    ButtonStateBuy,
    ButtonStateBuyDisabled,
    ButtonStateBought

} StoreTableCellButtonState;

@interface StoreTableCell : UITableViewCell <UIAlertViewDelegate> {
	UIButton* buyButton;
    StoreTableCellButtonState buttonState;
	NSString* productId;
}

-(void) addProgress;
-(void) purchaseCleanup:(NSString*)purchasedProductID;
-(void) setButtonState:(StoreTableCellButtonState)state;
-(void) updateButtonState;
-(void) update;
-(StoreTableCellButtonState) getButtonStateUnpurchased;
-(BOOL) alreadyPurchased;

@end


text:
const fakeRedis = require('fakeredis');
const setRedisClient = require('../src/routes/authentication').setRedisClient;

setRedisClient(fakeRedis.createClient());


text:
<!doctype html>

<meta charset="utf-8">
<title>Serialization of font shorthand</title>
<link rel="help" href="https://drafts.csswg.org/cssom-1/#serialize-a-css-declaration-block">

<link rel="stylesheet" type="text/css" href="/fonts/ahem.css" />


text:
package org.hive2hive.processframework;

import static org.junit.Assert.*;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.hive2hive.processframework.exceptions.InvalidProcessStateException;
import org.hive2hive.processframework.exceptions.ProcessExecutionException;
import org.hive2hive.processframework.interfaces.IProcessComponent;
import org.hive2hive.processframework.utils.BusyComponent;
import org.hive2hive.processframework.utils.TestUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class ProcessComponentTest extends BaseTest {

	@BeforeClass
	public static void initTest() throws Exception {
		testClass = ProcessComponentTest.class;
		beforeClass();
	}

	@AfterClass
	public static void endTest() {
		afterClass();
	}

	@Test
	public void testExecute() throws InvalidProcessStateException, ProcessExecutionException {

		ProcessComponent<Void> component = TestUtil.executionSuccessComponent(false);
		component.execute();

		assertTrue(component.getState() == ProcessState.EXECUTION_SUCCEEDED);
	}

	@Test
	public void testExecuteAsync() throws InvalidProcessStateException, ProcessExecutionException {

		ProcessComponent<Void> component = TestUtil.executionSuccessComponent(false);
		IProcessComponent<Void> busyComp = new BusyComponent(component);

		Future<Void> future = busyComp.executeAsync();

		assertTrue(component.getState() != ProcessState.EXECUTION_SUCCEEDED);

		try {
			future.get();
		} catch (InterruptedException | ExecutionException ex) {
			fail(ex.getMessage());
		}

		assertTrue(component.getState() == ProcessState.EXECUTION_SUCCEEDED);
	}
}