text:
[ ![Build Status](https://travis-ci.org/sensu-plugins/sensu-plugins-tripwire.svg?branch=master)](https://travis-ci.org/sensu-plugins/sensu-plugins-tripwire)
[![Gem Version](https://badge.fury.io/rb/sensu-plugins-tripwire.svg)](http://badge.fury.io/rb/sensu-plugins-tripwire)
[![Code Climate](https://codeclimate.com/github/sensu-plugins/sensu-plugins-tripwire/badges/gpa.svg)](https://codeclimate.com/github/sensu-plugins/sensu-plugins-tripwire)
[![Test Coverage](https://codeclimate.com/github/sensu-plugins/sensu-plugins-tripwire/badges/coverage.svg)](https://codeclimate.com/github/sensu-plugins/sensu-plugins-tripwire)
[![Dependency Status](https://gemnasium.com/sensu-plugins/sensu-plugins-tripwire.svg)](https://gemnasium.com/sensu-plugins/sensu-plugins-tripwire)
[![Sensu Bonsai Asset](https://img.shields.io/badge/Bonsai-Download%20Me-brightgreen.svg?colorB=89C967&logo=sensu)](https://bonsai.sensu.io/assets/sensu-plugins/sensu-plugins-tripwire)

## Sensu Asset
The Sensu assets packaged from this repository are built against the
Sensu Ruby runtime environment. When using these assets as part of a
Sensu Go resource (check, mutator or handler), make sure you include
the corresponding Sensu Ruby runtime asset in the list of assets
needed by the resource. The current ruby-runtime assets can be found
[here](https://bonsai.sensu.io/assets/sensu/sensu-ruby-runtime) in the
Bonsai Asset Index](bonsai.sensu.io).

## Functionality

## Files
 * bin/check-tripwire.rb

## Usage

## Installation

[Installation and Setup](http://sensu-plugins.io/docs/installation_instructions.html)

## Notes


text:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Molly White - Mewtube</title>
  <link rel="stylesheet" href="/css/bootstrap.min.css">
  <link href="/css/stylethings.css" rel="stylesheet" />
  <link rel="stylesheet" href="font-awesome-4.0.3/css/font-awesome.min.css">
  <link rel="shortcut icon" href="/images/favicon.ico" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#menu">
          Toggle navigation

        </button>
        Molly White
        Blog

Home

About

                Projects

General

Bots

Contact

Blog

No kittencam for now, but you can check if I have foster cats on the Facebook page!

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('block', '0002_auto_20141011_2223'),
    ]

    operations = [
        migrations.CreateModel(
            name='ViewUrl',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),
                ('url', models.CharField(max_length=200, blank=True)),
                ('page', models.ForeignKey(to='block.Page')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='+')),
            ],
            options={
                'ordering': ('user__username', 'page__slug', 'page__slug_menu'),
                'verbose_name_plural': 'View URLs',
                'verbose_name': 'View URL',
            },
            bases=(models.Model,),
        ),
        migrations.AlterUniqueTogether(
            name='viewurl',
            unique_together=set([('user', 'page')]),
        ),
        migrations.AddField(
            model_name='page',
            name='is_custom',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
    ]


text:
<?php

namespace lukisongroup\hrd\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use lukisongroup\hrd\models\Corp;

/**
 * CorpSearch represents the model behind the search form about `lukisongroup\hrd\models\Corp`.
 */
class CorpSearch extends Corp
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['CORP_ID', 'CORP_NM', 'CORP_AVATAR', 'CORP_DCRP'], 'safe'],
            [['CORP_STS'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Corp::find()->Where('u0001.CORP_STS<>3');;

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'CORP_STS' => $this->CORP_STS,
            'SORT' => $this->SORT,
        ]);

        $query->andFilterWhere(['like', 'CORP_ID', $this->CORP_ID])
            ->andFilterWhere(['like', 'CORP_NM', $this->CORP_NM])
            ->andFilterWhere(['like', 'CORP_AVATAR', $this->CORP_AVATAR])
            ->andFilterWhere(['like', 'CORP_DCRP', $this->CORP_DCRP]);

        return $dataProvider;
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../../" />

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

		[page:EventDispatcher] →

[name]

		This class can be used to provide a drag'n'drop interaction.

Code Example

		const controls = new DragControls( objects, camera, renderer.domElement );

		// add event listener to highlight dragged objects

		controls.addEventListener( 'dragstart', function ( event ) {

			event.object.material.emissive.set( 0xaaaaaa );

		} );

		controls.addEventListener( 'dragend', function ( event ) {

			event.object.material.emissive.set( 0x000000 );

		} );

Examples

[example:misc_controls_drag misc / controls / drag ]

Constructor

[name]( [param:Array objects], [param:Camera camera], [param:HTMLDOMElement domElement] )

				[page:Array objects]: An array of draggable 3D objects.

			[page:Camera camera]: The camera of the rendered scene.

			[page:HTMLDOMElement domElement]: The HTML element used for event listeners.

				Creates a new instance of [name].

Events

dragstart

			Fires when the user starts to drag a 3D object.

drag

			Fires when the user drags a 3D object.

dragend

			Fires when the user has finished dragging a 3D object.

hoveron

			Fires when the pointer is moved onto a 3D object, or onto one of its children.

hoveroff

			Fires when the pointer is moved out of a 3D object.

Properties

[property:Boolean enabled]

			Whether or not the controls are enabled.

[property:Boolean transformGroup]

			This option only works if the [page:DragControls.objects] array contains a single draggable group object.
			If set to *true*, [name] does not transform individual objects but the entire group. Default is *false*.

Methods

See the base [page:EventDispatcher] class for common methods.

[method:undefined activate] ()

			Adds the event listeners of the controls.

[method:undefined deactivate] ()

			Removes the event listeners of the controls.

[method:undefined dispose] ()

			Should be called if the controls is no longer required.

[method:Array getObjects] ()

			Returns the array of draggable objects.

[method:Raycaster getRaycaster] ()

			Returns the internal [page:Raycaster] instance that is used for intersection tests.

Source

			[link:https://github.com/mrdoob/three.js/blob/master/examples/jsm/controls/DragControls.js examples/jsm/controls/DragControls.js]


text:
using System;

namespace CodeCafeEngine
{
    /// <summary>
    /// Defines a game component that can be attached, and provide functionality, to a <see cref="GameObject"/>.
    /// </summary>
    public abstract class GameComponent : IGameComponent, IGameSequenceObject, ISearchableObject
    {
        private readonly Guid _id = Guid.NewGuid();
        private string _name = Properties.Resources.GameComponent_DefaultName;

        #region Implementation of IGameSequence

        /// <summary>
        /// Occurs when the component is first started.
        /// </summary>
        public virtual void OnStart() { }

        /// <summary>
        /// Occurs after OnStart.
        /// </summary>
        public virtual void OnLateStart() { }

        /// <summary>
        /// Occurs when a key is pressed.
        /// </summary>
        /// <param name="key">The pressed key.</param>
        /// <param name="modifiers">The pressed modifiers keys, if any.</param>
        public virtual void OnKeyDown(Key key, KeyModifiers modifiers) { }

        /// <summary>
        /// Occurs when a key is released.
        /// </summary>
        /// <param name="key">The pressed key.</param>
        /// <param name="modifiers">The pressed modifiers keys, if any.</param>
        public virtual void OnKeyUp(Key key, KeyModifiers modifiers) { }

        /// <summary>
        /// Occurs when the component is updated.
        /// </summary>
        public virtual void OnUpdate() { }

        /// <summary>
        /// Occurs when the component is rendered.
        /// </summary>
        public virtual void OnRender()
        {
#if DEVMODE
            if (GameContext.DebugDisplay.HasFlag(DebugDisplay.Collider))
            {
                // Display the collider
                if (Collider == null) return;
                foreach (BoundingBox bbox in Collider.BoundingBoxes)
                    Render2D.RenderShape(bbox.Shape, GameObject.Position.GetValue());
            }
#endif
        }

        /// <summary>
        /// Occurs when the component is destroyed.
        /// </summary>
        public virtual void OnDestroy() { }

        /// <summary>
        /// Occurs when any game object or component has been destroyed.
        /// </summary>
        public virtual void OnAnyDestroyed(string name) { }

        /// <summary>
        /// Occurs when the current game context is ending.
        /// </summary>
        public virtual void OnContextEnd() { }

        #endregion

        #region Implementation of ISearchableObject

        /// <summary>
        /// Gets the <see cref="IGameContext"/> of this <see cref="ISearchableObject"/>.
        /// </summary>
        public IGameContext GameContext { get; set; }

        /// <summary>
        /// Gets this object's unique id.
        /// </summary>
        public Guid Id
        {
            get { return _id; }
        }

        /// <summary>
        /// Gets this object's name-based hash for faster comparison.
        /// </summary>
        public int Hash { get; private set; }

        /// <summary>
        /// Gets or sets this object's non-unique name.
        /// </summary>
        public string Name
        {
            get { return _name; }
            set
            {
                // Re-register this object on name changes
                Unregister(GameContext);
                _name = value;
                Hash = value.GetHashCode();
                Register(GameContext);
            }
        }

        /// <summary>
        /// Register this <see cref="ISearchableObject"/> with the <see cref="IGameContext"/>. This is called when the object is added to a game context.
        /// </summary>
        /// <param name="gameContext"></param>
        public void Register(IGameContext gameContext)
        {
            if (gameContext == null) return;
            GameContext = gameContext;
            gameContext.RegisterSearchableObject(this);
        }

        /// <summary>
        /// Unregister this <see cref="ISearchableObject"/> from the <see cref="IGameContext"/>. This is called when the object is removed from a game context.
        /// </summary>
        /// <param name="gameContext"></param>
        public void Unregister(IGameContext gameContext)
        {
            if (gameContext == null) return;
            gameContext.UnregisterSearchableObject(this);
        }

        #endregion

        #region Implementation of IGameComponent

        /// <summary>
        /// Gets the <see cref="IGameComponent.GameObject"/> that owns this <see cref="IGameComponent"/>.
        /// </summary>
        public GameObject GameObject { get; set; }

        #endregion

        #region Implementation of IDisableable

        private bool _enabled = true;

        /// <summary>
        /// Gets or sets whether this object is enabled.
        /// </summary>
        public bool Enabled
        {
            get { return _enabled; }
            set { _enabled = value; }
        }

        #endregion

        #region Implementation of ICollideable

        private Collider _collider;

        /// <summary>
        /// Gets or sets the <see cref="ICollideable.Collider"/> of this object.
        /// </summary>
        public Collider Collider
        {
            get { return _collider; }
            set
            {
                _collider = value;
                if (_collider != null)
                    _collider.GameObject = GameObject;
            }
        }

        #endregion

        /// <summary>
        /// Destroy this <see cref="IGameComponent"/> and remove it from the current <see cref="IGameContext"/>.
        /// </summary>
        public void Destroy()
        {
            if (GameObject == null) return;
            OnDestroy();
            GameObject.RemoveComponent(this);
            GameContext.OnAnyDestroyed(Name);
        }

        /// <summary>
        /// Destro this <see cref="IGameComponent"/>'s <see cref="IGameObject"/>.
        /// </summary>
        public void DestroyGameObject()
        {
            if (GameObject == null) return;
            GameObject.Destroy();
        }
    }
}


text:
import { NgModule } from "@angular/core";

import {DataService} from "./data.service";
import {ToastyModule} from "./toasty/toasty.module";

@NgModule({
    imports: [ToastyModule.forRoot()],
    exports: [ToastyModule],
    declarations: [],
    providers: [DataService],
})
export class CoreModule { }


text:
from imdb import IMDb
ia = IMDb()

# get a movie and print its director(s)
the_matrix = ia.get_movie('0133093')
print(the_matrix['director'])

# show all the information sets avaiable for Movie objects
print(ia.get_movie_infoset())

# update a Movie object with more information
ia.update(the_matrix, ['technical'])
# show which keys were added by the information set
print(the_matrix.infoset2keys['technical'])
# print one of the new keys
print(the_matrix.get('cinematographic process'))

# search for a person
for person in ia.search_person('Mel Gibson'):
    print(person.personID, person['name'])

# get the first result of a company search,
# update it to get the basic information
ladd_company = ia.search_company('The Ladd Company')[0]
ia.update(ladd_company)
# show the available information and print some
print(ladd_company.keys())
print(ladd_company.get('production companies'))

# get 5 movies tagged with a keyword
dystopia = ia.get_keyword('dystopia', results=5)

# get a Character object
deckard = ia.search_character('Rick Deckard')[0]
ia.update(deckard)
print(deckard['full-size headshot'])

# get top250 and bottom100 movies
top250 = ia.get_top250_movies()
bottom100 = ia.get_bottom100_movies()


text:
function Randomizer(){

}
Randomizer.nextInt = function(low, high){
    low = Math.floor(low);
    var r = Math.random();
    return low + Math.floor(r * (high - low + 1));
}
Randomizer.nextDouble = function(low, high){
    return low + (high - low) * Math.random();
}

Randomizer.nextFloat = function(low, high){
    return low + (high - low) * Math.random();
}

Randomizer.getHexDigit = function(num){
    if(num < 10) return num + "";
    switch(num){
        case 10: return 'A';
        case 11: return 'B';
        case 12: return 'C';
        case 13: return 'D';
        case 14: return 'E';
        case 15: return 'F';
    }
    return 0;
}

Randomizer.toHex = function(val){
    var first = Math.floor(val / 16);
    var second = val % 16;
    return Randomizer.getHexDigit(first) + Randomizer.getHexDigit(second);
}

Randomizer.nextHex = function(){
    var val = Randomizer.nextInt(0, 255);
    return Randomizer.toHex(val);
}

Randomizer.nextColor = function(){
    var r = Randomizer.nextHex();
    var g = Randomizer.nextHex();
    var b = Randomizer.nextHex();
    return "#" + r + g + b;
}

Randomizer.nextBoolean = function(){
    return Math.random() > 0.5;
}


text:
<jigsaw-demo-description [summary]="summary" [content]="description">
</jigsaw-demo-description>

    <jigsaw-mobile-header [level]="1">Checkbox</jigsaw-mobile-header>

            <jigsaw-mobile-header [level]="2">状态</jigsaw-mobile-header>

三种状态:unchecked checked indeterminate

            <jm-checkbox [(checked)]="demo1Checked" [(enableIndeterminate)]="enableIndeterminate">click me</jm-checkbox>

                启用中间状态:
                <jm-switch [(checked)]="enableIndeterminate"></jm-switch>

The checkbox value is {{demo1Checked}}!

            <jigsaw-mobile-header [level]="2">初始值设置为中间状态</jigsaw-mobile-header>

提示:点击切换其他两个状态

            <jm-checkbox [(checked)]="demo2Checked" [enableIndeterminate]="false">click me</jm-checkbox>

            <jigsaw-mobile-header [level]="2">不可点击状态</jigsaw-mobile-header>
            <jm-checkbox [(checked)]="demo3Checked" [(disabled)]="!enabled">a great checkbox!</jm-checkbox>

                启用点击状态:
                <jm-switch [(checked)]="enabled"></jm-switch>

The checkbox value is {{demo3Checked}}!


text:
title: "rclone serve http"
description: "Serve the remote over HTTP."
slug: rclone_serve_http
url: /commands/rclone_serve_http/
# autogenerated - DO NOT EDIT, instead edit the source code in cmd/serve/http/ and as part of making a release run "make commanddocs"
---
# rclone serve http

Serve the remote over HTTP.

## Synopsis

rclone serve http implements a basic web server to serve the remote
over HTTP.  This can be viewed in a web browser or you can make a
remote of type http read from it.

You can use the filter flags (eg --include, --exclude) to control what
is served.

The server will log errors.  Use -v to see access logs.

--bwlimit will be respected for file transfers.  Use --stats to
control the stats printing.

## Server options

Use --addr to specify which IP address and port the server should
listen on, eg --addr 1.2.3.4:8000 or --addr :8080 to listen to all
IPs.  By default it only listens on localhost.  You can use port
:0 to let the OS choose an available port.

If you set --addr to listen on a public or LAN accessible IP address
then using Authentication is advised - see the next section for info.

--server-read-timeout and --server-write-timeout can be used to
control the timeouts on the server.  Note that this is the total time
for a transfer.

--max-header-bytes controls the maximum number of bytes the server will
accept in the HTTP header.

--baseurl controls the URL prefix that rclone serves from.  By default
rclone will serve from the root.  If you used --baseurl "/rclone" then
rclone would serve from a URL starting with "/rclone/".  This is
useful if you wish to proxy rclone serve.  Rclone automatically
inserts leading and trailing "/" on --baseurl, so --baseurl "rclone",
--baseurl "/rclone" and --baseurl "/rclone/" are all treated
identically.

--template allows a user to specify a custom markup template for http
and webdav serve functions.  The server exports the following markup
to be used within the template to server pages:

| Parameter   | Description |
| :---------- | :---------- |
| .Name       | The full path of a file/directory. |
| .Title      | Directory listing of .Name |
| .Sort       | The current sort used.  This is changeable via ?sort= parameter |
|             | Sort Options: namedirfist,name,size,time (default namedirfirst) |
| .Order      | The current ordering used.  This is changeable via ?order= parameter |
|             | Order Options: asc,desc (default asc) |
| .Query      | Currently unused. |
| .Breadcrumb | Allows for creating a relative navigation |
|-- .Link     | The relative to the root link of the Text. |
|-- .Text     | The Name of the directory. |
| .Entries    | Information about a specific file/directory. |
|-- .URL      | The 'url' of an entry.  |
|-- .Leaf     | Currently same as 'URL' but intended to be 'just' the name. |
|-- .IsDir    | Boolean for if an entry is a directory or not. |
|-- .Size     | Size in Bytes of the entry. |
|-- .ModTime  | The UTC timestamp of an entry. |

### Authentication

By default this will serve files without needing a login.

You can either use an htpasswd file which can take lots of users, or
set a single username and password with the --user and --pass flags.

Use --htpasswd /path/to/htpasswd to provide an htpasswd file.  This is
in standard apache format and supports MD5, SHA1 and BCrypt for basic
authentication.  Bcrypt is recommended.

To create an htpasswd file:

    touch htpasswd
    htpasswd -B htpasswd user
    htpasswd -B htpasswd anotherUser

The password file can be updated while rclone is running.

Use --realm to set the authentication realm.

### SSL/TLS

By default this will serve over http.  If you want you can serve over
https.  You will need to supply the --cert and --key flags.  If you
wish to do client side certificate validation then you will need to
supply --client-ca also.

--cert should be either a PEM encoded certificate or a concatenation
of that with the CA certificate.  --key should be the PEM encoded
private key and --client-ca should be the PEM encoded client
certificate authority certificate.

## VFS - Virtual File System

This command uses the VFS layer. This adapts the cloud storage objects
that rclone uses into something which looks much more like a disk
filing system.

Cloud storage objects have lots of properties which aren't like disk
files - you can't extend them or write to the middle of them, so the
VFS layer has to deal with that. Because there is no one right way of
doing this there are various options explained below.

The VFS layer also implements a directory cache - this caches info
about files and directories (but not the data) in memory.

## VFS Directory Cache

Using the `--dir-cache-time` flag, you can control how long a
directory should be considered up to date and not refreshed from the
backend. Changes made through the mount will appear immediately or
invalidate the cache.

    --dir-cache-time duration   Time to cache directory entries for. (default 5m0s)
    --poll-interval duration    Time to wait between polling for changes.

However, changes made directly on the cloud storage by the web
interface or a different copy of rclone will only be picked up once
the directory cache expires if the backend configured does not support
polling for changes. If the backend supports polling, changes will be
picked up within the polling interval.

You can send a `SIGHUP` signal to rclone for it to flush all
directory caches, regardless of how old they are.  Assuming only one
rclone instance is running, you can reset the cache like this:

    kill -SIGHUP $(pidof rclone)

If you configure rclone with a [remote control](/rc) then you can use
rclone rc to flush the whole directory cache:

    rclone rc vfs/forget

Or individual files or directories:

    rclone rc vfs/forget file=path/to/file dir=path/to/dir

## VFS File Buffering

The `--buffer-size` flag determines the amount of memory,
that will be used to buffer data in advance.

Each open file will try to keep the specified amount of data in memory
at all times. The buffered data is bound to one open file and won't be
shared.

This flag is a upper limit for the used memory per open file.  The
buffer will only use memory for data that is downloaded but not not
yet read. If the buffer is empty, only a small amount of memory will
be used.

The maximum memory used by rclone for buffering can be up to
`--buffer-size * open files`.

## VFS File Caching

These flags control the VFS file caching options. File caching is
necessary to make the VFS layer appear compatible with a normal file
system. It can be disabled at the cost of some compatibility.

For example you'll need to enable VFS caching if you want to read and
write simultaneously to a file.  See below for more details.

Note that the VFS cache is separate from the cache backend and you may
find that you need one or the other or both.

    --cache-dir string                   Directory rclone will use for caching.
    --vfs-cache-mode CacheMode           Cache mode off|minimal|writes|full (default off)
    --vfs-cache-max-age duration         Max age of objects in the cache. (default 1h0m0s)
    --vfs-cache-max-size SizeSuffix      Max total size of objects in the cache. (default off)
    --vfs-cache-poll-interval duration   Interval to poll the cache for stale objects. (default 1m0s)
    --vfs-write-back duration            Time to writeback files after last use when using cache. (default 5s)

If run with `-vv` rclone will print the location of the file cache.  The
files are stored in the user cache file area which is OS dependent but
can be controlled with `--cache-dir` or setting the appropriate
environment variable.

The cache has 4 different modes selected by `--vfs-cache-mode`.
The higher the cache mode the more compatible rclone becomes at the
cost of using disk space.

Note that files are written back to the remote only when they are
closed and if they haven't been accessed for --vfs-write-back
second. If rclone is quit or dies with files that haven't been
uploaded, these will be uploaded next time rclone is run with the same
flags.

If using --vfs-cache-max-size note that the cache may exceed this size
for two reasons.  Firstly because it is only checked every
--vfs-cache-poll-interval.  Secondly because open files cannot be
evicted from the cache.

### --vfs-cache-mode off

In this mode (the default) the cache will read directly from the remote and write
directly to the remote without caching anything on disk.

This will mean some operations are not possible

  * Files can't be opened for both read AND write
  * Files opened for write can't be seeked
  * Existing files opened for write must have O_TRUNC set
  * Files open for read with O_TRUNC will be opened write only
  * Files open for write only will behave as if O_TRUNC was supplied
  * Open modes O_APPEND, O_TRUNC are ignored
  * If an upload fails it can't be retried

### --vfs-cache-mode minimal

This is very similar to "off" except that files opened for read AND
write will be buffered to disk.  This means that files opened for
write will be a lot more compatible, but uses the minimal disk space.

These operations are not possible

  * Files opened for write only can't be seeked
  * Existing files opened for write must have O_TRUNC set
  * Files opened for write only will ignore O_APPEND, O_TRUNC
  * If an upload fails it can't be retried

### --vfs-cache-mode writes

In this mode files opened for read only are still read directly from
the remote, write only and read/write files are buffered to disk
first.

This mode should support all normal file system operations.

If an upload fails it will be retried at exponentially increasing
intervals up to 1 minute.

### --vfs-cache-mode full

In this mode all reads and writes are buffered to and from disk. When
data is read from the remote this is buffered to disk as well.

In this mode the files in the cache will be sparse files and rclone
will keep track of which bits of the files it has dowloaded.

So if an application only reads the starts of each file, then rclone
will only buffer the start of the file. These files will appear to be
their full size in the cache, but they will be sparse files with only
the data that has been downloaded present in them.

This mode should support all normal file system operations and is
otherwise identical to --vfs-cache-mode writes.

When reading a file rclone will read --buffer-size plus
--vfs-read-ahead bytes ahead.  The --buffer-size is buffered in memory
whereas the --vfs-read-ahead is buffered on disk.

When using this mode it is recommended that --buffer-size is not set
too big and --vfs-read-ahead is set large if required.

## VFS Performance

These flags may be used to enable/disable features of the VFS for
performance or other reasons.

In particular S3 and Swift benefit hugely from the --no-modtime flag
(or use --use-server-modtime for a slightly different effect) as each
read of the modification time takes a transaction.

    --no-checksum     Don't compare checksums on up/download.
    --no-modtime      Don't read/write the modification time (can speed things up).
    --no-seek         Don't allow seeking in files.
    --read-only       Mount read-only.

When rclone reads files from a remote it reads them in chunks. This
means that rather than requesting the whole file rclone reads the
chunk specified. This is advantageous because some cloud providers
account for reads being all the data requested, not all the data
delivered.

Rclone will keep doubling the chunk size requested starting at
--vfs-read-chunk-size with a maximum of --vfs-read-chunk-size-limit
unless it is set to "off" in which case there will be no limit.

    --vfs-read-chunk-size SizeSuffix        Read the source objects in chunks. (default 128M)
    --vfs-read-chunk-size-limit SizeSuffix  Max chunk doubling size (default "off")

Sometimes rclone is delivered reads or writes out of order. Rather
than seeking rclone will wait a short time for the in sequence read or
write to come in. These flags only come into effect when not using an
on disk cache file.

    --vfs-read-wait duration   Time to wait for in-sequence read before seeking. (default 20ms)
    --vfs-write-wait duration  Time to wait for in-sequence write before giving error. (default 1s)

## VFS Case Sensitivity

Linux file systems are case-sensitive: two files can differ only
by case, and the exact case must be used when opening a file.

File systems in modern Windows are case-insensitive but case-preserving:
although existing files can be opened using any case, the exact case used
to create the file is preserved and available for programs to query.
It is not allowed for two files in the same directory to differ only by case.

Usually file systems on macOS are case-insensitive. It is possible to make macOS
file systems case-sensitive but that is not the default

The "--vfs-case-insensitive" mount flag controls how rclone handles these
two cases. If its value is "false", rclone passes file names to the mounted
file system as-is. If the flag is "true" (or appears without a value on
command line), rclone may perform a "fixup" as explained below.

The user may specify a file name to open/delete/rename/etc with a case
different than what is stored on mounted file system. If an argument refers
to an existing file with exactly the same name, then the case of the existing
file on the disk will be used. However, if a file name with exactly the same
name is not found but a name differing only by case exists, rclone will
transparently fixup the name. This fixup happens only when an existing file
is requested. Case sensitivity of file names created anew by rclone is
controlled by an underlying mounted file system.

Note that case sensitivity of the operating system running rclone (the target)
may differ from case sensitivity of a file system mounted by rclone (the source).
The flag controls whether "fixup" is performed to satisfy the target.

If the flag is not provided on the command line, then its default value depends
on the operating system where rclone runs: "true" on Windows and macOS, "false"
otherwise. If the flag is provided without a value, then it is "true".

```
rclone serve http remote:path [flags]
```

## Options

```
      --addr string                            IPaddress:Port or :Port to bind server to. (default "localhost:8080")
      --baseurl string                         Prefix for URLs - leave blank for root.
      --cert string                            SSL PEM key (concatenation of certificate and CA certificate)
      --client-ca string                       Client certificate authority to verify clients with
      --dir-cache-time duration                Time to cache directory entries for. (default 5m0s)
      --dir-perms FileMode                     Directory permissions (default 0777)
      --file-perms FileMode                    File permissions (default 0666)
      --gid uint32                             Override the gid field set by the filesystem. (default 1000)
  -h, --help                                   help for http
      --htpasswd string                        htpasswd file - if not provided no authentication is done
      --key string                             SSL PEM Private key
      --max-header-bytes int                   Maximum size of request header (default 4096)
      --no-checksum                            Don't compare checksums on up/download.
      --no-modtime                             Don't read/write the modification time (can speed things up).
      --no-seek                                Don't allow seeking in files.
      --pass string                            Password for authentication.
      --poll-interval duration                 Time to wait between polling for changes. Must be smaller than dir-cache-time. Only on supported remotes. Set to 0 to disable. (default 1m0s)
      --read-only                              Mount read-only.
      --realm string                           realm for authentication (default "rclone")
      --server-read-timeout duration           Timeout for server reading data (default 1h0m0s)
      --server-write-timeout duration          Timeout for server writing data (default 1h0m0s)
      --template string                        User Specified Template.
      --uid uint32                             Override the uid field set by the filesystem. (default 1000)
      --umask int                              Override the permission bits set by the filesystem. (default 2)
      --user string                            User name for authentication.
      --vfs-cache-max-age duration             Max age of objects in the cache. (default 1h0m0s)
      --vfs-cache-max-size SizeSuffix          Max total size of objects in the cache. (default off)
      --vfs-cache-mode CacheMode               Cache mode off|minimal|writes|full (default off)
      --vfs-cache-poll-interval duration       Interval to poll the cache for stale objects. (default 1m0s)
      --vfs-case-insensitive                   If a file name not found, find a case insensitive match.
      --vfs-read-ahead SizeSuffix              Extra read ahead over --buffer-size when using cache-mode full.
      --vfs-read-chunk-size SizeSuffix         Read the source objects in chunks. (default 128M)
      --vfs-read-chunk-size-limit SizeSuffix   If greater than --vfs-read-chunk-size, double the chunk size after each chunk read, until the limit is reached. 'off' is unlimited. (default off)
      --vfs-read-wait duration                 Time to wait for in-sequence read before seeking. (default 20ms)
      --vfs-write-back duration                Time to writeback files after last use when using cache. (default 5s)
      --vfs-write-wait duration                Time to wait for in-sequence write before giving error. (default 1s)
```

See the [global flags page](/flags/) for global options not listed here.

## SEE ALSO

* [rclone serve](/commands/rclone_serve/)	 - Serve a remote over a protocol.


text:
package test;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import beans.student;
public class test_select_all
{
	public static void main(String[] args)
	{
		SessionFactory sf=new Configuration().configure("resources/oracle.cfg.xml").buildSessionFactory();
		Session s=sf.openSession();
		Transaction t=s.beginTransaction();
		String hql="select from student";
		Query q=s.createQuery(hql);
		List<String>list=q.list();
		student std=(student) q.uniqueResult();
		for(String name:list)
		 {
		   System.out.println(std.getRoll());
		   System.out.println(std.getName());
		   System.out.println(std.getEmail());
		   System.out.println(std.getMarks());
		 }
		s.close();
		sf.close();
   }
}


text:
<!doctype html>
<html lang="sv">
<meta charset="utf-8" />
<title>Python modulen cmd</title>

<!-- Mithril HTML Slideshow styles -->
<link href="../css/mithril-slideshow.css" rel="stylesheet" />

<!-- Code formatting using highlight.js -->
<link rel="stylesheet" href="../css/default.css">
<link rel="stylesheet" href="../css/tomorrow.css">
<script src="../js/highlight.pack.js"></script>

<!-- Text formatting using Markdown through showdown.js -->
<script src="../js/showdown.min.js"></script>

<!-- Here comes the slides in order -->
<script data-role="slide" data-markdown type="text/html">
#Python modulen cmd
###Mikael Roos, dbwebb
</script>

<!-- Slide -->
<script data-role="slide" data-markdown type="text/html">
#Agenda

* Om klasser i Python
* Om modulen cmd

</script>

<!-- Slide -->
<script data-role="slide" data-markdown type="text/html">
#Kodexemplet

* Kör kodexemplet tärning
* [I kursrepot](https://github.com/dbwebb-se/python/tree/master/example/cmd/dice)

</script>

<!-- Slide -->
<script data-role="slide" data-markdown type="text/html">
#Referenser

* [Random](https://docs.python.org/dev/library/random.html)
* [Modules](https://docs.python.org/3/tutorial/modules.html)
* [Class](https://docs.python.org/3.5/tutorial/classes.html)
* [Modulen cmd](https://docs.python.org/3/library/cmd.html)

</script>

<!-- Slide -->
<script data-role="slide" data-markdown type="text/html">
#Avslutningsvis

* Frågor på det?

</script>

<!-- Slide -->
<script data-role="slide" data-markdown type="text/html">
</script>

<!-- include essential js-script -->
<script src="../js/mithril.min.js"></script>
<script src="../js/mithril-slideshow.js"></script>


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Infrastructure.Validation;

namespace Squidex.Areas.Api.Controllers;

public sealed class RenameTagDto
{
    /// <summary>
    /// The new name for the tag.
    /// </summary>
    [LocalizedRequired]
    public string TagName { get; set; }
}


text: JavaScript Development Environment


text:
package eu.hansolo.steelseries.tools;

/**
 * Simply enum to define the different looks for the
 * frames of the components. The real colors and gradients
 * are defined in the drawing methods of the components.
 * @author hansolo
 */
public enum FrameDesign {

    BLACK_METAL,
    METAL,
    SHINY_METAL,
    GLOSSY_METAL,
    BRASS,
    STEEL,
    CHROME,
    GOLD,
    ANTHRACITE,
    TILTED_GRAY,
    TILTED_BLACK,
    CUSTOM
}


text:
from django.conf.urls import url

from .views import draft, drafts

urlpatterns = [
    url(r'^$', drafts, name='drafts'),
    url(r'^(?P<pk>\d+)/$', draft, name='draft'),
]


text:
var ValidationError = (function () {
    function ValidationError() {
    }
    return ValidationError;
})();

var DeploymentTemplate = (function () {
    function DeploymentTemplate() {
        this.$schema = "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#";
    }
    DeploymentTemplate.prototype.validation = function (errors) {
        if (!this.contentVersion) {
            var err = new ValidationError();

            //messages
            errors.push(err);
        } else if (!this.contentVersion.match("(^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$)")) {
            var err = new ValidationError();

            //messages
            errors.push(err);
        }
    };
    return DeploymentTemplate;
})();

var Parameter = (function () {
    function Parameter(name, type, defaultValue, allowedValues) {
        this.name = name;
        this.type = type;
        this.defaultValue = defaultValue;
        this.allowedValues = allowedValues;
    }
    return Parameter;
})();

var Resource = (function () {
    function Resource() {
    }
    return Resource;
})();
//# sourceMappingURL=ResourceFormer.js.map


text:
Home

Games

Game

    <form editable-form name="gameForm" onaftersave="Update()">

{{game.name}}Partially verifiedVerified

                    {{game.teams[0].name}}

vs

{{game.teams[1].name}}

Date

{{game.date | date:'longDate'}}

Location Name

{{game.location.name}}

Location Link

{{game.location.url}}

            <button type="button" class="btn btn-default btn-sm" ng-click="gameForm.$show()"
                ng-show="!gameForm.$visible && (user.properties.captain.value && (user.properties.team.value===game.teams[0]._id || user.properties.team.value===game.teams[1]._id) || user.properties.admin.value)"> Edit </button>

                <button class="btn btn-primary" ng-disabled="gameForm.$waiting"> Save </button>
                <button type="button" class="btn btn-danger" ng-disabled="gameForm.$waiting"
                    ng-click="gameForm.$cancel()"> Cancel </button>

Statistics

Game Time: {{game.time | date:'mm:ss'}}

                    Player
                    Position
                    Team
                    Statistic
                    Time

                    {{stat.player.name}}
                    {{stat.position.name}}
                    {{stat.team.name}}
                    {{stat.value | possessionFilter}} {{stat.name}}, {{stat.attribute}} ({{stat.type.name}})
                    {{stat.time | date:'h:mm:ss a'}}

                        Dispute

                            <input class="form-control form-group" type="text" ng-model="disputeReason"></input>
                            Submit
                            Cancel

                        Disputed

                            {{stat.dispute.reason}}

            Stat sign off

Disputes have been recorded.

    </form>


text:
using System;

namespace LoonyC.Compiler.Types
{
    class AnyType : TypeBase
    {
        public override int Size => 1;

        public AnyType(bool constant = false) : base(constant)
        {
            if (constant)
                throw new ArgumentException("'any' type can not be constant");
        }

        public override bool Equals(TypeBase other)
        {
            if (!base.Equals(other))
                return false;

            return other is AnyType;
        }

        public override bool IsAssignableTo(TypeBase other, int depth = 0, bool checkConst = true)
        {
            if (!base.IsAssignableTo(other, depth, checkConst))
                return false;

            return true;
        }

        public override string ToString()
        {
            return (IsConstant ? "const " : null) + "any";
        }

        public override int GetHashCode()
        {
            return 7;
        }
    }
}


text:
"""Support for Vanderbilt (formerly Siemens) SPC alarm systems."""
import logging

import voluptuous as vol

from homeassistant.helpers import discovery, aiohttp_client
from homeassistant.helpers.dispatcher import async_dispatcher_send
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

CONF_WS_URL = 'ws_url'
CONF_API_URL = 'api_url'

DOMAIN = 'spc'
DATA_API = 'spc_api'

SIGNAL_UPDATE_ALARM = 'spc_update_alarm_{}'
SIGNAL_UPDATE_SENSOR = 'spc_update_sensor_{}'

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Required(CONF_WS_URL): cv.string,
        vol.Required(CONF_API_URL): cv.string
    }),
}, extra=vol.ALLOW_EXTRA)

async def async_setup(hass, config):
    """Set up the SPC component."""
    from pyspcwebgw import SpcWebGateway

    async def async_upate_callback(spc_object):
        from pyspcwebgw.area import Area
        from pyspcwebgw.zone import Zone

        if isinstance(spc_object, Area):
            async_dispatcher_send(hass,
                                  SIGNAL_UPDATE_ALARM.format(spc_object.id))
        elif isinstance(spc_object, Zone):
            async_dispatcher_send(hass,
                                  SIGNAL_UPDATE_SENSOR.format(spc_object.id))

    session = aiohttp_client.async_get_clientsession(hass)

    spc = SpcWebGateway(loop=hass.loop, session=session,
                        api_url=config[DOMAIN].get(CONF_API_URL),
                        ws_url=config[DOMAIN].get(CONF_WS_URL),
                        async_callback=async_upate_callback)

    hass.data[DATA_API] = spc

    if not await spc.async_load_parameters():
        _LOGGER.error('Failed to load area/zone information from SPC.')
        return False

    # add sensor devices for each zone (typically motion/fire/door sensors)
    hass.async_create_task(discovery.async_load_platform(
        hass, 'binary_sensor', DOMAIN, {}, config))

    # create a separate alarm panel for each area
    hass.async_create_task(discovery.async_load_platform(
        hass, 'alarm_control_panel', DOMAIN, {}, config))

    # start listening for incoming events over websocket
    spc.start()

    return True


text:
FOUNDATION_EXPORT double Pods_SwiftCountryPicker_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_SwiftCountryPicker_TestsVersionString[];


text:
/**
 * Settings content module
 *
 * @param {Constants} constants
 * @param {Knockout} ko
 * @param {JQuery} $
 * @param {Moment} moment
 * @returns {SettingsViewModel}
 */
define(['model/Constants',
    'knockout',
    'jquery',
    'moment'],
    function (constants, ko, $, moment) {

        /**
         * The view model for the Settings panel.
         *
         * @constructor
         * @param {Globe} globe
         * @param {String} viewFragment HTML
         * @param {String} appendToId Parent element id
         * @returns {SettingsViewModel}
         */
        function SettingsViewModel(globe, viewFragment, appendToId) {
            var self = this,
                domNodes = $.parseHTML(viewFragment),
                skyLayer, starsLayer, atmosphereLayer, timeZoneLayer, viewControls, widgets, crosshairs,
                tessellation, frameStatistics;

            // Load the view html into the specified DOM element
            $("#" + appendToId).append(domNodes);
            this.view = domNodes[0];

            this.globe = globe;
            this.layerManager = globe.layerManager;

            skyLayer = this.layerManager.findLayer(constants.LAYER_NAME_SKY);
            starsLayer = this.layerManager.findLayer(constants.LAYER_NAME_STARS);
            atmosphereLayer = this.layerManager.findLayer(constants.LAYER_NAME_ATMOSPHERE);
            timeZoneLayer = this.layerManager.findLayer(constants.LAYER_NAME_TIME_ZONES);
            viewControls = this.layerManager.findLayer(constants.LAYER_NAME_VIEW_CONTROLS);
            widgets = this.layerManager.findLayer(constants.LAYER_NAME_WIDGETS);
            crosshairs = this.layerManager.findLayer(constants.LAYER_NAME_RETICLE);
            tessellation = this.layerManager.findLayer("Show Tessellation");
            frameStatistics = this.layerManager.findLayer("Frame Statistics");

            //
            // Observables
            //

            /**
             * The current state of the time zones layer (settable).
             */
            this.timeZonesEnabled = timeZoneLayer ? timeZoneLayer.enabled : ko.observable();
            /**
             * The current state of the time zones layer opacity (settable).
             */
            this.timeZonesOpacity = timeZoneLayer ? timeZoneLayer.opacity : ko.observable();
            /**
             * The globe's timeZoneDetectEnabled observable setting (settable).
             */
            this.timeZoneDetectEnabled = globe.timeZoneDetectEnabled;
            this.timeZoneDetectEnabled.subscribe(function (newValue) {
                self.timeZonesEnabled(newValue);
            });
            /**
             * The globe's use24Time observable setting.
             */
            this.use24Time = globe.use24Time;
            /**
             * Tracks the current background color selection. Used by radio buttons in the view.
             */
            this.backgroundColor = ko.observable(skyLayer && skyLayer.enabled() ? "blue" : "black");
            /**
             * The current state of the blue background layer (settable).
             */
            this.blueBackgroundEnabled = skyLayer ? skyLayer.enabled : ko.observable();
            /**
             * The state of the black background (read-only).
             */
            this.blackBackgroundEnabled = ko.computed(function () {
                return skyLayer ? !skyLayer.enabled() : true;
            });
            /**
             * The current state of the star field layer (settable).
             */
            this.starsBackgroundEnabled = starsLayer ? starsLayer.enabled : ko.observable();
            /**
             * The current state of the atmosphere layer (settable)
             */
            this.atmosphereBackgroundEnabled = atmosphereLayer ? atmosphereLayer.enabled : ko.observable();
            /**
             * The current opacity level for the atmosphere's nightime effect
             */
            this.nightOpacity = atmosphereLayer ? atmosphereLayer.opacity : ko.observable();

            this.dayNightEnabled = ko.observable(false);

            this.viewControlsEnabled = viewControls ? viewControls.enabled : ko.observable();
            this.widgetsEnabled = widgets ? widgets.enabled : ko.observable();
            this.crosshairsEnabled = crosshairs ? crosshairs.enabled : ko.observable();
            this.tessellationEnabled = tessellation ? tessellation.enabled : ko.observable();
            this.frameStatisticsEnabled = frameStatistics ? frameStatistics.enabled : ko.observable();

            /**
             * Background color selection handler
             * @param {String} newValue background color
             */
            this.backgroundColor.subscribe(function (newValue) {
                switch (newValue) {
                    case "blue":
                        self.blueBackgroundEnabled(true);
                        break;
                    case "black":
                        self.blueBackgroundEnabled(false);
                        // The sky background layer manipulates the canvas' background color.
                        // When it's disabled, the last used color remains in the canvas.
                        // Set the background color to the default when the background is disabled.
                        $(self.globe.wwd.canvas).css('background-color', 'black');
                        break;
                }
            });

            /**
             * Turn off stars if the default background layer is enabled.
             * @param {Boolean} newValue day/night ensbled state
             */
            this.dayNightEnabled.subscribe(function (newValue) {
                if (atmosphereLayer) {
                    atmosphereLayer.wwLayer.nightEnabled = newValue;
                }
                if (starsLayer) {
                    starsLayer.wwLayer.sunEnabled = newValue;
                }
                // Tickle the time to force a redraw of the day/night
                var time = new moment(globe.dateTime());
                globe.dateTime(time.add(1, 'ms').toDate());
                globe.redraw();
                globe.dateTime(time.subtract(1, 'ms').toDate());
                globe.redraw();

            });

            // Binds the view to this view model.
            ko.applyBindings(this, this.view);
        }

        return SettingsViewModel;
    }
);


text:
package com.coremedia.iso.boxes;

import com.coremedia.iso.IsoTypeReader;
import com.coremedia.iso.IsoTypeWriter;
import com.googlecode.mp4parser.AbstractContainerBox;
import com.googlecode.mp4parser.util.ByteBufferByteChannel;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * A common base structure to contain general metadata. See ISO/IEC 14496-12 Ch. 8.44.1.
 */
public class MetaBox extends AbstractContainerBox {
    private int version = 0;
    private int flags = 0;

    public static final String TYPE = "meta";

    public MetaBox() {
        super(TYPE);
    }

    @Override
    public long getContentSize() {
        if (isMp4Box()) {
            // it's a fullbox
            return 4 + super.getContentSize();
        } else {
            // it's an apple metabox
            return super.getContentSize();
        }
    }

    @Override
    public long getNumOfBytesToFirstChild() {
        if (isMp4Box()) {
            // it's a fullbox
            return 12;
        } else {
            // it's an apple metabox
            return 8;
        }
    }

    @Override
    public void _parseDetails(ByteBuffer content) {
        int pos = content.position();
        content.get(new byte[4]);
        String isHdlr = IsoTypeReader.read4cc(content);
        if ("hdlr".equals(isHdlr)) {
            //  this is apple bullshit - it's NO FULLBOX
            content.position(pos);
            version = -1;
            flags = -1;
        } else {
            content.position(pos);
            version = IsoTypeReader.readUInt8(content);
            flags = IsoTypeReader.readUInt24(content);
        }
        while (content.remaining() >= 8) {
            try {
                boxes.add(boxParser.parseBox(new ByteBufferByteChannel(content), this));
            } catch (IOException e) {
                throw new RuntimeException("Sebastian needs to fix 7518765283");
            }
        }
        if (content.remaining() > 0) {
            throw new RuntimeException("Sebastian needs to fix it 90732r26537");
        }
    }

    @Override
    protected void getContent(ByteBuffer byteBuffer) {
        if (isMp4Box()) {
            IsoTypeWriter.writeUInt8(byteBuffer, version);
            IsoTypeWriter.writeUInt24(byteBuffer, flags);
        }
        writeChildBoxes(byteBuffer);
    }

    public boolean isMp4Box() {
        return version != -1 && flags != -1;
    }

    public void setMp4Box(boolean mp4) {
        if (mp4) {
            version = 0;
            flags = 0;
        } else {
            version = -1;
            flags = -1;
        }
    }
}


text:
package torrent

import (
	"container/heap"
	"expvar"
	"fmt"
	"io"
	"log"
	"math"
	"math/rand"
	"net"
	"sort"
	"sync"
	"time"

	"github.com/anacrolix/missinggo"
	"github.com/anacrolix/missinggo/bitmap"
	"github.com/anacrolix/missinggo/itertools"
	"github.com/anacrolix/missinggo/perf"
	"github.com/anacrolix/missinggo/pubsub"
	"github.com/bradfitz/iter"

	"github.com/anacrolix/torrent/bencode"
	"github.com/anacrolix/torrent/metainfo"
	pp "github.com/anacrolix/torrent/peer_protocol"
	"github.com/anacrolix/torrent/storage"
)

func (t *Torrent) chunkIndexSpec(chunkIndex, piece int) chunkSpec {
	return chunkIndexSpec(chunkIndex, t.pieceLength(piece), t.chunkSize)
}

type peersKey struct {
	IPBytes string
	Port    int
}

// Maintains state of torrent within a Client.
type Torrent struct {
	cl *Client

	closing chan struct{}

	// Closed when no more network activity is desired. This includes
	// announcing, and communicating with peers.
	ceasingNetworking chan struct{}

	infoHash metainfo.Hash
	pieces   []piece
	// Values are the piece indices that changed.
	pieceStateChanges *pubsub.PubSub
	chunkSize         pp.Integer
	// Total length of the torrent in bytes. Stored because it's not O(1) to
	// get this from the info dict.
	length int64

	// The storage to open when the info dict becomes available.
	storageOpener storage.I
	// Storage for torrent data.
	storage storage.Torrent

	// The info dict. nil if we don't have it (yet).
	info *metainfo.InfoEx
	// Active peer connections, running message stream loops.
	conns []*connection
	// Set of addrs to which we're attempting to connect. Connections are
	// half-open until all handshakes are completed.
	halfOpen map[string]struct{}

	// Reserve of peers to connect to. A peer can be both here and in the
	// active connections if were told about the peer after connecting with
	// them. That encourages us to reconnect to peers that are well known.
	peers     map[peersKey]Peer
	wantPeers sync.Cond

	// BEP 12 Multitracker Metadata Extension. The tracker.Client instances
	// mirror their respective URLs from the announce-list metainfo key.
	trackers []trackerTier
	// Name used if the info name isn't available.
	displayName string
	// The bencoded bytes of the info dict.
	metadataBytes []byte
	// Each element corresponds to the 16KiB metadata pieces. If true, we have
	// received that piece.
	metadataCompletedChunks []bool

	// Closed when .Info is set.
	gotMetainfo chan struct{}

	readers map[*Reader]struct{}

	pendingPieces   bitmap.Bitmap
	completedPieces bitmap.Bitmap

	connPieceInclinationPool sync.Pool
}

var (
	pieceInclinationsReused = expvar.NewInt("pieceInclinationsReused")
	pieceInclinationsNew    = expvar.NewInt("pieceInclinationsNew")
	pieceInclinationsPut    = expvar.NewInt("pieceInclinationsPut")
)

func (t *Torrent) setDisplayName(dn string) {
	t.displayName = dn
}

func (t *Torrent) pieceComplete(piece int) bool {
	return t.completedPieces.Get(piece)
}

func (t *Torrent) pieceCompleteUncached(piece int) bool {
	return t.pieces[piece].Storage().GetIsComplete()
}

func (t *Torrent) numConnsUnchoked() (num int) {
	for _, c := range t.conns {
		if !c.PeerChoked {
			num++
		}
	}
	return
}

// There's a connection to that address already.
func (t *Torrent) addrActive(addr string) bool {
	if _, ok := t.halfOpen[addr]; ok {
		return true
	}
	for _, c := range t.conns {
		if c.remoteAddr().String() == addr {
			return true
		}
	}
	return false
}

func (t *Torrent) worstConns(cl *Client) (wcs *worstConns) {
	wcs = &worstConns{
		c:  make([]*connection, 0, len(t.conns)),
		t:  t,
		cl: cl,
	}
	for _, c := range t.conns {
		if !c.closed.IsSet() {
			wcs.c = append(wcs.c, c)
		}
	}
	return
}

func (t *Torrent) ceaseNetworking() {
	select {
	case <-t.ceasingNetworking:
		return
	default:
	}
	close(t.ceasingNetworking)
	for _, c := range t.conns {
		c.Close()
	}
}

func (t *Torrent) addPeer(p Peer, cl *Client) {
	cl.openNewConns(t)
	if len(t.peers) >= torrentPeersHighWater {
		return
	}
	key := peersKey{string(p.IP), p.Port}
	if _, ok := t.peers[key]; ok {
		return
	}
	t.peers[key] = p
	peersAddedBySource.Add(string(p.Source), 1)
	cl.openNewConns(t)

}

func (t *Torrent) invalidateMetadata() {
	t.metadataBytes = nil
	t.metadataCompletedChunks = nil
	t.info = nil
}

func (t *Torrent) saveMetadataPiece(index int, data []byte) {
	if t.haveInfo() {
		return
	}
	if index >= len(t.metadataCompletedChunks) {
		log.Printf("%s: ignoring metadata piece %d", t, index)
		return
	}
	copy(t.metadataBytes[(1<<14)*index:], data)
	t.metadataCompletedChunks[index] = true
}

func (t *Torrent) metadataPieceCount() int {
	return (len(t.metadataBytes) + (1 << 14) - 1) / (1 << 14)
}

func (t *Torrent) haveMetadataPiece(piece int) bool {
	if t.haveInfo() {
		return (1<<14)*piece < len(t.metadataBytes)
	} else {
		return piece < len(t.metadataCompletedChunks) && t.metadataCompletedChunks[piece]
	}
}

func (t *Torrent) metadataSizeKnown() bool {
	return t.metadataBytes != nil
}

func (t *Torrent) metadataSize() int {
	return len(t.metadataBytes)
}

func infoPieceHashes(info *metainfo.Info) (ret []string) {
	for i := 0; i < len(info.Pieces); i += 20 {
		ret = append(ret, string(info.Pieces[i:i+20]))
	}
	return
}

// Called when metadata for a torrent becomes available.
func (t *Torrent) setMetadata(md *metainfo.Info, infoBytes []byte) (err error) {
	err = validateInfo(md)
	if err != nil {
		err = fmt.Errorf("bad info: %s", err)
		return
	}
	t.info = &metainfo.InfoEx{
		Info:  *md,
		Bytes: infoBytes,
		Hash:  &t.infoHash,
	}
	t.storage, err = t.storageOpener.OpenTorrent(t.info)
	if err != nil {
		return
	}
	t.length = 0
	for _, f := range t.info.UpvertedFiles() {
		t.length += f.Length
	}
	t.metadataBytes = infoBytes
	t.metadataCompletedChunks = nil
	hashes := infoPieceHashes(md)
	t.pieces = make([]piece, len(hashes))
	for i, hash := range hashes {
		piece := &t.pieces[i]
		piece.t = t
		piece.index = i
		piece.noPendingWrites.L = &piece.pendingWritesMutex
		missinggo.CopyExact(piece.Hash[:], hash)
	}
	for _, conn := range t.conns {
		if err := conn.setNumPieces(t.numPieces()); err != nil {
			log.Printf("closing connection: %s", err)
			conn.Close()
		}
	}
	for i := range t.pieces {
		t.updatePieceCompletion(i)
		t.pieces[i].QueuedForHash = true
	}
	go func() {
		for i := range t.pieces {
			t.verifyPiece(i)
		}
	}()
	return
}

func (t *Torrent) verifyPiece(piece int) {
	t.cl.verifyPiece(t, piece)
}

func (t *Torrent) haveAllMetadataPieces() bool {
	if t.haveInfo() {
		return true
	}
	if t.metadataCompletedChunks == nil {
		return false
	}
	for _, have := range t.metadataCompletedChunks {
		if !have {
			return false
		}
	}
	return true
}

func (t *Torrent) setMetadataSize(bytes int64, cl *Client) {
	if t.haveInfo() {
		// We already know the correct metadata size.
		return
	}
	if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
		log.Printf("received bad metadata size: %d", bytes)
		return
	}
	if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
		return
	}
	t.metadataBytes = make([]byte, bytes)
	t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
	for _, c := range t.conns {
		cl.requestPendingMetadata(t, c)
	}

}

// The current working name for the torrent. Either the name in the info dict,
// or a display name given such as by the dn value in a magnet link, or "".
func (t *Torrent) name() string {
	if t.haveInfo() {
		return t.info.Name
	}
	return t.displayName
}

func (t *Torrent) pieceState(index int) (ret PieceState) {
	p := &t.pieces[index]
	ret.Priority = t.piecePriority(index)
	if t.pieceComplete(index) {
		ret.Complete = true
	}
	if p.QueuedForHash || p.Hashing {
		ret.Checking = true
	}
	if !ret.Complete && t.piecePartiallyDownloaded(index) {
		ret.Partial = true
	}
	return
}

func (t *Torrent) metadataPieceSize(piece int) int {
	return metadataPieceSize(len(t.metadataBytes), piece)
}

func (t *Torrent) newMetadataExtensionMessage(c *connection, msgType int, piece int, data []byte) pp.Message {
	d := map[string]int{
		"msg_type": msgType,
		"piece":    piece,
	}
	if data != nil {
		d["total_size"] = len(t.metadataBytes)
	}
	p, err := bencode.Marshal(d)
	if err != nil {
		panic(err)
	}
	return pp.Message{
		Type:            pp.Extended,
		ExtendedID:      c.PeerExtensionIDs["ut_metadata"],
		ExtendedPayload: append(p, data...),
	}
}

func (t *Torrent) pieceStateRuns() (ret []PieceStateRun) {
	rle := missinggo.NewRunLengthEncoder(func(el interface{}, count uint64) {
		ret = append(ret, PieceStateRun{
			PieceState: el.(PieceState),
			Length:     int(count),
		})
	})
	for index := range t.pieces {
		rle.Append(t.pieceState(index), 1)
	}
	rle.Flush()
	return
}

// Produces a small string representing a PieceStateRun.
func pieceStateRunStatusChars(psr PieceStateRun) (ret string) {
	ret = fmt.Sprintf("%d", psr.Length)
	ret += func() string {
		switch psr.Priority {
		case PiecePriorityNext:
			return "N"
		case PiecePriorityNormal:
			return "."
		case PiecePriorityReadahead:
			return "R"
		case PiecePriorityNow:
			return "!"
		default:
			return ""
		}
	}()
	if psr.Checking {
		ret += "H"
	}
	if psr.Partial {
		ret += "P"
	}
	if psr.Complete {
		ret += "C"
	}
	return
}

func (t *Torrent) writeStatus(w io.Writer, cl *Client) {
	fmt.Fprintf(w, "Infohash: %x\n", t.infoHash)
	fmt.Fprintf(w, "Metadata length: %d\n", t.metadataSize())
	if !t.haveInfo() {
		fmt.Fprintf(w, "Metadata have: ")
		for _, h := range t.metadataCompletedChunks {
			fmt.Fprintf(w, "%c", func() rune {
				if h {
					return 'H'
				} else {
					return '.'
				}
			}())
		}
		fmt.Fprintln(w)
	}
	fmt.Fprintf(w, "Piece length: %s\n", func() string {
		if t.haveInfo() {
			return fmt.Sprint(t.usualPieceSize())
		} else {
			return "?"
		}
	}())
	if t.haveInfo() {
		fmt.Fprintf(w, "Num Pieces: %d\n", t.numPieces())
		fmt.Fprint(w, "Piece States:")
		for _, psr := range t.pieceStateRuns() {
			w.Write([]byte(" "))
			w.Write([]byte(pieceStateRunStatusChars(psr)))
		}
		fmt.Fprintln(w)
	}
	fmt.Fprintf(w, "Reader Pieces:")
	t.forReaderOffsetPieces(func(begin, end int) (again bool) {
		fmt.Fprintf(w, " %d:%d", begin, end)
		return true
	})
	fmt.Fprintln(w)
	fmt.Fprintf(w, "Trackers: ")
	for _, tier := range t.trackers {
		for _, tr := range tier {
			fmt.Fprintf(w, "%q ", tr)
		}
	}
	fmt.Fprintf(w, "\n")
	fmt.Fprintf(w, "Pending peers: %d\n", len(t.peers))
	fmt.Fprintf(w, "Half open: %d\n", len(t.halfOpen))
	fmt.Fprintf(w, "Active peers: %d\n", len(t.conns))
	sort.Sort(&worstConns{
		c:  t.conns,
		t:  t,
		cl: cl,
	})
	for i, c := range t.conns {
		fmt.Fprintf(w, "%2d. ", i+1)
		c.WriteStatus(w, t)
	}
}

func (t *Torrent) String() string {
	s := t.name()
	if s == "" {
		s = fmt.Sprintf("%x", t.infoHash)
	}
	return s
}

func (t *Torrent) haveInfo() bool {
	return t.info != nil
}

// TODO: Include URIs that weren't converted to tracker clients.
func (t *Torrent) announceList() (al [][]string) {
	missinggo.CastSlice(&al, t.trackers)
	return
}

// Returns a run-time generated MetaInfo that includes the info bytes and
// announce-list as currently known to the client.
func (t *Torrent) metainfo() *metainfo.MetaInfo {
	if t.metadataBytes == nil {
		panic("info bytes not set")
	}
	return &metainfo.MetaInfo{
		Info:         *t.info,
		CreationDate: time.Now().Unix(),
		Comment:      "dynamic metainfo from client",
		CreatedBy:    "go.torrent",
		AnnounceList: t.announceList(),
	}
}

func (t *Torrent) bytesLeft() (left int64) {
	for i := 0; i < t.numPieces(); i++ {
		left += int64(t.pieces[i].bytesLeft())
	}
	return
}

// Bytes left to give in tracker announces.
func (t *Torrent) bytesLeftAnnounce() uint64 {
	if t.haveInfo() {
		return uint64(t.bytesLeft())
	} else {
		return math.MaxUint64
	}
}

func (t *Torrent) piecePartiallyDownloaded(piece int) bool {
	if t.pieceComplete(piece) {
		return false
	}
	if t.pieceAllDirty(piece) {
		return false
	}
	return t.pieces[piece].hasDirtyChunks()
}

func (t *Torrent) usualPieceSize() int {
	return int(t.info.PieceLength)
}

func (t *Torrent) lastPieceSize() int {
	return int(t.pieceLength(t.numPieces() - 1))
}

func (t *Torrent) numPieces() int {
	return t.info.NumPieces()
}

func (t *Torrent) numPiecesCompleted() (num int) {
	return t.completedPieces.Len()
}

// Safe to call with or without client lock.
func (t *Torrent) isClosed() bool {
	select {
	case <-t.closing:
		return true
	default:
		return false
	}
}

func (t *Torrent) close() (err error) {
	if t.isClosed() {
		return
	}
	t.ceaseNetworking()
	close(t.closing)
	if c, ok := t.storage.(io.Closer); ok {
		c.Close()
	}
	for _, conn := range t.conns {
		conn.Close()
	}
	t.pieceStateChanges.Close()
	return
}

func (t *Torrent) requestOffset(r request) int64 {
	return torrentRequestOffset(t.length, int64(t.usualPieceSize()), r)
}

// Return the request that would include the given offset into the torrent
// data. Returns !ok if there is no such request.
func (t *Torrent) offsetRequest(off int64) (req request, ok bool) {
	return torrentOffsetRequest(t.length, t.info.PieceLength, int64(t.chunkSize), off)
}

func (t *Torrent) writeChunk(piece int, begin int64, data []byte) (err error) {
	tr := perf.NewTimer()

	n, err := t.pieces[piece].Storage().WriteAt(data, begin)
	if err == nil && n != len(data) {
		err = io.ErrShortWrite
	}
	if err == nil {
		tr.Stop("write chunk")
	}
	return
}

func (t *Torrent) bitfield() (bf []bool) {
	bf = make([]bool, t.numPieces())
	t.completedPieces.IterTyped(func(piece int) (again bool) {
		bf[piece] = true
		return true
	})
	return
}

func (t *Torrent) validOutgoingRequest(r request) bool {
	if r.Index >= pp.Integer(t.info.NumPieces()) {
		return false
	}
	if r.Begin%t.chunkSize != 0 {
		return false
	}
	if r.Length > t.chunkSize {
		return false
	}
	pieceLength := t.pieceLength(int(r.Index))
	if r.Begin+r.Length > pieceLength {
		return false
	}
	return r.Length == t.chunkSize || r.Begin+r.Length == pieceLength
}

func (t *Torrent) pieceChunks(piece int) (css []chunkSpec) {
	css = make([]chunkSpec, 0, (t.pieceLength(piece)+t.chunkSize-1)/t.chunkSize)
	var cs chunkSpec
	for left := t.pieceLength(piece); left != 0; left -= cs.Length {
		cs.Length = left
		if cs.Length > t.chunkSize {
			cs.Length = t.chunkSize
		}
		css = append(css, cs)
		cs.Begin += cs.Length
	}
	return
}

func (t *Torrent) pieceNumChunks(piece int) int {
	return int((t.pieceLength(piece) + t.chunkSize - 1) / t.chunkSize)
}

func (t *Torrent) pendAllChunkSpecs(pieceIndex int) {
	t.pieces[pieceIndex].DirtyChunks.Clear()
}

type Peer struct {
	Id     [20]byte
	IP     net.IP
	Port   int
	Source peerSource
	// Peer is known to support encryption.
	SupportsEncryption bool
}

func (t *Torrent) pieceLength(piece int) (len_ pp.Integer) {
	if piece < 0 || piece >= t.info.NumPieces() {
		return
	}
	if piece == t.numPieces()-1 {
		len_ = pp.Integer(t.length % t.info.PieceLength)
	}
	if len_ == 0 {
		len_ = pp.Integer(t.info.PieceLength)
	}
	return
}

func (t *Torrent) hashPiece(piece int) (ret metainfo.Hash) {
	hash := pieceHash.New()
	p := &t.pieces[piece]
	p.waitNoPendingWrites()
	ip := t.info.Piece(piece)
	pl := ip.Length()
	n, err := io.Copy(hash, io.NewSectionReader(t.pieces[piece].Storage(), 0, pl))
	if n == pl {
		missinggo.CopyExact(&ret, hash.Sum(nil))
		return
	}
	if err != io.ErrUnexpectedEOF {
		log.Printf("unexpected error hashing piece with %T: %s", t.storage, err)
	}
	return
}

func (t *Torrent) haveAllPieces() bool {
	if !t.haveInfo() {
		return false
	}
	return t.completedPieces.Len() == t.numPieces()
}

func (me *Torrent) haveAnyPieces() bool {
	for i := range me.pieces {
		if me.pieceComplete(i) {
			return true
		}
	}
	return false
}

func (t *Torrent) havePiece(index int) bool {
	return t.haveInfo() && t.pieceComplete(index)
}

func (t *Torrent) haveChunk(r request) (ret bool) {
	// defer func() {
	// 	log.Println("have chunk", r, ret)
	// }()
	if !t.haveInfo() {
		return false
	}
	if t.pieceComplete(int(r.Index)) {
		return true
	}
	p := &t.pieces[r.Index]
	return !p.pendingChunk(r.chunkSpec, t.chunkSize)
}

func chunkIndex(cs chunkSpec, chunkSize pp.Integer) int {
	return int(cs.Begin / chunkSize)
}

// TODO: This should probably be called wantPiece.
func (t *Torrent) wantChunk(r request) bool {
	if !t.wantPiece(int(r.Index)) {
		return false
	}
	if t.pieces[r.Index].pendingChunk(r.chunkSpec, t.chunkSize) {
		return true
	}
	// TODO: What about pieces that were wanted, but aren't now, and aren't
	// completed either? That used to be done here.
	return false
}

// TODO: This should be called wantPieceIndex.
func (t *Torrent) wantPiece(index int) bool {
	if !t.haveInfo() {
		return false
	}
	p := &t.pieces[index]
	if p.QueuedForHash {
		return false
	}
	if p.Hashing {
		return false
	}
	if t.pieceComplete(index) {
		return false
	}
	if t.pendingPieces.Contains(index) {
		return true
	}
	return !t.forReaderOffsetPieces(func(begin, end int) bool {
		return index < begin || index >= end
	})
}

func (t *Torrent) forNeededPieces(f func(piece int) (more bool)) (all bool) {
	return t.forReaderOffsetPieces(func(begin, end int) (more bool) {
		for i := begin; begin < end; i++ {
			if !f(i) {
				return false
			}
		}
		return true
	})
}

func (t *Torrent) connHasWantedPieces(c *connection) bool {
	return !c.pieceRequestOrder.IsEmpty()
}

func (t *Torrent) extentPieces(off, _len int64) (pieces []int) {
	for i := off / int64(t.usualPieceSize()); i*int64(t.usualPieceSize()) < off+_len; i++ {
		pieces = append(pieces, int(i))
	}
	return
}

func (t *Torrent) worstBadConn(cl *Client) *connection {
	wcs := t.worstConns(cl)
	heap.Init(wcs)
	for wcs.Len() != 0 {
		c := heap.Pop(wcs).(*connection)
		if c.UnwantedChunksReceived >= 6 && c.UnwantedChunksReceived > c.UsefulChunksReceived {
			return c
		}
		if wcs.Len() >= (socketsPerTorrent+1)/2 {
			// Give connections 1 minute to prove themselves.
			if time.Since(c.completedHandshake) > time.Minute {
				return c
			}
		}
	}
	return nil
}

type PieceStateChange struct {
	Index int
	PieceState
}

func (t *Torrent) publishPieceChange(piece int) {
	cur := t.pieceState(piece)
	p := &t.pieces[piece]
	if cur != p.PublicPieceState {
		p.PublicPieceState = cur
		t.pieceStateChanges.Publish(PieceStateChange{
			piece,
			cur,
		})
	}
}

func (t *Torrent) pieceNumPendingChunks(piece int) int {
	if t.pieceComplete(piece) {
		return 0
	}
	return t.pieceNumChunks(piece) - t.pieces[piece].numDirtyChunks()
}

func (t *Torrent) pieceAllDirty(piece int) bool {
	return t.pieces[piece].DirtyChunks.Len() == t.pieceNumChunks(piece)
}

func (t *Torrent) forUrgentPieces(f func(piece int) (again bool)) (all bool) {
	return t.forReaderOffsetPieces(func(begin, end int) (again bool) {
		if begin < end {
			if !f(begin) {
				return false
			}
		}
		return true
	})
}

func (t *Torrent) readersChanged() {
	t.updatePiecePriorities()
}

func (t *Torrent) maybeNewConns() {
	// Tickle the accept routine.
	t.cl.event.Broadcast()
	t.openNewConns()
}

func (t *Torrent) piecePriorityChanged(piece int) {
	for _, c := range t.conns {
		c.updatePiecePriority(piece)
	}
	t.maybeNewConns()
	t.publishPieceChange(piece)
}

func (t *Torrent) updatePiecePriority(piece int) bool {
	p := &t.pieces[piece]
	newPrio := t.piecePriorityUncached(piece)
	if newPrio == p.priority {
		return false
	}
	p.priority = newPrio
	return true
}

// Update all piece priorities in one hit. This function should have the same
// output as updatePiecePriority, but across all pieces.
func (t *Torrent) updatePiecePriorities() {
	newPrios := make([]piecePriority, t.numPieces())
	t.pendingPieces.IterTyped(func(piece int) (more bool) {
		newPrios[piece] = PiecePriorityNormal
		return true
	})
	t.forReaderOffsetPieces(func(begin, end int) (next bool) {
		if begin < end {
			newPrios[begin].Raise(PiecePriorityNow)
		}
		for i := begin + 1; i < end; i++ {
			newPrios[i].Raise(PiecePriorityReadahead)
		}
		return true
	})
	t.completedPieces.IterTyped(func(piece int) (more bool) {
		newPrios[piece] = PiecePriorityNone
		return true
	})
	for i, prio := range newPrios {
		if prio != t.pieces[i].priority {
			t.pieces[i].priority = prio
			t.piecePriorityChanged(i)
		}
	}
}

func (t *Torrent) byteRegionPieces(off, size int64) (begin, end int) {
	if off >= t.length {
		return
	}
	if off < 0 {
		size += off
		off = 0
	}
	if size <= 0 {
		return
	}
	begin = int(off / t.info.PieceLength)
	end = int((off + size + t.info.PieceLength - 1) / t.info.PieceLength)
	if end > t.info.NumPieces() {
		end = t.info.NumPieces()
	}
	return
}

// Returns true if all iterations complete without breaking.
func (t *Torrent) forReaderOffsetPieces(f func(begin, end int) (more bool)) (all bool) {
	// There's an oppurtunity here to build a map of beginning pieces, and a
	// bitmap of the rest. I wonder if it's worth the allocation overhead.
	for r := range t.readers {
		r.mu.Lock()
		pos, readahead := r.pos, r.readahead
		r.mu.Unlock()
		if readahead < 1 {
			readahead = 1
		}
		begin, end := t.byteRegionPieces(pos, readahead)
		if begin >= end {
			continue
		}
		if !f(begin, end) {
			return false
		}
	}
	return true
}

func (t *Torrent) piecePriority(piece int) piecePriority {
	if !t.haveInfo() {
		return PiecePriorityNone
	}
	return t.pieces[piece].priority
}

func (t *Torrent) piecePriorityUncached(piece int) (ret piecePriority) {
	ret = PiecePriorityNone
	if t.pieceComplete(piece) {
		return
	}
	if t.pendingPieces.Contains(piece) {
		ret = PiecePriorityNormal
	}
	raiseRet := ret.Raise
	t.forReaderOffsetPieces(func(begin, end int) (again bool) {
		if piece == begin {
			raiseRet(PiecePriorityNow)
		}
		if begin <= piece && piece < end {
			raiseRet(PiecePriorityReadahead)
		}
		return true
	})
	return
}

func (t *Torrent) pendPiece(piece int) {
	if t.pendingPieces.Contains(piece) {
		return
	}
	if t.havePiece(piece) {
		return
	}
	t.pendingPieces.Add(piece)
	if !t.updatePiecePriority(piece) {
		return
	}
	t.piecePriorityChanged(piece)
}

func (t *Torrent) getCompletedPieces() (ret bitmap.Bitmap) {
	return t.completedPieces.Copy()
}

func (t *Torrent) unpendPieces(unpend *bitmap.Bitmap) {
	t.pendingPieces.Sub(unpend)
	t.updatePiecePriorities()
}

func (t *Torrent) pendPieceRange(begin, end int) {
	for i := begin; i < end; i++ {
		t.pendPiece(i)
	}
}

func (t *Torrent) unpendPieceRange(begin, end int) {
	var bm bitmap.Bitmap
	bm.AddRange(begin, end)
	t.unpendPieces(&bm)
}

func (t *Torrent) connRequestPiecePendingChunks(c *connection, piece int) (more bool) {
	if !c.PeerHasPiece(piece) {
		return true
	}
	chunkIndices := t.pieces[piece].undirtiedChunkIndices().ToSortedSlice()
	return itertools.ForPerm(len(chunkIndices), func(i int) bool {
		req := request{pp.Integer(piece), t.chunkIndexSpec(chunkIndices[i], piece)}
		return c.Request(req)
	})
}

func (t *Torrent) pendRequest(req request) {
	ci := chunkIndex(req.chunkSpec, t.chunkSize)
	t.pieces[req.Index].pendChunkIndex(ci)
}

func (t *Torrent) pieceChanged(piece int) {
	t.cl.pieceChanged(t, piece)
}

func (t *Torrent) openNewConns() {
	t.cl.openNewConns(t)
}

func (t *Torrent) getConnPieceInclination() []int {
	_ret := t.connPieceInclinationPool.Get()
	if _ret == nil {
		pieceInclinationsNew.Add(1)
		return rand.Perm(t.numPieces())
	}
	pieceInclinationsReused.Add(1)
	return _ret.([]int)
}

func (t *Torrent) putPieceInclination(pi []int) {
	t.connPieceInclinationPool.Put(pi)
	pieceInclinationsPut.Add(1)
}

func (t *Torrent) updatePieceCompletion(piece int) {
	pcu := t.pieceCompleteUncached(piece)
	changed := t.completedPieces.Get(piece) != pcu
	t.completedPieces.Set(piece, pcu)
	if changed {
		t.pieceChanged(piece)
	}
}

// Non-blocking read. Client lock is not required.
func (t *Torrent) readAt(b []byte, off int64) (n int, err error) {
	p := &t.pieces[off/t.info.PieceLength]
	p.waitNoPendingWrites()
	return p.Storage().ReadAt(b, off-p.Info().Offset())
}

func (t *Torrent) updateAllPieceCompletions() {
	for i := range iter.N(t.numPieces()) {
		t.updatePieceCompletion(i)
	}
}


text:
package com.apress.spring.domain;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JournalEntry {

	private String title;
	private Date created;
	private String summary;

	private final SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

	public JournalEntry(String title, String summary, String date) throws ParseException{
		this.title = title;
		this.summary = summary;
		this.created = format.parse(date);
	}

	JournalEntry(){}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getCreated() {
		return created;
	}

	public void setCreated(String date) throws ParseException{
		Long _date = null;
		try{
			_date = Long.parseLong(date);
			this.created = new Date(_date);
			return;
		}catch(Exception ex){}
		this.created = format.parse(date);
	}

	public String getSummary() {
		return summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	public String toString(){
		StringBuilder value = new StringBuilder("* JournalEntry(");
		value.append("Title: ");
		value.append(title);
		value.append(",Summary: ");
		value.append(summary);
		value.append(",Created: ");
		value.append(format.format(created));
		value.append(")");
		return value.toString();
	}
}


text:
package fr.univnantes.termsuite.model;

import java.util.List;

import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import fr.univnantes.termsuite.utils.StringUtils;

public class Word {

	private CompoundType compoundType;

	private String stem;
	private String lemma;

	private List<Component> components;

	private static final String MSG_NOT_COMPOUND = "Word <%s> is not a compound";
	private static final String MSG_NOT_NEOCLASSICAL = "Word <%s> is not a neoclassical compound.";
	private static final String MSG_NO_NEOCLASSICAL_COMPOUND = "No neoclassical compound found for word <%s>";

	public Word(String lemma, String stem) {
		this.lemma = lemma;
		this.stem = stem;
		resetComposition();
	}

	public void resetComposition() {
		components = ImmutableList.of();
		compoundType = CompoundType.UNSET;
	}

	public boolean isCompound() {
		return compoundType != CompoundType.UNSET && this.components.size() > 1;
	}

	public String getStem() {
		return stem;
	}

	public void setStem(String stem) {
		this.stem = stem;
	}

	public void setComponents(List<Component> components) {
		this.components = components;
	}

	public List<Component> getComponents() {
		return components;
	}

	@Override
	public String toString() {
		return MoreObjects.toStringHelper(this)
				.add("lemma", this.lemma)
				.add("isCompound", this.isCompound())
				.toString();
	}

	public CompoundType getCompoundType() {
		return compoundType;
	}

	public void setCompoundType(CompoundType compoundType) {
		this.compoundType = compoundType;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Word) {
			Word o = (Word) obj;
			return this.lemma.equals(o.lemma);
		} else
			return false;
	}

	@Override
	public int hashCode() {
		return this.lemma.hashCode();
	}

	private String normalizedStem;
	public String getNormalizedStem() {
		if(normalizedStem == null)
			this.normalizedStem = StringUtils.replaceAccents(stem).toLowerCase();
		return this.normalizedStem;
	}

	private String normalizedLemma;
	public String getNormalizedLemma() {
		if(normalizedLemma == null)
			this.normalizedLemma = StringUtils.replaceAccents(this.lemma).toLowerCase();
		return this.normalizedLemma;
	}

	/**
	 * Returns the {@link Component} object if
	 *
	 * @return
	 * 		The neoclassical component affix
	 *
	 * @throws IllegalStateException when this word is not a neoclassical compound
	 */
	public Component getNeoclassicalAffix() {
		Preconditions.checkState(isCompound(), MSG_NOT_COMPOUND, this);
		Preconditions.checkState(getCompoundType() == CompoundType.NEOCLASSICAL, MSG_NOT_NEOCLASSICAL, this);
		for(Component c:components)
			if(c.isNeoclassicalAffix())
				return c;
		throw new IllegalArgumentException(String.format(MSG_NO_NEOCLASSICAL_COMPOUND, this));
	}

	public String getLemma() {
		return lemma;
	}
}


text:
var util = require('util'),
should = require('should'),
NDDB = require('./../nddb').NDDB,
J = require('JSUS').JSUS;

var db = new NDDB();

var db = new NDDB();

db.hash('ha', function(i) {
    return i.id;
});
db.insert({id: 1});
db.insert({id: 2});

ADB.prototype = new NDDB();
ADB.prototype.constructor = ADB;

function ADB() {
    var options = {};
    options.update = {};
    options.update.indexes = true;
    NDDB.call(this, options);
    this.index('id', function(i) {
        return i.id;
    });
    this.hash('ha', function(i) {
        return i.id;
    });
    this.view('vi', function(i) {
        return i.id;
    });
}

ADB.prototype.remove = function(id) {
    this.id.remove(id);
};

var adb, adb2;
var out;

describe('ADB inherited class with view, index, and hash', function() {
    before(function() {
        adb = new ADB();
    });
    describe("#constructor()",function() {

        it("created obj should have empty index", function() {
            ('undefined' !== typeof adb.id).should.be.true;
        });
        it("created obj should have empty view", function() {
            ('undefined' !== typeof adb.vi).should.be.true;
        });
        it("created obj should have hash hash", function() {
            ('undefined' !== typeof adb.ha).should.be.true;
        });

        it("created obj should have view with empty index", function() {
            ('undefined' !== typeof adb.vi.id).should.be.true;
        });
        it("created obj should have view with empty hash", function() {
            ('undefined' !== typeof adb.vi.ha).should.be.true;
        });

    });

    describe("#insert()",function() {

        it("should return add 1 item to adb", function() {
            adb.insert({id: 1});
            adb.size().should.be.eql(1);
        });
        it("hash should have non-empty index", function() {
            ('undefined' !== typeof adb.ha[1].id).should.be.true;
            adb.ha[1].id.size().should.be.eql(1);
        });
        it("hash should have non-empty view", function() {
            ('undefined' !== typeof adb.ha[1].vi).should.be.true;
            adb.ha[1].vi.size().should.be.eql(1);
        });

        it("view should have non-empty index", function() {
            ('undefined' !== typeof adb.vi.id).should.be.true;
            adb.vi.id.size().should.be.eql(1);
        });
        it("view should have non-empty hash", function() {
            ('undefined' !== typeof adb.vi.ha[1]).should.be.true;
            adb.vi.ha[1].size().should.be.eql(1);
        });
    });

    describe("#breed()",function() {
        before(function() {
            adb2 = adb.breed();
        });
        it("adb2 should be instance of ADB", function() {
            adb.constructor.name.should.equal('ADB');
            ('function' === typeof adb.remove).should.be.true;
        });
    });

    describe("removing from index",function() {
        before(function() {
            adb.id.pop(1);
        });
        it("should reduce db size to 0", function() {
            adb.size().should.be.eql(0);
        });

        it("should reduce view size to 0", function() {
            adb.vi.size().should.be.eql(0);
        });
        it("should reduce index size in view to 0", function() {
            adb.vi.id.size().should.be.eql(0);
        });
        it("should reduce hash size in view to 0", function() {
            J.size(adb.vi.ha).should.be.eql(0);
        });

        it("should reduce hash size to 0", function() {
            J.size(adb.ha).should.be.eql(0);
        });
    });

    describe("#on('insert')", function() {
        before(function() {
            out = [];
            adb.on('insert', function(o) {
                out.push(o);
            });
            adb.insert({id: 100});
        });
        after(function() {
            adb.off('insert');
            out = null;
        });
        it('should call insert listener only once and not on hashes and views',
           function() {
               out.length.should.eql(1);
           });

    });

});


text:
<?php

/**
 * This file is part of the Nextras community extensions of Nette Framework
 *
 * @license    MIT
 * @link       https://github.com/nextras/forms
 * @author     Jan Skrasek
 */

namespace Nextras\Forms\Bridges\Latte\Macros;

use Nette\Forms\Controls\Button;
use Nette\Forms\Controls\ImageButton;
use Nette\Forms\Controls\SelectBox;
use Nette\Forms\Controls\TextBase;
use Nette\Utils\Html;
use Nette\Forms\Controls\BaseControl;
use Nextras;

class BS3InputMacros extends BaseInputMacros
{

	public static function label(Html $label, BaseControl $control)
	{
		if ($label->getName() === 'label') {
			$label->addClass('control-label');
		}

		return $label;
	}

	public static function input(Html $input, BaseControl $control)
	{
		$name = $input->getName();
		if ($name === 'select' || $name === 'textarea' || ($name === 'input' && !in_array($input->type, array('radio', 'checkbox', 'file', 'hidden', 'range', 'image', 'submit', 'reset')))) {
			$input->addClass('form-control');

		} elseif ($name === 'input' && ($input->type === 'submit' || $input->type === 'reset')) {
			$input->setName('button');
			$input->add($input->value);
			$input->addClass('btn');
		}

		return $input;
	}

}


text:
(function(global, doc) {

	var id = 0;
	var prefix = "__JSONP__";
	var head = doc.head;

	// Dynamic URI can be shared because we do not support reloading files
	var dynamicExtension = "&r=" + Date.now();

	/**
	 * Async JSON-P loader
	 *
	 */
	core.Module("core.io.Jsonp",
	{
		/** {Boolean} Whether the loader supports parallel requests. Always true for images. */
		SUPPORTS_PARALLEL : true,

		/**
		 * Loads an JSONP via the given @uri {String} and fires a @callback {Function} (in the given @context {Object?}) when the data was loaded.
		 * Optionally appends an random `GET` parameter to omit caching when @nocache {Boolean?false} is enabled.
		 */
		load : function load(uri, callback, context, nocache)
		{
			function JSONPResponse()
			{
				try {
					delete global[src]
				} catch(e) {
					global[src] = null;
				}

				head.removeChild(script);
				callback.apply(context||global, arguments);
			}

			var src = prefix + id++;
			var script = doc.createElement("script");

			global[src] = JSONPResponse;

			head.insertBefore(script, head.lastChild);
			script.src = uri + "=" + src + (nocache ? dynamicExtension : "");
		}
	});
})(this, document);


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="40dp"
    android:height="40dp"
    android:viewportWidth="40"
    android:viewportHeight="40"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M6.625,25.125V15.042H9.667V22.083H30.333V15.042H33.375V25.125Z"/>
</vector>


text:
package org.apache.geode.internal.offheap;

/**
 * Implements the Slab interface using AddressableMemoryManager.
 *
 * @since Geode 1.0
 */
public class SlabImpl implements Slab {
  private final long address;
  private final int size;

  public SlabImpl(int size) {
    this(size, false);
  }

  /**
   * This constructor is used by unit test to add padding to prevent intermittent combining of
   * fragments during defragmentation.
   */
  public SlabImpl(int size, boolean withPadding) {
    this(AddressableMemoryManager.allocate(size + (withPadding ? 4 : 0)), size);
  }

  public SlabImpl(long addr, int size) {
    address = addr;
    this.size = size;
  }

  @Override
  public int getSize() {
    return size;
  }

  @Override
  public long getMemoryAddress() {
    return address;
  }

  @Override
  public void free() {
    AddressableMemoryManager.free(address);
  }

  @Override
  public String toString() {
    return getClass().getSimpleName() + "{"
        + "MemoryAddress=" + getMemoryAddress()
        + ", Size=" + getSize()
        + "}";
  }
}


text:
import numpy as np
import itertools
from ..base import Model, ParamMixin, PhaseMixin
from ..input import Input
from ..loss import Loss
from ..feedforward.layers import Layer
from . import digraph

class GraphNetwork(Model, PhaseMixin):
    def __init__(self, graph):
        self.input = None
        self.graph = graph
        self._initialized = False
        self._fprop_topology = None
        self._bprop_topology = None
        self._graph_rev = None

    def _setup(self, **in_shapes):
        if self._initialized:
            return

#        for node, in_degree in self.graph.in_degree():
#            print(node, in_degree)
#        for node, in_degree in self.graph.out_degree():
#            print(node, in_degree)
        # TODO: check that only one node has in-degree 0
        # TODO: check that only one node has out-degree 0 and is Loss

        # Create data structures for fprop and bprop array passing
        self._fprop_topology = digraph.topological_sort(self.graph)
        self._graph_rev = digraph.reverse(self.graph)
        edges = self._graph_rev.edges(with_attr=True)
        for node1, node2, (port1, port2) in edges:
            self._graph_rev.remove_edge(node1, node2)
            self._graph_rev.add_edge(node1, node2, (port2+'_grad', port1+'_grad'))
        self._bprop_topology = digraph.topological_sort(self._graph_rev)

        shapes = {node: {} for node in self._fprop_topology}
        shapes[self._fprop_topology[0]] = in_shapes
        for node1 in self._fprop_topology:
            in_shapes = shapes[node1]
            node1._setup(**in_shapes)
            if node1 is self._fprop_topology[-1]:
                break
            if isinstance(node1, Layer):
                out_shapes = {'y': node1.y_shape(**in_shapes)}
            else:
                out_shapes = node1.out_shapes(**in_shapes)
            for node2, (port1, port2) in self.graph[node1].items():
                shapes[node2][port2 + '_shape'] = out_shapes[port1]
        self._initialized = True

    @property
    def _params(self):
        all_params = [node._params for node in self.graph.nodes()
                      if isinstance(node, ParamMixin)]
        # Concatenate lists in list
        return list(itertools.chain.from_iterable(all_params))

    @PhaseMixin.phase.setter
    def phase(self, phase):
        if self._phase == phase:
            return
        self._phase = phase
        for node in self.graph.nodes():
            if isinstance(node, PhaseMixin):
                node.phase = phase

    def _update(self, **arrays):
        self.phase = 'train'
        # Forward propagation
        inputs = {node: {} for node in self._fprop_topology}
        inputs[self._fprop_topology[0]] = arrays
        for node1 in self._fprop_topology[:-1]:
            out = node1.fprop(**inputs[node1])
            if isinstance(node1, Layer):
                out = {'y': out}
            for node2, (port1, port2) in self.graph[node1].items():
                inputs[node2][port2] = out[port1]

        loss_node = self._bprop_topology[0]
        grad = loss_node.grad(**inputs[loss_node])

        # Backward propagation
        grads = {node: {} for node in self._bprop_topology[1:]}
        for node2, (port1, port2) in self._graph_rev[loss_node].items():
            grads[node2][port2] = grad
        for node1 in self._bprop_topology[1:-1]:
            grad = node1.bprop(**grads[node1])
            if isinstance(node1, Layer):
                grad = {'x_grad': grad}
            for node2, (port1, port2) in self._graph_rev[node1].items():
                grads[node2][port2] = grad[port1]

        return loss_node.loss(**inputs[loss_node])

    def fprop(self, **arrays):
        inputs = {node: {} for node in self._fprop_topology}
        inputs[self._fprop_topology[0]] = arrays
        for node1 in self._fprop_topology[:-1]:
            out = node1.fprop(**inputs[node1])
            if isinstance(node1, Layer):
                out = {'y': out}
            for node2, (port1, port2) in self.graph[node1].items():
                inputs[node2][port2] = out[port1]
        last_node = self._fprop_topology[-1]
        out = last_node.fprop(**inputs[last_node])
        if isinstance(node1, Layer):
            out = {'y': out}
        return out

    def out_shapes(self, **in_shapes):
        shapes = {node: {} for node in self._fprop_topology}
        shapes[self._fprop_topology[0]] = in_shapes
        for node1 in self._fprop_topology[:-1]:
            in_shapes = shapes[node1]
            if isinstance(node1, Layer):
                out_shapes = {'y': node1.y_shape(**in_shapes)}
            else:
                out_shapes = node1.out_shapes(**in_shapes)
            for node2, (port1, port2) in self.graph[node1].items():
                shapes[node2][port2 + '_shape'] = out_shapes[port1]
        last_node = self._fprop_topology[-1]
        if isinstance(last_node, Layer):
            out_shape = {'y': last_node.y_shape(**shapes[last_node])}
        else:
            out_shape = last_node.out_shapes(**shapes[last_node])
        return out_shape


text:
<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Propagation;

use OpenTelemetry\Context\Propagation\MultiTextMapPropagator;
use OpenTelemetry\Context\Propagation\NoopTextMapPropagator;
use OpenTelemetry\Context\Propagation\TextMapPropagatorInterface;
use OpenTelemetry\SDK\Behavior\LogsMessagesTrait;
use OpenTelemetry\SDK\Common\Configuration\Configuration;
use OpenTelemetry\SDK\Common\Configuration\KnownValues;
use OpenTelemetry\SDK\Common\Configuration\Variables;

class PropagatorFactory
{
    use LogsMessagesTrait;

    private const KNOWN_PROPAGATORS = [
        KnownValues::VALUE_TRACECONTEXT => ['\OpenTelemetry\API\Trace\Propagation\TraceContextPropagator', 'getInstance'],
        KnownValues::VALUE_BAGGAGE => ['\OpenTelemetry\API\Baggage\Propagation\BaggagePropagator', 'getInstance'],
        KnownValues::VALUE_B3 => ['\OpenTelemetry\Extension\Propagator\B3\B3Propagator', 'getB3SingleHeaderInstance'],
        KnownValues::VALUE_B3_MULTI => ['\OpenTelemetry\Extension\Propagator\B3\B3Propagator', 'getB3MultiHeaderInstance'],
    ];

    public function create(): TextMapPropagatorInterface
    {
        $propagators = Configuration::getList(Variables::OTEL_PROPAGATORS);
        switch (count($propagators)) {
            case 0:
                return new NoopTextMapPropagator();
            case 1:
                return $this->buildPropagator($propagators[0]) ?? new NoopTextMapPropagator();
            default:
                return new MultiTextMapPropagator($this->buildPropagators($propagators));
        }
    }

    /**
     * @return array<TextMapPropagatorInterface>
     */
    private function buildPropagators(array $names): array
    {
        $propagators = [];
        foreach ($names as $name) {
            $propagator = $this->buildPropagator($name);
            if ($propagator !== null) {
                $propagators[] = $propagator;
            }
        }

        return $propagators;
    }

    private function buildPropagator(string $name): ?TextMapPropagatorInterface
    {
        switch ($name) {
            case KnownValues::VALUE_NONE:
                return null;
            case KnownValues::VALUE_XRAY:
            case KnownValues::VALUE_OTTRACE:
                self::logWarning('Unimplemented propagator: ' . $name);

                return null;
            default:
                if (!array_key_exists($name, self::KNOWN_PROPAGATORS)) {
                    self::logWarning('Unknown propagator: ' . $name);

                    return null;
                }
                $parts = self::KNOWN_PROPAGATORS[$name];

                try {
                    return call_user_func($parts);
                } catch (\Throwable $e) {
                    self::logError(sprintf('Unable to create %s propagator: %s', $name, $e->getMessage()));

                    return null;
                }

        }
    }
}