text:
StaticPlaneBodyConstraint::StaticPlaneBodyConstraint( const unsigned body_idx, const Vector3s& collision_point, const Vector3s& n, const VectorXs& q, const unsigned plane_idx )
: m_idx_body( body_idx )
, m_n( n )
, m_r( collision_point - q.segment<3>( 3 * m_idx_body ) )
, m_idx_plane( plane_idx )
{
  assert( fabs( m_n.norm() - 1.0 ) <= 1.0e-6 );
}

StaticPlaneBodyConstraint::~StaticPlaneBodyConstraint()
{}

scalar StaticPlaneBodyConstraint::evalNdotV( const VectorXs& q, const VectorXs& v ) const
{
  assert( v.size() % 6 == 0 );
  assert( 3 * ( m_idx_body + v.size() / 6 ) + 2 < v.size() );
  return m_n.dot( computeRelativeVelocity( q, v ) );
}

//void StaticPlaneBodyConstraint::exertImpulse( const VectorXs& q, const scalar& lambda, const SparseMatrixsc& Minv, VectorXs& vout ) const
//{
//  assert( vout.size() % 6 == 0 ); assert( 3 * ( m_idx_body + vout.size() / 6 ) + 2 < vout.size() );
//  assert( Minv.rows() == Minv.cols() ); assert( Minv.nonZeros() == 2 * vout.size() );
//  assert( Minv.valuePtr()[ 3 * m_idx_body ] > 0.0 );
//  assert( Minv.valuePtr()[ 3 * m_idx_body ] == Minv.valuePtr()[ 3 * m_idx_body + 1 ] );
//  assert( Minv.valuePtr()[ 3 * m_idx_body ] == Minv.valuePtr()[ 3 * m_idx_body + 2 ] );
//
//  const unsigned nbodies = vout.size() / 6;
//
//  vout.segment<3>( 3 * m_idx_body ) += Minv.valuePtr()[ 3 * m_idx_body ] * lambda * m_n;
//
//  const Vector3s ntilde = m_r.cross( m_n );
//
//  // Retrieve the inverse mass matrix for this body
//  const Eigen::Map<const Matrix33sr> Iinv = Eigen::Map<const Matrix33sr>( &Minv.valuePtr()[3 * nbodies + 9 * m_idx_body] );
//  assert( ( Iinv - Iinv.transpose() ).lpNorm<Eigen::Infinity>() <= 1.0e-6 );
//
//  vout.segment<3>( 3 * ( m_idx_body + nbodies ) ) += lambda * Iinv * ntilde;
//}

void StaticPlaneBodyConstraint::evalgradg( const VectorXs& q, const int col, SparseMatrixsc& G, const FlowableSystem& fsys ) const
{
  assert( col >= 0 );
  assert( col < G.cols() );
  assert( q.size() % 12 == 0 );

  const unsigned nbodies{ static_cast<unsigned>( q.size() / 12 ) };

  // MUST BE ADDED GOING DOWN THE COLUMN. DO NOT TOUCH ANOTHER COLUMN.
  G.insert( 3 * m_idx_body + 0, col ) = m_n.x();
  G.insert( 3 * m_idx_body + 1, col ) = m_n.y();
  G.insert( 3 * m_idx_body + 2, col ) = m_n.z();

  {
    const Vector3s ntilde{ m_r.cross( m_n ) };
    G.insert( 3 * ( m_idx_body + nbodies ) + 0, col ) = ntilde.x();
    G.insert( 3 * ( m_idx_body + nbodies ) + 1, col ) = ntilde.y();
    G.insert( 3 * ( m_idx_body + nbodies ) + 2, col ) = ntilde.z();
  }
}

void StaticPlaneBodyConstraint::computeGeneralizedFrictionDisk( const VectorXs& q, const VectorXs& v, const int start_column, const int num_samples, SparseMatrixsc& D, VectorXs& drel ) const
{
  assert( start_column >= 0 );
  assert( start_column < D.cols() );
  assert( num_samples > 0 );
  assert( start_column + num_samples - 1 < D.cols() );
  assert( q.size() % 12 == 0 );
  assert( q.size() == 2 * v.size() );

  std::vector<Vector3s> friction_disk( static_cast<std::vector<Vector3s>::size_type>( num_samples ) );
  assert( friction_disk.size() == std::vector<Vector3s>::size_type( num_samples ) );
  {
    // Compute the relative velocity
    Vector3s tangent_suggestion{ computeRelativeVelocity( q, v ) };
    if( tangent_suggestion.cross( m_n ).squaredNorm() < 1.0e-9 )
    {
      tangent_suggestion = FrictionUtilities::orthogonalVector( m_n );
    }
    tangent_suggestion *= -1.0;

    // Sample the friction disk
    friction_disk.resize( num_samples );
    FrictionUtilities::generateOrthogonalVectors( m_n, friction_disk, tangent_suggestion );
  }
  assert( unsigned( num_samples ) == friction_disk.size() );

  // For each sample of the friction disk
  const unsigned nbodies{ static_cast<unsigned>( q.size() / 12 ) };
  for( unsigned friction_sample = 0; friction_sample < unsigned( num_samples ); ++friction_sample )
  {
    const unsigned cur_col{ start_column + friction_sample };
    assert( cur_col < unsigned( D.cols() ) );

    // Effect on center of mass
    assert( fabs( friction_disk[friction_sample].norm() - 1.0 ) <= 1.0e-6 );
    D.insert( 3 * m_idx_body + 0, cur_col ) = friction_disk[friction_sample].x();
    D.insert( 3 * m_idx_body + 1, cur_col ) = friction_disk[friction_sample].y();
    D.insert( 3 * m_idx_body + 2, cur_col ) = friction_disk[friction_sample].z();

    // Effect on orientation
    {
      const Vector3s ntilde{ m_r.cross( friction_disk[friction_sample] ) };
      D.insert( 3 * ( nbodies + m_idx_body ) + 0, cur_col ) = ntilde.x();
      D.insert( 3 * ( nbodies + m_idx_body ) + 1, cur_col ) = ntilde.y();
      D.insert( 3 * ( nbodies + m_idx_body ) + 2, cur_col ) = ntilde.z();
    }

    // Relative velocity contribution from kinematic scripting
    assert( cur_col < drel.size() );
    // Zero for now
    drel( cur_col ) = 0.0;
  }
}

void StaticPlaneBodyConstraint::computeGeneralizedFrictionGivenTangentSample( const VectorXs& q, const VectorXs& t, const unsigned column, SparseMatrixsc& D ) const
{
  assert( column < unsigned( D.cols() ) );
  assert( q.size() % 12 == 0 );
  assert( t.size() == 3 );
  assert( fabs( t.norm() - 1.0 ) <= 1.0e-6 );
  assert( fabs( m_n.dot( t ) ) <= 1.0e-6 );

  const unsigned nbodies{ static_cast<unsigned>( q.size() / 12 ) };

  // Effect on center of mass of body i
  D.insert( 3 * m_idx_body + 0, column ) = t.x();
  D.insert( 3 * m_idx_body + 1, column ) = t.y();
  D.insert( 3 * m_idx_body + 2, column ) = t.z();
  // Effect on orientation of body i
  {
    const Vector3s ntilde{ m_r.cross( Eigen::Map<const Vector3s>{ t.data() } ) };
    D.insert( 3 * ( m_idx_body + nbodies ) + 0, column ) = ntilde.x();
    D.insert( 3 * ( m_idx_body + nbodies ) + 1, column ) = ntilde.y();
    D.insert( 3 * ( m_idx_body + nbodies ) + 2, column ) = ntilde.z();
  }
}

int StaticPlaneBodyConstraint::impactStencilSize() const
{
  return 6;
}

int StaticPlaneBodyConstraint::frictionStencilSize() const
{
  return 6;
}

void StaticPlaneBodyConstraint::getSimulatedBodyIndices( std::pair<int,int>& bodies ) const
{
  bodies.first = m_idx_body;
  bodies.second = -1;
}

void StaticPlaneBodyConstraint::getBodyIndices( std::pair<int,int>& bodies ) const
{
  this->getSimulatedBodyIndices( bodies );
}

void StaticPlaneBodyConstraint::evalKinematicNormalRelVel( const VectorXs& q, const int strt_idx, VectorXs& gdotN ) const
{
  assert( strt_idx >= 0 );
  assert( strt_idx < gdotN.size() );

  // No kinematic scripting here, yet
  gdotN( strt_idx ) = 0.0;
}

void StaticPlaneBodyConstraint::evalH( const VectorXs& q, const MatrixXXsc& basis, MatrixXXsc& H0, MatrixXXsc& H1 ) const
{
  assert( H0.rows() == 3 );
  assert( H0.cols() == 6 );
  assert( H1.rows() == 3 );
  assert( H1.cols() == 6 );

  // Grab the contact normal
  const Vector3s n{ basis.col( 0 ) };
  // Grab the tangent basis
  const Vector3s s{ basis.col( 1 ) };
  const Vector3s t{ basis.col( 2 ) };
  assert( MathUtilities::isRightHandedOrthoNormal( n, s, t, 1.0e-6 ) );

  H0.block<1,3>(0,0) = n;
  H0.block<1,3>(0,3) = m_r.cross( n );

  H0.block<1,3>(1,0) = s;
  H0.block<1,3>(1,3) = m_r.cross( s );

  H0.block<1,3>(2,0) = t;
  H0.block<1,3>(2,3) = m_r.cross( t );
}

bool StaticPlaneBodyConstraint::conservesTranslationalMomentum() const
{
  return false;
}

bool StaticPlaneBodyConstraint::conservesAngularMomentumUnderImpact() const
{
  return false;
}

bool StaticPlaneBodyConstraint::conservesAngularMomentumUnderImpactAndFriction() const
{
  return false;
}

std::string StaticPlaneBodyConstraint::name() const
{
  return "static_plane_body";
}

void StaticPlaneBodyConstraint::getWorldSpaceContactPoint( const VectorXs& q, VectorXs& contact_point ) const
{
  contact_point = q.segment<3>( 3 * m_idx_body ) + m_r;
}

void StaticPlaneBodyConstraint::getWorldSpaceContactNormal( const VectorXs& q, VectorXs& contact_normal ) const
{
  contact_normal = m_n;
}

unsigned StaticPlaneBodyConstraint::getStaticObjectIndex() const
{
  return m_idx_plane;
}

void StaticPlaneBodyConstraint::computeContactBasis( const VectorXs& q, const VectorXs& v, MatrixXXsc& basis ) const
{
  assert( fabs( m_n.norm() - 1.0 ) <= 1.0e-6 );

  // Compute the relative velocity to use as a direction for the tangent sample
  Vector3s s{ computeRelativeVelocity( q, v ) };
  // If the relative velocity is zero, any vector will do
  if( m_n.cross( s ).squaredNorm() < 1.0e-9 )
  {
    s = FrictionUtilities::orthogonalVector( m_n );
  }
  // Otherwise project out the component along the normal and normalize the relative velocity
  else
  {
    s = ( s - s.dot( m_n ) * m_n ).normalized();
  }
  // Invert the tangent vector in order to oppose
  s *= -1.0;

  // Create a second orthogonal sample in the tangent plane
  const Vector3s t{ m_n.cross( s ).normalized() }; // Don't need to normalize but it won't hurt

  assert( MathUtilities::isRightHandedOrthoNormal( m_n, s, t, 1.0e-6 ) );
  basis.resize( 3, 3 );
  basis.col( 0 ) = m_n;
  basis.col( 1 ) = s;
  basis.col( 2 ) = t;
}

VectorXs StaticPlaneBodyConstraint::computeRelativeVelocity( const VectorXs& q, const VectorXs& v ) const
{
  assert( v.size() % 6 == 0 );
  assert( 3 * ( m_idx_body + v.size() / 6 ) + 2 < v.size() );

  const unsigned nbodies{ static_cast<unsigned>( v.size() / 6 ) };

  // v + omega x r
  return v.segment<3>( 3 * m_idx_body ) + v.segment<3>( 3 * ( nbodies + m_idx_body ) ).cross( m_r );
}

void StaticPlaneBodyConstraint::setBodyIndex0( const unsigned idx )
{
  m_idx_body = idx;
}

VectorXs StaticPlaneBodyConstraint::computeKinematicRelativeVelocity( const VectorXs& q, const VectorXs& v ) const
{
  // IMPORTANT NOTE: This code has not been updated to treat kinematic boundaries, yet. If this is important to you, please email smith@cs.columbia.edu
  // TODO: Fixing this will require mirroring the structure of StaticPlaneSphereConstraint
  return VectorXs::Zero( 3 );
}


text:
  hubcaps

   a Rust interface for GitHub

## installation

Add the following to your `Cargo.toml` file

```toml
[dependencies]
hubcaps = "0.6"
```

## usage

Basic usage requires a user agent string and
optionally a flavor of `hubcaps::Credentials` for making requests as a particular
GitHub user.

For user authenticated requests you'll typically want to use
`hubcaps::Credentials::Token` with a
[personal access token](https://github.com/settings/tokens).

```rust
use hubcaps::{Credentials, Github};

fn main() {
  let github = Github::new(
    "my-cool-user-agent/0.1.0",
    Credentials::Token("personal-access-token".to_string()),
  );
}
```

GitHub instances define methods for accessing api services that map closely to
their url structure.

As a convention, api methods that expect arguments are represented as functions
that accept a struct representing those arguments with an optional builder
interface for convenience of construction.

See [examples directory](examples/) for some getting started examples

### repositories

Typically the reference point of most GitHub services is a repository

```rust
let repo = github.repo("user", "repo");
```

With a repo instance on hand, you can access a number of sub services,
like `labels`, `deployments`, `pulls`, `issues`, `releases`, and many more.
Each of this are named functions exported from the repo interface.

See [examples directory](examples/repos.rs) for examples

### branches

Branches is a service for listing repository branches

```rust
let branches = repo.branches();
```

### labels

Labels is a service for tagging resources like issues and pulls with names which you can later group and filter on.

```rust
use hubcaps::labels::LabelOptions;

let labels = repo.labels();

// create new labels
labels.create(
    &LabelOptions::new(
      "rustic", "ccc"
    )
  )
```

### deployments

Deployments is a service for orchestrating deployments of applications sourced from GitHub repositories

```rust
let deployments = repo.deployments();
```

See [examples directory](examples/deployments.rs) for examples

### pulls

Pulls is a service for issuing code change requests against a repository

```rust
let pulls = repo.pulls();
```

See [examples directory](examples/pulls.rs) for examples

### issues

Issues is a service for tracking bugs for a repository

```rust
let issues = repo.issues();
```

See [examples directory](examples/issues.rs) for examples

### releases

Releases is a service for tracking changes for a stable releases of a versioned library or application

```rust
let releases = repo.releases();
```

### gists

Gists is a service for micro repositories

```rust
let gists = github.gists();
```

See [examples directory](examples/gists.rs) for examples

### hooks

Hooks is a service for managing repository hooks

```rust
let hooks = repo.hooks();
```

See [examples directory](examples/hooks.rs) for examples

### search

Search provides a raw string query search for indexed data. Currently only search for issues is supported

```rust
let search_issues = github.search().issues();
```

### teams

Teams is a service for listing repository and organization teams

```rust
let teams = repo.teams();
```

See [examples directory](examples/teams.rs) for examples

Doug Tangren (softprops) 2015-2020

redpajama_set_name: RedPajamaGithub


text: DELETE FROM attribute_mapper.users;


text:
pruebas repo curso git

Lo cambiamos con dos bolas

el usr 3 mete mas cosas

p2 mete cosas

p1 mete lo suyo

p2 mete cosas de nuevo
p2 mete por segunda

p1 mete por segunda

p2 mete por tercera

p1 por tervera


text:
rock.namespace('pong.engine');

/**
 * Pong game engine
 *
 * @param {rock.graphics.engine.WebGLGraphicsEngine} graphicsEngine
 *
 * @param {rock.game.Repository} repository
 *
 * @constructor
 * @extends rock.game.engine.GameEngine
 *
 * @author Luis Alberto Jiménez
 */
pong.engine.PongEngine = function (graphicsEngine, repository) {
    var renderEngine = new rock.game.graphics.engine.webgl.RockBasicRenderEngine(graphicsEngine);
    renderEngine.setClearColor(rock.graphics.Color.BLACK.clone());
    var representationAttendant = new pong.engine.RepresentationAttendant(renderEngine, repository);
    rock.super_(this, [renderEngine, representationAttendant]);

    this.CAMERA_POSITION = new rock.geometry.Point3(0, 50, 80);
    this.CAMERA_CENTER = new rock.geometry.Point3(0, 0, 0);
    this.CAMERA_LOOKUP = new rock.geometry.Vector3(0, 1, 0);
    this.FOV = 60;
    this.ZNEAR = 0.1;
    this.ZFAR = 200;

    this.pongState = new pong.engine.PongState();
};

rock.extends_(pong.engine.PongEngine, rock.game.engine.GameEngine);

pong.engine.PongEngine.prototype.prepareGame = function () {
    this.createLighting();
    this.createCamera();
    this.createCourt();
    this.createAdapters();
    this.createRepresentations();
};

pong.engine.PongEngine.prototype.createLighting = function () {
    var directionalLight = new rock.game.graphics.lighting.DirectionalLight();
    directionalLight.setPosition(0, 0, 1);
    directionalLight.setAmbient(255, 255, 255);
    directionalLight.setDiffuse(255, 255, 255);
    directionalLight.setSpecular(255, 255, 255);

    var directionalLighting = new rock.game.graphics.scene.DirectionalLighting();
    directionalLighting.addLight(directionalLight);
    this.lighting = directionalLighting;
};

pong.engine.PongEngine.prototype.createCamera = function () {
    var aspectRatio = this.window.getWindowSystem().getAspectRatio();
    var camera = new rock.game.graphics.scene.Camera(this.CAMERA_POSITION, this.CAMERA_CENTER, this.CAMERA_LOOKUP,
        this.FOV, aspectRatio, this.ZNEAR, this.ZFAR);
    this.camera = camera;
};

pong.engine.PongEngine.prototype.createCourt = function () {
    var court = new pong.court.Court(this);
    this.world = court;
};

pong.engine.PongEngine.prototype.createAdapters = function () {
    this.representationAttendant.createAdapters();
};

pong.engine.PongEngine.prototype.createRepresentations = function () {
    var court = this.world;
    var representationAttendant = this.representationAttendant;

    var ball = court.getBall();
    var ballRepresentation = representationAttendant.createRepresentation(ball);
    ball.setRepresentation(ballRepresentation);

    var playerRacket = court.getPlayerRacket();
    var playerRacketRepresentation = representationAttendant.createRepresentation(playerRacket);
    playerRacket.setRepresentation(playerRacketRepresentation);

    var opponentRacket = court.getOpponentRacket();
    var opponentRacketRepresentation = representationAttendant.createRepresentation(opponentRacket);
    opponentRacket.setRepresentation(opponentRacketRepresentation);

    var leftWall = court.getLeftWall();
    var leftWallRepresentation = representationAttendant.createRepresentation(leftWall);
    leftWall.setRepresentation(leftWallRepresentation);

    var rightWall = court.getRightWall();
    var rightWallRepresentation = representationAttendant.createRepresentation(rightWall);
    rightWall.setRepresentation(rightWallRepresentation);
};

pong.engine.PongEngine.prototype.initGame = function () {
    // Set all game objects initial values
    this.world.prepareGame();
    this.updateScore();
    this.pongState.setResult(rock.game.engine.GameState.IS_RUNNING);
};

pong.engine.PongEngine.prototype.runLogic = function () {
    var pongState = this.pongState;
    pongState.clearEvents();
    var court = this.world;
    court.runLogic(pongState);
    this.processEvents();
    return pongState;
};

pong.engine.PongEngine.prototype.processEvents = function () {
    var pongState = this.pongState;
    var events = pongState.getEvents();
    var i, event, repository, bounceBallAudio, goalAudio, length = events.getLength();
    for (i = 0; i < length; i++) {
        event = events.getValue(i);
        if (event === pong.engine.PongState.BALL_BOUND_EVENT) {
            repository = this.window.getApplication().getRepository();
            bounceBallAudio = repository.getAudio(pong.constants.RES_ID_AUDIO_BOUNCE_BALL);
            bounceBallAudio.play()
        } else if (event === pong.engine.PongState.GOAL_EVENT) {
            this.updateScore();
            repository = this.window.getApplication().getRepository();
            goalAudio = repository.getAudio(pong.constants.RES_ID_AUDIO_GOAL);
            goalAudio.play();
        } else if (event === pong.engine.PongState.PLAYER_WINS_EVENT) {
            pongState.setResult(rock.game.engine.GameState.FINISH_GAME);
            pongState.setWinner(true);
        } else if (event === pong.engine.PongState.PLAYER_LOST_EVENT) {
            pongState.setResult(rock.game.engine.GameState.FINISH_GAME);
            pongState.setWinner(false);
        }
    }
};

pong.engine.PongEngine.prototype.onKeyDown = function (event) {
    var keyCode = event.getKey();
    this.updateMovementOnKeyEvent(keyCode, true);
};

pong.engine.PongEngine.prototype.onKeyUp = function (event) {
    var keyCode = event.getKey();
    this.updateMovementOnKeyEvent(keyCode, false);
};

pong.engine.PongEngine.prototype.updateMovementOnKeyEvent = function (keyCode, isMoving) {
    var court = this.world;

    if (keyCode == 65 || keyCode == 37) {
        // left
        court.setIsMovingPlayerRacketLeft(isMoving);
    } else if (keyCode == 68 || keyCode == 39) {
        // right
        court.setIsMovingPlayerRacketRight(isMoving);
    }
};

pong.engine.PongEngine.prototype.updateScore = function () {
    var court = this.world;
    var playerAnnotation = court.getPlayerAnnotation();
    var opponentAnnotation = court.getOpponentAnnotation();
    this.window.updateScore(playerAnnotation, opponentAnnotation);
};

pong.engine.PongEngine.prototype.onWindowActivate = function (event) {
    this.initGame();
    this.window.start();
};

pong.engine.PongEngine.prototype.onWindowDeactivate = function (event) {
    this.window.stop();
};


text:
<Record>
<Term>Vitiligo</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Hypopigmentation</ParentTerm>
<ParentTerm>Dermatitis</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Disorder by Site/Skin Disorder/Non-Neoplastic Skin Disorder/Dermatosis/Dermatitis/Vitiligo</ClassificationPath>
<ClassificationPath>Skin and Connective Tissue Diseases/Skin Diseases/Pigmentation Disorders/Hypopigmentation/Vitiligo</ClassificationPath>
<BroaderTerm>Skin Diseases</BroaderTerm>
<BroaderTerm>Disorder by Site</BroaderTerm>
<BroaderTerm>Hypopigmentation</BroaderTerm>
<BroaderTerm>Non-Neoplastic Skin Disorder</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Dermatosis</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Vitiligo</BroaderTerm>
<BroaderTerm>Pigmentation Disorders</BroaderTerm>
<BroaderTerm>Skin and Connective Tissue Diseases</BroaderTerm>
<BroaderTerm>Dermatitis</BroaderTerm>
<BroaderTerm>Skin Disorder</BroaderTerm>
<Synonym>Vitiligo</Synonym>
<Description>A disorder consisting of areas of macular depigmentation, commonly on extensor aspects of extremities, on the face or neck, and in skin folds. Age of onset is often in young adulthood and the condition tends to progress gradually with lesions enlarging and extending until a quiescent state is reached.</Description>
<Source>NCI Thesaurus</Source>
<Source>MeSH</Source>
</Record>


text:
from sys import maxsize

class Contact:

    def __init__(self, firstname= None, middlename= None, lastname= None, nickname= None, title= None, company= None,
                 address= None, homephone= None, mobilephone= None, workphone= None, fax= None, email1= None, email2= None,
                 address2= None, secondaryphone= None, id= None, all_phones_from_home_page= None, all_emails_from_home_page=None):
        self.firstname = firstname
        self.middlename = middlename
        self.lastname = lastname
        self.nickname = nickname
        self.title = title
        self.company = company
        self.address = address
        self.homephone = homephone
        self.mobilephone = mobilephone
        self.workphone = workphone
        self.fax = fax
        self.email1 = email1
        self.email2 = email2
        self.address2 = address2
        self.secondaryphone = secondaryphone
        self.id = id
        self.all_phones_from_home_page = all_phones_from_home_page
        self.all_emails_from_home_page = all_emails_from_home_page

    def __repr__(self):
        return "%s:%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s" % (self.firstname, self.lastname, self.middlename,
                                                                 self.nickname, self.title, self.company, self.address,
                                                                 self.homephone, self.mobilephone, self.workphone,
                                                                 self.fax, self.email1, self.email2, self.address2,
                                                                 self.secondaryphone)

    def __eq__(self, other):
        return self.firstname == other.firstname and self.lastname == other.lastname

    def id_or_max(self):
        if self.id:
            return int(self.id)
        else:
           return maxsize


text:
title: AutoTileGen Rearranger
slug: autotilegen-rearranger
author: kenton
published: 2014-10-06T21:37:02-07:00
tags: [Python]
meta_image: /images/autotilegen-rearranger/rearrange.png
preview_image: /images/autotilegen-rearranger/rearrange.png
summary: I somewhat recently came across AutoTileGen by Pixelatto—a tool for rapidly creating "blob pattern" tilesets from just three input images. It seems like a pretty good tool, at least for a quick rough-in of tiles. It just has one major flaw—the tilesheet that it outputs is all mangled.
section: Tools
---

I somewhat recently came across [AutoTileGen](http://autotilegen.com/) by [Pixelatto](http://pixelatto.com/)—a tool for rapidly creating ["blob pattern"](http://www.squidi.net/three/entry.php?id=166) tilesets from just three input images. It seems like a pretty good tool, at least for a quick rough-in of tiles. It just has one major flaw—the tilesheet that it outputs is all mangled:

How am I supposed to use this?

So I created a simple tool in Python to covert the above output in something a little more friendly:

Much better!

You can get it (and the source) on [GitHub](https://github.com/hamaluik/AutoTileGenRearranger).


text:
<?php namespace App\Gateways;

use App\Models\{{ modelUpper }};
use Illuminate\Contracts\Validation\Factory;

class Db{{ modelUpper }}Gateway
{
    {% if position %}
    use ActsAsList;
    {% endif %}

    /**
     * The Eloquent {{ modelVar }}.
     *
     * @var \App\Models\{{ modelUpper }}
     */
    protected ${{ modelVar }};

    /**
     * Constructor.
     *
     * @param \App\Models\{{ modelUpper }}|string ${{ modelVar }}
     */
    public function __construct({{ modelUpper }} ${{ modelVar }})
    {
        $this->{{ modelVar }} = ${{ modelVar }};
    }

    public function newInstance($attributes = [])
    {
        return $this->{{ modelVar }}->newInstance($attributes);
    }

    public function all()
    {
        return $this
            ->{{ modelVar }}
            ->newQuery()
            {% if position %}->orderBy('position', 'asc'){% endif %}

            ->get();
    }

    public function find($id)
    {
        return $this
            ->{{ modelVar }}
            ->where('id', (int)$id)
            ->first();
    }

    public function create(array $data)
    {
        with($client = $this->{{ modelVar }})->fill($data)->save();

        return $client;
    }

    public function update($id, array $data)
    {
        $client = $this->find($id);

        $client->fill($data)->save();

        return $client;
    }

    public function delete($id)
    {
        if ($client = $this->find($id)) {
            $client->delete();

            return true;
        }

        return false;
    }
}


text:
module Azure::IotHub::Mgmt::V2018_04_01
  module Models
    #
    # The operations monitoring properties for the IoT hub. The possible keys
    # to the dictionary are Connections, DeviceTelemetry, C2DCommands,
    # DeviceIdentityOperations, FileUploadOperations, Routes,
    # D2CTwinOperations, C2DTwinOperations, TwinQueries, JobsOperations,
    # DirectMethods.
    #
    class OperationsMonitoringProperties

      include MsRestAzure

      # @return [Hash{String => OperationMonitoringLevel}]
      attr_accessor :events

      #
      # Mapper for OperationsMonitoringProperties class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'OperationsMonitoringProperties',
          type: {
            name: 'Composite',
            class_name: 'OperationsMonitoringProperties',
            model_properties: {
              events: {
                client_side_validation: true,
                required: false,
                serialized_name: 'events',
                type: {
                  name: 'Dictionary',
                  value: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'OperationMonitoringLevelElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package io.github.winsontse.hearteyes.page.moment.module;

import dagger.Module;
import dagger.Provides;
import io.github.winsontse.hearteyes.page.moment.contract.MomentEditContract;
import io.github.winsontse.hearteyes.util.scope.FragmentScope;

@Module
public class MomentEditModule {
    private MomentEditContract.View view;

    public MomentEditModule(MomentEditContract.View view) {
        this.view = view;
    }

    @FragmentScope
    @Provides
    MomentEditContract.View provideMomentEditView() {
        return view;
    }
}


text:
var webPage = require('webpage');
var page = webPage.create();

//var url = 'http://www.tuhaokuai.com/image';
var file = '/Users/yeshaoting/Pictures/27fa013ec0accbe03581a82a296f6e8e.jpg';

var url = 'http://www.gaitubao.com/';
//var file = '/Users/yeshaoting/Pictures/6035219325378201.jpeg';

var count = 5;

page.open(url, function(status) {
	console.log('Status: ' + status);
	if (status == 'success') {
		upload();
	}

    console.log("end");
});

var interval;

function upload() {
	console.log("upload image: " + file);
	//page.uploadFile('div.uploadCtl input[type=file]', file);
    //$('#fileupload').attr('multiple', 'multiple');
	page.uploadFile('#fileupload', file);

    interval = window.setInterval(take_png, 500);
}

function take_png() {
   count--;
   if (count >= 0) {
        console.log(count + ". take png~");
        page.render('screenshots/screen' + count + '.png');
   } else {
       console.log("exit~")
       phantom.exit()
   }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
using Xunit;

namespace Microsoft.Azure.WebJobs.Logging.FunctionalTests
{
    // Helper for unit testing safe creating tables.
    // This works through various retry and error scenarios.
    public class SafeCreateTests
    {
        static StorageException Error(HttpStatusCode code)
        {
            return new StorageException(
                new RequestResult
                {
                    HttpStatusCode = (int)code
                },
                string.Empty,
                new Exception());
        }

        // Create Normally
        [Fact]
        public async Task CreateNormal()
        {
            var func = MockCloudTable.GetSafeCreateMethod();

            var table = new MockCloudTable();
            table.Func = new Action[]
            {
                () => { } // Nop, success
            };

            await func(table);
        }

        // Have conflict, retry
        [Fact]
        public async Task CreateWithConflict()
        {
            var func = MockCloudTable.GetSafeCreateMethod();
            {
                var table = new MockCloudTable();
                table.Func = new Action[]
                {
                    () => { throw Error(HttpStatusCode.Conflict); },
                    () => { },  // success
                };

                await func(table);
            }
        }

        // Fail with non 409 error from storage
        [Fact]
        public async Task FailWithStorageError()
        {
            var func = MockCloudTable.GetSafeCreateMethod();

            var exception = Error(HttpStatusCode.BadRequest);
            try
            {
                var table = new MockCloudTable();
                table.Func = new Action[]
                {
                       () => { throw exception; } // terminal abort
                };

                await func(table);
                Assert.True(false); // should have thrown
            }
            catch (StorageException e)
            {
                Assert.True(object.ReferenceEquals(e, exception));
            }
        }

        // Fail with an error not from storage
        [Fact]
        public async Task FailWithNonStorageError()
        {
            var func = MockCloudTable.GetSafeCreateMethod();

            // Completely different exception  Storage error

            var exception = new InvalidOperationException("other");
            try
            {
                var table = new MockCloudTable();
                table.Func = new Action[]
                {
                     () => { throw exception; } // terminal abort
                };

                await func(table);

                Assert.True(false); // should have thrown
            }
            catch (Exception e)
            {
                Assert.True(object.ReferenceEquals(e, exception));
            }
        }

        // Fail because of too many retries.
        [Fact]
        public async Task FailWithTimeout()
        {
            var func = MockCloudTable.GetSafeCreateMethod();
            try
            {
                var table = new MockCloudTable();
                table.Func = new Action[]
                {
                    () => { throw Error(HttpStatusCode.Conflict); },
                    () => { throw Error(HttpStatusCode.Conflict); },
                    () => { throw Error(HttpStatusCode.Conflict); },
                    () => { throw Error(HttpStatusCode.Conflict); },
                };

                await func(table);
                Assert.True(false); // should have thrown
            }
            catch (StorageException)
            {
                // Success
            }
        }

        // Helper for unit testing SafeCreateAsync()
        public class MockCloudTable : CloudTable
        {
            public int Counter = 0;

            public MockCloudTable() : base(new Uri("http://contoso.com"))
            {
            }

            public override Task<bool> CreateIfNotExistsAsync()
            {
                try
                {
                    this.Func[this.Counter]();
                }
                finally
                {
                    this.Counter++;
                }
                return Task.FromResult(true);
            }

            // What to do on each iteration
            public Action[] Func;

            public static Func<CloudTable, Task> GetSafeCreateMethod()
            {
                // Pass in short timeouts
                var method = typeof(LogFactory).Assembly.GetType("Microsoft.Azure.WebJobs.Logging.Utility").GetMethod("SafeCreateAsync", BindingFlags.Static | BindingFlags.NonPublic);
                Func<CloudTable, Task> func = (CloudTable t) => (Task)method.Invoke(null, new object[] { t, 1, 2 });
                return func;
            }
        }
    } // end SafeCreateTests
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/video/stitcher/v1/video_stitcher_service.proto

package com.google.cloud.video.stitcher.v1;

public interface ListCdnKeysRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.video.stitcher.v1.ListCdnKeysRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The project that contains the list of CDN keys, in the form of
   * `projects/{project_number}/locations/{location}`.
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The parent.
   */
  java.lang.String getParent();
  /**
   *
   *
   *

   * Required. The project that contains the list of CDN keys, in the form of
   * `projects/{project_number}/locations/{location}`.
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for parent.
   */
  com.google.protobuf.ByteString getParentBytes();

  /**
   *
   *
   *

   * Requested page size. Server may return fewer items than requested.
   * If unspecified, server will pick an appropriate default.
   *

   *
   * int32 page_size = 2;
   *
   * @return The pageSize.
   */
  int getPageSize();

  /**
   *
   *
   *

   * A token identifying a page of results the server should return.
   *

   *
   * string page_token = 3;
   *
   * @return The pageToken.
   */
  java.lang.String getPageToken();
  /**
   *
   *
   *

   * A token identifying a page of results the server should return.
   *

   *
   * string page_token = 3;
   *
   * @return The bytes for pageToken.
   */
  com.google.protobuf.ByteString getPageTokenBytes();

  /**
   *
   *
   *

   * Filtering results
   *

   *
   * string filter = 4;
   *
   * @return The filter.
   */
  java.lang.String getFilter();
  /**
   *
   *
   *

   * Filtering results
   *

   *
   * string filter = 4;
   *
   * @return The bytes for filter.
   */
  com.google.protobuf.ByteString getFilterBytes();

  /**
   *
   *
   *

   * Hint for how to order the results
   *

   *
   * string order_by = 5;
   *
   * @return The orderBy.
   */
  java.lang.String getOrderBy();
  /**
   *
   *
   *

   * Hint for how to order the results
   *

   *
   * string order_by = 5;
   *
   * @return The bytes for orderBy.
   */
  com.google.protobuf.ByteString getOrderByBytes();
}


text: var PullRequest = Backbone.Model.extend({});


text:
package de.rndm.todo.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import de.rndm.todo.R;
import de.rndm.todo.adapter.DashboardListAdapter;
import de.rndm.todo.custom.FadeoutAnimation;
import de.rndm.todo.model.*;
import de.rndm.todo.model.accessor.ContactsAccessorImpl;
import de.rndm.todo.model.accessor.SqliteAccessorImpl;

import java.util.ArrayList;
import java.util.Date;

public class DashboardActivity extends Activity {

    private final String logKey = "DashboardActivity";
    private final int TIME_REFRESH_RATE = 1000 * 60;
    private ArrayList<Todo> todos = new ArrayList<Todo>();
    private ListView listview;
    private DashboardListAdapter adapter;
    private SortOrder order = SortOrder.DATE;
    private ImageView newButton;
    private ProgressBar loadIndicator;
    private TextView todoCount;
    private Handler guiHandler;
    private SqliteAccessorImpl todoAccessor;
    private ContactsAccessorImpl contactAccessor;
    private Date adapterUpdated = new Date();

    private FadeoutAnimation fadeoutAnimation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_dashboard);

        guiHandler = new Handler();
        todoAccessor = new SqliteAccessorImpl(getApplicationContext());
        contactAccessor = new ContactsAccessorImpl(this.getContentResolver(), getResources().getDrawable(R.drawable.ic_contact_picture), getApplicationContext());

        adapter = new DashboardListAdapter(this, R.layout.listview_todo_item_row, todos, todoAccessor);

        listview = (ListView) findViewById(R.id.list_todos);
        listview.setDividerHeight(0);
        listview.setDrawingCacheEnabled(true);
        listview.setAlwaysDrawnWithCacheEnabled(true);
        listview.setPersistentDrawingCache(ViewGroup.PERSISTENT_SCROLLING_CACHE);

        todoCount = (TextView) findViewById(R.id.label_count_todos);
        newButton = (ImageView) findViewById(R.id.button_new);
        loadIndicator = (ProgressBar) findViewById(R.id.button_reload);
        fadeoutAnimation = new FadeoutAnimation(getApplicationContext(), R.anim.fade_out, guiHandler, loadIndicator);

        newButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                new AsyncTask<Todo, Void, Todo>() {
                    @Override
                    protected Todo doInBackground(Todo... todo) {
                        return todoAccessor.createTodo(todo[0]);
                    }

                    @Override
                    protected void onPostExecute(Todo todo) {
                        if (todo != null) {
                            Intent i = new Intent(DashboardActivity.this, DetailActivity.class);
                            todo.setActive(true);
                            i.putExtra(getString(R.string.parcel_todo), todo);
                            i.putExtra(getString(R.string.parcel_num), todos.size() - 1);
                            startActivityForResult(i, 1);

                            todos.add(todo);
                            updateTodoCount();
                            adapter.notifyDataSetChanged();
                        }
                    }
                }.execute(new Todo());
            }
        });

        listview.setAdapter(adapter);
        listview.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                checkUpdate();
                return false;
            }
        });

        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {

                Intent i = new Intent(DashboardActivity.this, DetailActivity.class);
                i.putExtra(getString(R.string.parcel_todo), todos.get(arg2));
                i.putExtra(getString(R.string.parcel_num), arg2);
                startActivityForResult(i, 1);
            }
        });

        loadAll();
    }

    protected void onStop() {
        super.onStop();
    }

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

    /*
     * update the adapter after a given time, if there is a touch event
     * useful to update the remaining time kinda responsive without using a timer
     */
    private void checkUpdate() {
        Date checkDate = new Date();
        if (checkDate.getTime() > adapterUpdated.getTime() + TIME_REFRESH_RATE) {
            sortRefresh();
            adapterUpdated = new Date();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {

                Log.i(logKey, "RESULT_OK");

                Todo receivedTodo = (Todo) data.getParcelableExtra(getString(R.string.parcel_todo));
                if (data.getBooleanExtra(getString(R.string.parcel_delete), false)) {

                    //Fall result gelöscht
                    Log.i(logKey, "parcel_delete");

                    new AsyncTask<Todo, Void, Todo>() {
                        @Override
                        protected void onPreExecute() {
                            adapter.setEnabled(false);
                            fadeoutAnimation.reset();
                            guiHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    //wenn result delete gestartet wird
                                }
                            });
                            super.onPreExecute();
                        }

                        @Override
                        protected Todo doInBackground(Todo... todo) {
                            return todoAccessor.deleteTodo(todo[0].getId()) ? todo[0] : null;
                        }

                        @Override
                        protected void onPostExecute(Todo todo) {
                            adapter.setEnabled(true);

                            fadeoutAnimation.start();

                            if (todo != null) {
                                guiHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        //wenn erfolgreich gelöscht, dann
                                    }
                                });

                                todos.remove(RememberUtils.getTodoIndexInArrayList(todo, todos));
                                updateTodoCount();
                                sortRefresh();

                            } else {
                                guiHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        //wenn fehlerhaft gelöscht, dann
                                    }
                                });
                            }
                        }
                    }.execute(receivedTodo);

                } else if (data.getBooleanExtra(getString(R.string.parcel_update), false)) {

                    //Fall result updated
                    Log.i(logKey, "parcel_update");

                    new AsyncTask<Todo, Void, Todo>() {
                        @Override
                        protected void onPreExecute() {
                            adapter.setEnabled(false);
                            fadeoutAnimation.reset();
                            guiHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    //wenn result update gestartet wird
                                }
                            });
                            super.onPreExecute();
                        }

                        @Override
                        protected Todo doInBackground(Todo... todo) {
                            return todoAccessor.updateTodo(todo[0]);
                        }

                        @Override
                        protected void onPostExecute(Todo todo) {
                            adapter.setEnabled(true);
                            fadeoutAnimation.start();

                            if (todo != null) {
                                guiHandler.post(new Runnable() {  // Handler benutzen, der mitк UI-Thread verbunden ist
                                    @Override
                                    public void run() {
                                        //wenn result update erfolgreich beendet wird
                                    }
                                });
                                todos.set(RememberUtils.getTodoIndexInArrayList(todo, todos), todo);
                                sortRefresh();
                            } else {
                                guiHandler.post(new Runnable() {  // Handler benutzen, der mitк UI-Thread verbunden ist
                                    @Override
                                    public void run() {
                                        //wenn result update fehlerhaft beendet wird
                                    }
                                });
                            }
                        }
                    }.execute(receivedTodo);
                }
            }
        }

        if (resultCode == RESULT_CANCELED) {
            Log.i(logKey, "RESULT_CANCELED");
        }
    }

    private void sortRefresh() {
        todos = RememberUtils.sortListByOrder(todos, order);
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_list_reload:
                todos.clear();
                adapter.setEnabled(true);
                loadAll();
                break;
            case R.id.menu_sort_date_importance:
                order = SortOrder.DATE;
                todos = RememberUtils.sortListByOrder(todos, order);
                break;
            case R.id.menu_sort_importance_date:
                order = SortOrder.SPECIAL;
                todos = RememberUtils.sortListByOrder(todos, order);
                break;
            case R.id.menu_sort_kreutel_dw:
                order = SortOrder.KREUTELDW;
                todos = RememberUtils.sortListByOrder(todos, order);
                break;
            case R.id.menu_sort_kreutel_wd:
                order = SortOrder.KREUTELWD;
                todos = RememberUtils.sortListByOrder(todos, order);
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        adapter.notifyDataSetChanged();
        return true;
    }

    private void updateTodoCount() {
        todoCount.setText(todos.size() + " " + getApplicationContext().getString(R.string.label_todos));
    }

    private void loadAll() {
        new AsyncTask<Void, Void, ArrayList<Todo>>() {
            @Override
            protected void onPreExecute() {
                adapter.setEnabled(false);

                //wenn loadAll gestarted wird
                fadeoutAnimation.reset();

                super.onPreExecute();
            }

            @Override
            protected ArrayList<Todo> doInBackground(Void... params) {
                ArrayList<Todo> todos = todoAccessor.readAllTodos();

                for (Todo t : todos) {
                    ArrayList<Contact> contacts = contactAccessor.readAllContactsFromLookupList(t.getContactIds());
                    t.setContacts(contacts);
                }
                return todos;
            }

            @Override
            protected void onPostExecute(ArrayList<Todo> result) {

                adapter.setEnabled(true);

                fadeoutAnimation.start();

                todos.addAll(result);
                updateTodoCount();
                sortRefresh();

            }

        }.execute();
    }
}


text:
this is local config for phonegap stuff to be eventually moved to
config.xml ...we think. feedback to @davejohnson/@brianleroux
appreciated here!


text:
class Question < ActiveRecord::Base
	# This is Sinatra! Remember to create a migration!
	belongs_to :user

	self.per_page = 10
end


text:
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::verifying_client::state_store::{StateStore, WriteThroughCache};
use diem_crypto::hash::{CryptoHasher, HashValue};
use diem_types::{
    transaction::Version,
    trusted_state::{TrustedState, TrustedStateHasher},
};
use std::{
    cmp::max_by_key,
    fs::{self, File},
    io::{self, Read, Seek, SeekFrom, Write},
    path::Path,
    sync::{Arc, Mutex},
};

/// A `StateStore` that stores `TrustedState`s in files inside a given directory
/// on the local filesystem.
///
/// After initialization, the given directory will contain two files
/// `/<dir>/trusted_state.0` and `/<dir>/trusted_state.1`.
///
/// Note: we assumes that calls to `fsync` after every a write will make the
/// store durable, though this is not actually true for all file systems or storage
/// devices. Unfortunately, the it's also the best we can do at this layer.
///
/// Note: we don't (yet) use FS advisory locks, so this store will fail in fun
/// and exciting ways if multiple processes try to use the same directory.
#[derive(Debug, Clone)]
pub struct FileStateStore(Arc<WriteThroughCache<ACIDStateFiles>>);

/// A pair of files that can durably store [`TrustedState`]s.
///
/// The main idea here is that the highest version state file is durable and not
/// being written to at all times. It only supports either one writer or one
/// reader at a time.
///
/// When a writer wants to store a new state, it gets an exclusive lock and writes
/// to the on-disk state file with the lower version (if the new state is actually newer).
/// That way, if the machine crashes or restarts during a store, we'll only corrupt
/// the older state file and the newer state file will remain untouched.
#[derive(Debug)]
struct ACIDStateFiles(Mutex<[StateFile; 2]>);

/// Metadata for an on-disk [`TrustedState`] file.
#[derive(Debug)]
struct StateFile {
    /// The version of the on-disk trusted state, or `None` if the on-disk state
    /// has not been written yet.
    version: Option<Version>,
    /// The opened file handle for the on-disk trusted state.
    file: File,
}

////////////////////
// FileStateStore //
////////////////////

impl FileStateStore {
    pub fn new(dir: &Path) -> io::Result<Self> {
        let store = ACIDStateFiles::new(dir)?;
        let store_cache = WriteThroughCache::new(store)?;
        Ok(Self(Arc::new(store_cache)))
    }
}

impl StateStore for FileStateStore {
    type Error = io::Error;

    fn latest_state(&self) -> io::Result<Option<TrustedState>> {
        self.0.latest_state()
    }
    fn latest_state_version(&self) -> io::Result<Option<u64>> {
        self.0.latest_state_version()
    }
    fn store(&self, new_state: &TrustedState) -> io::Result<()> {
        self.0.store(new_state)
    }
}

////////////////////
// ACIDStateFiles //
////////////////////

impl ACIDStateFiles {
    fn new(dir: &Path) -> io::Result<Self> {
        let state_file0 = StateFile::open(&dir.join("trusted_state.0"))?;
        let state_file1 = StateFile::open(&dir.join("trusted_state.1"))?;
        let state_files = [state_file0, state_file1];

        // make sure any newly created files are synced
        fsync_dir(dir)?;

        Ok(Self(Mutex::new(state_files)))
    }
}

impl StateStore for ACIDStateFiles {
    type Error = io::Error;

    fn latest_state(&self) -> io::Result<Option<TrustedState>> {
        let mut state_files = self.0.lock().unwrap();

        let state0 = state_files[0].read()?;
        let state1 = state_files[1].read()?;
        Ok(max_by_key(state0, state1, |opt| {
            opt.as_ref().map(|s| s.version())
        }))
    }

    fn store(&self, new_state: &TrustedState) -> io::Result<()> {
        let mut state_files = self.0.lock().unwrap();

        let newest_version = state_files
            .iter_mut()
            .max_by_key(|f| f.version)
            .unwrap()
            .version;
        let oldest_state_file = state_files.iter_mut().min_by_key(|f| f.version).unwrap();

        // the new state is actually newer; write it to the oldest state file.
        if Some(new_state.version()) > newest_version {
            oldest_state_file.write(new_state)?;
        }

        Ok(())
    }
}

///////////////
// StateFile //
///////////////

// A dumb format for dumping a TrustedState to a File.
//
// serialized format: <bcs-serialized state blob> || <sha3-checksum(bcs-serialized state blob)>
//
// basic requirements:
// 1. fs writes are unreliable and not atomic:
//    ==> we validate the serialized bytes are uncorrupted with a sha3 checksum.
// 2. upgrade format:
//    ==> add a new TrustedState enum variant to modify.

fn decode_and_validate_checksum(mut buf: Vec<u8>) -> io::Result<(Vec<u8>, HashValue)> {
    let offset = buf
        .len()
        .checked_sub(HashValue::LENGTH)
        .ok_or_else(|| invalid_data("state file: empty or too small"))?;
    let file_hash = HashValue::from_slice(&buf[offset..]).expect("cannot fail");

    buf.truncate(offset);
    let computed_hash = TrustedStateHasher::hash_all(&buf);

    if file_hash != computed_hash {
        Err(invalid_data(format!(
            "state file: corrupt: file checksum ({:x}) != computed checksum ({:x})",
            file_hash, computed_hash
        )))
    } else {
        Ok((buf, file_hash))
    }
}

fn decode_state(buf: Vec<u8>) -> io::Result<TrustedState> {
    let (buf, _) = decode_and_validate_checksum(buf)?;
    let state = bcs::from_bytes(&buf).map_err(invalid_data)?;
    Ok(state)
}

fn encode_state(state: &TrustedState) -> io::Result<Vec<u8>> {
    let mut buf = bcs::to_bytes(state).map_err(invalid_input)?;
    let hash = TrustedStateHasher::hash_all(&buf);
    buf.extend_from_slice(hash.as_ref());
    Ok(buf)
}

fn read_file(file: &mut File) -> io::Result<Vec<u8>> {
    let mut buf = Vec::new();
    file.seek(SeekFrom::Start(0))?;
    file.read_to_end(&mut buf)?;
    Ok(buf)
}

// Note: this method can take anywhere from 20ms to 50ms...
fn write_file(file: &mut File, buf: &[u8]) -> io::Result<()> {
    file.seek(SeekFrom::Start(0))?;
    file.write_all(buf)?;
    file.set_len(buf.len() as u64)?;
    // call fsync here to flush kernel cache to disk. this way we can (more) safely
    // assume that the write is actually durable once the write completes and clients
    // can't observe non-durable state.
    file.sync_all()?;
    Ok(())
}

impl StateFile {
    fn open(path: &Path) -> io::Result<Self> {
        let file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .open(path)?;
        Ok(Self::new(file))
    }

    fn new(file: File) -> Self {
        Self {
            version: None,
            file,
        }
    }

    // only returns an error on io::Error, otherwise assumes the file is just corrupt.
    fn read(&mut self) -> io::Result<Option<TrustedState>> {
        let buf = read_file(&mut self.file)?;
        let maybe_state = decode_state(buf)
            .map_err(|_err| () /* TODO: how to log in client sdk? */)
            .ok();
        self.version = maybe_state.as_ref().map(|s| s.version());
        Ok(maybe_state)
    }

    fn write(&mut self, new_state: &TrustedState) -> io::Result<()> {
        let buf = encode_state(new_state)?;
        write_file(&mut self.file, &buf)?;
        self.version = Some(new_state.version());
        Ok(())
    }
}

///////////
// Utils //
///////////

type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;

fn invalid_input(err: impl Into<BoxError>) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, err)
}

fn invalid_data(err: impl Into<BoxError>) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, err)
}

/// fsync a directory. In certain file systems, this is required to persistently create a file.
// Note: shamelessly copied from tantivy-search:
// https://github.com/tantivy-search/tantivy/blob/b8a10c84067fa1e7841a0e6c962b023ed806d307/src/directory/mmap_directory.rs#L225
fn fsync_dir<P: AsRef<Path>>(dir: P) -> io::Result<()> {
    let mut open_opts = fs::OpenOptions::new();

    // Linux needs read to be set, otherwise returns EINVAL
    // write must not be set, or it fails with EISDIR
    open_opts.read(true);

    // On Windows, opening a directory requires FILE_FLAG_BACKUP_SEMANTICS
    // and calling sync_all() only works if write access is requested.
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;
        use winapi::winbase;

        open_opts
            .write(true)
            .custom_flags(winbase::FILE_FLAG_BACKUP_SEMANTICS);
    }

    let fd = open_opts.open(dir)?;
    fd.sync_all()?;
    Ok(())
}

///////////
// Tests //
///////////

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::{collection::vec, prelude::*, sample::Index};
    use tempfile::{tempdir, tempfile};

    fn max_state(idx: usize, states: &[TrustedState]) -> &TrustedState {
        states[..=idx].iter().max_by_key(|s| s.version()).unwrap()
    }

    // simulate a crash during write by truncating the file
    fn corrupt_file(corrupt_idx: &Index, file: &mut File) {
        let len = file.metadata().unwrap().len();
        if len > 0 {
            // note: Index::index(N) returns x in [0, N)
            let new_len = corrupt_idx.index(len as usize);
            file.set_len(new_len as u64).unwrap();
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn state_file_read_corrupt(
            state in any::<TrustedState>(),
            corrupt_idx in any::<Index>(),
        ) {
            let file = tempfile().unwrap();
            let mut state_file = StateFile::new(file);

            // write a state
            state_file.write(&state).unwrap();
            assert_eq!(state_file.version, Some(state.version()));

            // read that state back
            let maybe_state = state_file.read().unwrap();
            assert_eq!(maybe_state, Some(state));

            // simulate a crash during write by truncating the file
            corrupt_file(&corrupt_idx, &mut state_file.file);

            // read should return None b/c file is corrupt.
            let maybe_state = state_file.read().unwrap();
            assert_eq!(maybe_state, None);
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(25))]

        #[test]
        fn file_state_store(
            states in vec(any::<TrustedState>(), 1..10),
            corrupt_idx in any::<Index>(),
        ) {
            let dir = tempdir().unwrap();
            let state_store = FileStateStore::new(dir.path()).unwrap();
            assert_eq!(None, state_store.latest_state().unwrap());

            // store some states (without any particular order)
            for (idx, state) in states.iter().enumerate() {
                state_store.store(state).unwrap();

                // latest_state should be monotonically increasing by version
                let store_max = state_store.latest_state().unwrap().unwrap();
                let expected_max = max_state(idx, &states);
                assert_eq!(expected_max, &store_max);
            }

            // final highest state
            let store_max1 = state_store.latest_state().unwrap().unwrap();
            drop(state_store);

            // restarting should recover the same final state
            let state_store = FileStateStore::new(dir.path()).unwrap();
            let store_max2 = state_store.latest_state().unwrap().unwrap();
            assert_eq!(store_max1, store_max2);

            // "corrupt" the older state file (if it exists) to simulate crashing
            // while writing
            {
                let mut state_files = state_store.0.as_inner().0.lock().unwrap();
                if let Some(oldest_state_file) = state_files.iter_mut().min_by_key(|f| f.version).as_mut() {
                    corrupt_file(&corrupt_idx, &mut oldest_state_file.file);
                }
            }
            drop(state_store);

            // restarting after partial write should still recover state
            let state_store = FileStateStore::new(dir.path()).unwrap();
            let store_max3 = state_store.latest_state().unwrap().unwrap();
            assert_eq!(store_max1, store_max3);
        }
    }
}


text:
#include <Python.h>
#include <stdlib.h>
#include "pyconcrete.h"

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >=7
    #define MAGIC_OFFSET 16
#elif PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >=3
    #define MAGIC_OFFSET 12
#else
    #define MAGIC_OFFSET 8
#endif

void execPycContent(PyObject* pyc_content);
void runFile(const char* filepath);

int main(int argc, char *argv[])
{
#if PY_MAJOR_VERSION >= 3
    int i, len;
    wchar_t** argv_ex = NULL;
    argv_ex = (wchar_t**) malloc(sizeof(wchar_t*) * argc);
    for(i=0 ; i<argc ; ++i)
    {
        len = mbstowcs(NULL, argv[i], 0);
        argv_ex[i] = (wchar_t*) malloc(sizeof(wchar_t) * (len+1));
        mbstowcs(argv_ex[i], argv[i], len);
        argv_ex[i][len] = 0;
    }
#else
    char** argv_ex = argv;
#endif

    Py_SetProgramName(argv_ex[0]);  /* optional but recommended */
    Py_Initialize();
    PyGILState_Ensure();

    if(argc >= 2)
    {
        if(argc == 2 && (strncmp(argv[1], "-v", 3)==0 || strncmp(argv[1], "--version", 10)==0))
        {
            printf("pyconcrete %s [Python %s]\n", TOSTRING(PYCONCRETE_VERSION), TOSTRING(PY_VERSION));  // defined in setup.py
        }
        else
        {
            PySys_SetArgv(argc-1, argv_ex+1);
            runFile(argv[1]);
        }
    }

    PyGILState_Ensure();

    if (PyErr_Occurred()) {
        PyErr_Print();
    }

    // reference mod_wsgi & uwsgi finalize steps
    // https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/src/server/wsgi_interp.c
    // https://github.com/unbit/uwsgi/blob/master/plugins/python/python_plugin.c
    PyObject *module = PyImport_ImportModule("atexit");
    Py_XDECREF(module);

    if (!PyImport_AddModule("dummy_threading")) {
        PyErr_Clear();
    }

    Py_Finalize();

#if PY_MAJOR_VERSION >= 3
    for(i=0 ; i<argc ; ++i)
    {
        free(argv_ex[i]);
    }
    free(argv_ex);
#endif
    return 0;
}

void execPycContent(PyObject* pyc_content)
{
    PyObject* py_marshal = NULL;
    PyObject* py_marshal_loads = NULL;
    PyObject* pyc_content_wo_magic = NULL;
    PyObject* py_code = NULL;
    PyObject* global = PyDict_New();
    Py_ssize_t content_size = 0;
    char* content = NULL;
#if PY_MAJOR_VERSION >= 3
    PyObject* main_name = PyUnicode_FromString("__main__");
#else
    PyObject* main_name = PyBytes_FromString("__main__");
#endif

    // load compiled source from .pyc content
    py_marshal = PyImport_ImportModule("marshal");
    py_marshal_loads = PyObject_GetAttrString(py_marshal, "loads");

    content = PyBytes_AS_STRING(pyc_content);
    content_size = PyBytes_Size(pyc_content);

    pyc_content_wo_magic = PyBytes_FromStringAndSize(content+MAGIC_OFFSET, content_size-MAGIC_OFFSET);
    py_code = PyObject_CallFunctionObjArgs(py_marshal_loads, pyc_content_wo_magic, NULL);
    if(py_code == NULL && PyErr_Occurred() != NULL)
    {
        PyErr_Print();
        goto ERROR;
    }

    // setup global and exec loaded py_code
    PyDict_SetItemString(global, "__name__", main_name);
    PyDict_SetItemString(global, "__builtins__", PyEval_GetBuiltins());
    PyEval_EvalCode(py_code, global, global);

ERROR:
    Py_XDECREF(py_code);
    Py_XDECREF(global);
    Py_XDECREF(pyc_content_wo_magic);
    Py_XDECREF(py_marshal_loads);
    Py_XDECREF(py_marshal);
}

void runFile(const char* filepath)
{
    FILE* src = NULL;
    char* content = NULL;
    size_t s, size;
    PyObject* py_content = NULL;
    PyObject* py_plaint_content = NULL;
    PyObject* py_args = NULL;

    src = fopen(filepath, "rb");
    if(src == NULL)
    {
        return;
    }

    // read & parse file
    {
        fseek(src, 0, SEEK_END);
        size = ftell(src);

        fseek(src, 0, SEEK_SET);
        content = malloc(size * sizeof(char));
        s = fread(content, 1, size, src);
        if(s != size)
        {
            return;
        }
        py_content = PyBytes_FromStringAndSize(content, size);
        py_args = PyTuple_New(1);
        PyTuple_SetItem(py_args, 0, py_content);
        py_plaint_content = fnDecryptBuffer(NULL, py_args);

        Py_DECREF(py_args);
        free(content);
    }
    fclose(src);

    execPycContent(py_plaint_content);

    Py_DECREF(py_plaint_content);
}


text:
/*
	HUMANIZED MESSAGES 1.0
	idea - http://www.humanized.com/weblog/2006/09/11/monolog_boxes_and_transparent_messages
	home - http://humanmsg.googlecode.com
*/

var humanMsg = {
    shouldShow: true,

	setup: function(appendTo, logName, msgOpacity) {

        if (humanMsg.hasSetup) {
            return;
        }

        humanMsg.hasSetup = true;
        humanMsg.msgID = 'humanMsg';
		humanMsg.logID = 'humanMsgLog';

		// appendTo is the element the msg is appended to
        appendTo = 'body';

		// The text on the Log tab
		if (logName == undefined) {
			if (humanMsg.logTitle == undefined) {
				logName = 'Message Log';
			} else {
				logName = humanMsg.logTitle;
			}
		}

        // Opacity of the message
		humanMsg.msgOpacity = 0.8;

		if (msgOpacity != undefined)
			humanMsg.msgOpacity = parseFloat(msgOpacity);

		// Inject the message structure
		jQuery(appendTo).prepend('

');
		jQuery('#mainFooter').prepend('

'+logName+'x

');

        humanMsg.logTop = jQuery('#'+humanMsg.logID).css("top");

        jQuery('#humanMsgClose').click(
            function() {
                jQuery('#'+humanMsg.logID+' p').addClass('minimized');
                jQuery('#humanMsgClose').hide();
                return false;
        });

		jQuery('#'+humanMsg.logID+' p').click(
            function() {
                humanMsg.activateLog();

                if (jQuery('#'+humanMsg.logID+' p').hasClass('minimized')) {
                    jQuery('#humanMsgClose').show();
                    jQuery('#'+humanMsg.logID+' p').removeClass('minimized');
                    return;
                }

                if (jQuery(this).siblings('ul').css('display') != 'none') {
                    jQuery('#'+humanMsg.logID).css("top", humanMsg.logTop);
					jQuery(this).siblings('ul').hide();
                    jQuery('#humanMsgClose').show();
                    jQuery('#' + humanMsg.logID).animate({
                        'top': '-' + humanMsg.logTop + 'px'
                    }, 300);
				} else {
                    humanMsg.setLogHeight();
                    jQuery(this).siblings('ul').show();
                    jQuery('#humanMsgClose').hide();
                    jQuery('#' + humanMsg.logID).animate({
                        'top': '-' + (78 + jQuery('#' + humanMsg.logID + ' > ul').height()) + 'px'
                    }, 300);
				}
			}
		)
	},

	setLogTitle: function(/*string*/ title) {
		 humanMsg.logTitle = title;
		 jQuery("#" + humanMsg.logID + " > p").text(title);
	},

	displayMsg: function(msg, /*boolean*/doLog) {
        if (!humanMsg.shouldShow) {
            return;
        }

		if (msg == '')
			return;

        humanMsg.setup();

        humanMsg.activateLog();

        clearTimeout(humanMsg.t2);

		/*
		 * IE doesn't really support CSS fixed position so we need to set the position manually
		 */
		jQuery('#' + humanMsg.msgID).css('top', (jQuery(window).scrollTop() + 75) + 'px');

		// Inject message
		jQuery('#'+humanMsg.msgID+' p').html(msg)

		// Show message
		jQuery('#'+humanMsg.msgID+'').show().animate({ opacity: humanMsg.msgOpacity}, 200, function() {
			if (doLog) {
				humanMsg.log(msg);
			}

		});

        /*
         * If we are starting a new message and have an existing
         * message then we want to restart the timers so the
         * existing message doesn't get hidden very fast.
         */
        if (humanMsg.t1) {
            clearTimeout(humanMsg.t1);
        }

        if (humanMsg.t2) {
            clearTimeout(humanMsg.t2);
        }

		// Watch for mouse & keyboard in .5s
		humanMsg.t1 = setTimeout(function() {humanMsg.bindEvents();}, 3000);
		// Remove message after 5s
		humanMsg.t2 = setTimeout(function() {humanMsg.removeMsg();}, 5000);
	},

	log: function(msg) {
         humanMsg.setup();
		 jQuery('#'+humanMsg.logID)
			.show().children('ul').prepend('
'+msg+'
')	// Prepend message to log
			.children('li:first').slideDown(200)				// Slide it down

		 if (jQuery('#'+humanMsg.logID+' ul').css('display') == 'none') {
			 jQuery('#'+humanMsg.logID+' p').animate({ bottom: 40 }, 200, 'linear', function() {
				jQuery(this).animate({ bottom: 0 }, 300, 'swing', function() { jQuery(this).css({ bottom: 0 }) })
			})
		 } else {
			 humanMsg.setLogHeight();
		 }

         jQuery('#humanMsgClose').show();
         jQuery('#'+humanMsg.logID+' p').removeClass('minimized');
	},

    activateLog: function() {
         jQuery('#'+humanMsg.logID+' p').removeClass("faded");

         clearTimeout(humanMsg.t3);

         //fadeout the error log after 15s
         humanMsg.t3 = setTimeout(humanMsg.fadeLog, 15000)
    },

	setLogHeight: function() {
         /*
		  * When items are added to the log we want to adjust the top of the log (where
		  * the pull tab goes) and the height of the log list dynamically so the log is
		  * always a reasonable size.
		  */
         if (navigator.appName === "Microsoft Internet Explorer") {
             /*
              * IE just calculates the size of these list items differently thn every
              * other browser.  There isn't a good cross-browser way to set the height,
              * so we tweak it for IE.
              */
             var height = Math.min(jQuery('#'+humanMsg.logID + ' ul').children('li').length * 48, 112);
             jQuery('#'+humanMsg.logID + ' ul').css("height", (height + 10) + "px");

             jQuery('#'+humanMsg.logID).css("top", "-" + ((height) + 56 + humanMsg.logTop) + "px");
         } else {
             var height = Math.min(jQuery('#'+humanMsg.logID + ' ul').children('li').length * 14, 56);
             jQuery('#'+humanMsg.logID + ' ul').css("height", (height + 10) + "px");
             jQuery('#'+humanMsg.logID).css("top", "-" + ((height) + 112 + humanMsg.logTop) + "px");
         }

	},

	bindEvents: function() {
	// Remove message if mouse is moved or key is pressed
		jQuery(window)
			.mousemove(humanMsg.removeMsg)
			.click(humanMsg.removeMsg)
			.keypress(humanMsg.removeMsg)
	},

	removeMsg: function() {
         // Unbind mouse & keyboard
		jQuery(window)
			.unbind('mousemove', humanMsg.removeMsg)
			.unbind('click', humanMsg.removeMsg)
			.unbind('keypress', humanMsg.removeMsg)

        jQuery('#'+humanMsg.msgID).fadeOut();
	},

    fadeLog: function() {
         if(jQuery('#'+humanMsg.logID+' ul').css('display') === "none") {
             jQuery('#'+humanMsg.logID+' p').addClass("faded");
         }
    }
};


text:
// server.js

require('coffee-script/register');

// Absolute imports.
// See https://gist.github.com/branneman/8048520#6-the-hack
process.env.NODE_PATH = '.';
require('module').Module._initPaths();

var nconf = require('./config/nconf')

// Nodetime stats
if (process.env.NODETIME_ACCOUNT_KEY) {
	require('nodetime').profile({
		accountKey: process.env.NODETIME_ACCOUNT_KEY,
		appName: 'QI LABS', // optional
	});
}

///////////////////////////////////////////////////////////////////////////////

// Utils
var _
, 	path 	= require('path')
, 	_ 		= require('lodash')

if (nconf.get('env') === 'production') {
	require('newrelic');
}

// Logging.
// Create before app is used as arg to modules.
var logger = require('./core/bunyan')();
logger.level(process.env.BUNYAN_LVL || "debug");

// module.exports.ga = require('universal-analytics')(nconf.get('GA_ID'));

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Server-related libraries
var __
,	express = require('express')
,	helmet 	= require('helmet')
, 	bParser	= require('body-parser')
,	passport= require('passport')
, 	http 	= require('http')
;

var app = express();

app.set('logger', logger);
app.use(function (req, res, next) {
	req.logger = logger;
	next();
});

var mongoose = require('./config/mongoose')(app);

/*
** Template engines and static files. **/
var swig = require('./core/swig')
app.engine('html', swig.renderFile);
app.set('view engine', 'html'); 			// make '.html' the default
app.set('views', nconf.get('viewsRoot')); 	// set views for error and 404 pages
app.set('view cache', false);
app.use(require('compression')());
app.use('/robots.txt', express.static(path.join(nconf.get('staticRoot'), 'robots.txt')));
app.use('/humans.txt', express.static(path.join(nconf.get('staticRoot'), 'humans.txt')));
app.use(require('serve-favicon')(path.join(nconf.get('staticRoot'), 'favicon.ico')));

swig.setDefaults({ cache: false });
if (nconf.get('env') === 'development') {
}

/******************************************************************************/
/* BEGINNING of a DO_NOT_TOUCH_ZONE *******************************************/
app.use(helmet.defaults());
app.use(bParser.urlencoded({ extended: true }));
app.use(bParser.json());
app.use(require('method-override')());
app.use(require('express-validator')());
app.use(nconf.get('staticUrl'), express.static(nconf.get('staticRoot')));
app.use(require('cookie-parser')());
/** END of a DO_NOT_TOUCH_ZONE ----------------------------------------------**/
/**--------------------------------------------------------------------------**/

/******************************************************************************/
/** BEGINNING of a SHOULD_NOT_TOUCH_ZONE **************************************/
var session = require('express-session');
app.use(session({
	store: new (require('connect-mongo')(session))({ db: mongoose.connection.db }),
	// store: new (require('connect-redis')(session))({ url: process.env.REDISTOGO_URL || '' }),
	secret: process.env.SESSION_SECRET || 'mysecretes',
	cookie: {
		httpOnly: true,
		secure: false,
		// expires: new Date(Date.now() + 24*60*60*1000),
		maxAge: 24*60*60*1000,
	},
	rolling: true,
	resave: true,
	saveUninitialized: true,
}));
app.use(require('csurf')());
app.use(function(req, res, next){
	res.locals.token = req.csrfToken();	// Add csrf token to views's locals.
	next();
});
app.use(require('connect-flash')()); 	// Flash messages middleware
app.use(passport.initialize());
app.use(passport.session());
/** END of a SHOULD_NOT_TOUCH_ZONE ------------------------------------------**/
/**--------------------------------------------------------------------------**/

app.use(require('./core/middlewares/local_user'));
app.use(require('./core/reqExtender'));
app.use(require('./core/resExtender'));
require('./core/locals/all')(app);

/**--------------------------------------------------------------------------**/

app.use('/api', require('./api/controllers')(app));
app.use('/', require('./app/controllers')(app));

app.use(require('./core/middlewares/handle_404')); // Handle 404
app.use(require('./core/middlewares/handle_500')); // Handle 500 (and log)

var server = http.createServer(app);

process.on('exit', function() {
	logger.info('exit');
});

server.listen(nconf.get('PORT') || 3000, function () {
	logger.info('Server on port %d in mode %s', nconf.get('PORT') || 3000, nconf.get('env'));
});

module.exports = server;


text:
/*global define*/
///////////////////////////////////////////////////////////////////////////
// Copyright © 2015 Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
  "units": {
    "miles": {
      "displayText": "Miles",
      "acronym": "mi"
    },
    "kilometers": {
      "displayText": "Kilomètres",
      "acronym": "km"
    },
    "feet": {
      "displayText": "Pieds",
      "acronym": "pi"
    },
    "meters": {
      "displayText": "Mètres",
      "acronym": "m"
    }
  },
  "searchSetting": {
    "searchSettingTabTitle": "Paramètres de recherche",
    "defaultBufferDistanceLabel": "Définir la distance par défaut de la zone tampon",
    "maxBufferDistanceLabel": "Définir la distance maximum de la zone tampon",
    "bufferDistanceUnitLabel": "Unités de distance de la zone tampon",
    "defaultBufferHintLabel": "Astuce : définissez la valeur par défaut du curseur de la zone tampon",
    "maxBufferHintLabel": "Astuce : définissez la valeur maximum du curseur de la zone tampon",
    "bufferUnitLabel": "Astuce : définissez l'unité pour créer la zone tampon",
    "selectGraphicLocationSymbol": "Symbole d'adresse ou d'emplacement",
    "graphicLocationSymbolHintText": "Astuce : symbole d'une adresse recherchée ou d'un emplacement sélectionné",
    "fontColorLabel": "Sélectionner la couleur de police pour les résultats de la recherche",
    "fontColorHintText": "Astuce : couleur de police des résultats de la recherche",
    "zoomToSelectedFeature": "Zoom sur l'entité sélectionnée",
    "zoomToSelectedFeatureHintText": "Astuce : zoomez sur l'entité sélectionnée au lieu de la zone tampon",
    "intersectSearchLocation": "Revenir aux polygones d'intersection",
    "intersectSearchLocationHintText": "Astuce : renvoyez les polygones contenant l'emplacement recherché au lieu des polygones au sein de la zone tampon",
    "bufferVisibilityLabel": "Définir la visibilité de la zone tampon",
    "bufferVisibilityHintText": "Astuce : la zone tampon s'affichera sur la carte",
    "bufferColorLabel": "Définir le symbole de la zone tampon",
    "bufferColorHintText": "Astuce : sélectionnez la couleur et la transparence de la zone tampon",
    "searchLayerResultLabel": "Dessiner uniquement les résultats de la couche sélectionnée",
    "searchLayerResultHint": "Astuce : seule la couche sélectionnée dans les résultats de recherche s'affichera sur la carte."
  },
  "layerSelector": {
    "selectLayerLabel": "Sélectionner des couches de recherche",
    "layerSelectionHint": "Astuce : utilisez le bouton Définir pour sélectionner les couches",
    "addLayerButton": "Définir"
  },
  "routeSetting": {
    "routeSettingTabTitle": "Attributs de direction",
    "routeServiceUrl": "Service de calcul d'itinéraire",
    "buttonSet": "Définir",
    "routeServiceUrlHintText": "Astuce : cliquez sur Définir pour rechercher et sélectionner un service de calcul d'itinéraire",
    "directionLengthUnit": "Unités de longueur de la direction",
    "unitsForRouteHintText": "Astuce : utilisé pour afficher les unités de l'itinéraire",
    "selectRouteSymbol": "Sélectionner le symbole pour afficher l'itinéraire",
    "routeSymbolHintText": "Astuce : utilisé pour afficher le symbole linéaire de l'itinéraire",
    "routingDisabledMsg": "Pour activer les directions, assurez-vous que le calcul d'itinéraire est activé dans l'élément ArcGIS Online."
  },
  "networkServiceChooser": {
    "arcgislabel": "Ajouter depuis ArcGIS Online",
    "serviceURLabel": "Ajouter une URL de service",
    "routeURL": "URL de l'itinéraire",
    "validateRouteURL": "Valider",
    "exampleText": "Exemple",
    "hintRouteURL1": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/",
    "hintRouteURL2": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
    "invalidRouteServiceURL": "Spécifiez un service d'itinéraire valide.",
    "rateLimitExceeded": "Limite de débit atteinte. Réessayez ultérieurement.",
    "errorInvokingService": "Le nom d'utilisateur ou le mot de passe est incorrect."
  },
  "errorStrings": {
    "bufferErrorString": "Saisissez une valeur numérique valide.",
    "selectLayerErrorString": "Sélectionnez les couches à rechercher.",
    "invalidDefaultValue": "La distance de la zone tampon par défaut ne peut pas être vide. Veuillez spécifier la distance de la zone tampon.",
    "invalidMaximumValue": "La distance de la zone tampon maximale ne peut pas être vide. Veuillez spécifier la distance de la zone tampon.",
    "defaultValueLessThanMax": "Spécifiez la distance de la zone tampon par défaut au sein de la limite maximale",
    "defaultBufferValueGreaterThanZero": "Spécifiez une distance de la zone tampon par défaut supérieure à 0",
    "maximumBufferValueGreaterThanZero": "Spécifiez une distance de la zone tampon maximale supérieure à 0"
  },
  "symbolPickerPreviewText": "Aperçu :"
});


text:
@interface MOBProjectionEPSG3674 : MOBProjection

@end


text:
package org.apache.tika.server;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.apache.tika.parser.ocr.TesseractOCRConfig;
import org.apache.tika.parser.ocr.TesseractOCRParser;
import org.apache.tika.server.resource.TikaResource;
import org.junit.Test;

public class TikaResourceTest extends CXFTestBase {
    public static final String TEST_DOC = "test.doc";
    public static final String TEST_PASSWORD_PROTECTED = "password.xls";
    private static final String TEST_RECURSIVE_DOC = "test_recursive_embedded.docx";

    private static final String TIKA_PATH = "/tika";
    private static final int UNPROCESSEABLE = 422;

    @Override
    protected void setUpResources(JAXRSServerFactoryBean sf) {
        sf.setResourceClasses(TikaResource.class);
        sf.setResourceProvider(TikaResource.class,
                new SingletonResourceProvider(new TikaResource()));
    }

    @Override
    protected void setUpProviders(JAXRSServerFactoryBean sf) {
        List<Object> providers = new ArrayList<Object>();
        providers.add(new TikaServerParseExceptionMapper(false));
        sf.setProviders(providers);
    }

    @Test
    public void testHelloWorld() throws Exception {
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("text/plain").accept("text/plain").get();
        assertEquals(TikaResource.GREETING,
                getStringFromInputStream((InputStream) response.getEntity()));
    }

    @Test
    public void testSimpleWord() throws Exception {
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/msword")
                .accept("text/plain")
                .put(ClassLoader.getSystemResourceAsStream(TEST_DOC));
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("test"));
    }

    @Test
    public void testTextMain() throws Exception {
        //boilerpipe
        Response response = WebClient.create(endPoint + TIKA_PATH + "/main")
                .accept("text/plain")
                .put(ClassLoader.getSystemResourceAsStream("testHTML.html"));
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("Title : Test Indexation Html"));
        assertFalse(responseMsg.contains("Indexation du fichier"));
    }

    @Test
    public void testTextMainMultipart() throws Exception {
        //boilerpipe
        Attachment attachmentPart =
                new Attachment("myhtml", "text/html", ClassLoader.getSystemResourceAsStream("testHTML.html"));

        Response response = WebClient.create(endPoint + TIKA_PATH+"/form/main")
                .type("multipart/form-data")
                .accept("text/plain")
                .post(attachmentPart);
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("Title : Test Indexation Html"));
        assertFalse(responseMsg.contains("Indexation du fichier"));
    }

    @Test
    public void testApplicationWadl() throws Exception {
        Response response = WebClient
                .create(endPoint + TIKA_PATH + "?_wadl")
                .accept("text/plain").get();
        String resp = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(resp.startsWith("<application"));
    }

    @Test
    public void testPasswordXLS() throws Exception {
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/vnd.ms-excel")
                .accept("text/plain")
                .put(ClassLoader.getSystemResourceAsStream("password.xls"));

        assertEquals(UNPROCESSEABLE, response.getStatus());
    }

    @Test
    public void testSimpleWordHTML() throws Exception {
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/msword")
                .accept("text/html")
                .put(ClassLoader.getSystemResourceAsStream(TEST_DOC));
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("test"));
        assertContains("<meta name=\"X-TIKA:digest:MD5\" content=\"f8be45c34e8919eedba48cc8d207fbf0\"/>",
                responseMsg);
    }

    @Test
    public void testPasswordXLSHTML() throws Exception {
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/vnd.ms-excel")
                .accept("text/html")
                .put(ClassLoader.getSystemResourceAsStream("password.xls"));

        assertEquals(UNPROCESSEABLE, response.getStatus());
    }

    @Test
    public void testSimpleWordXML() throws Exception {
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/msword")
                .accept("text/xml")
                .put(ClassLoader.getSystemResourceAsStream(TEST_DOC));
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("test"));
    }

    @Test
    public void testPasswordXLSXML() throws Exception {
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/vnd.ms-excel")
                .accept("text/xml")
                .put(ClassLoader.getSystemResourceAsStream("password.xls"));

        assertEquals(UNPROCESSEABLE, response.getStatus());
    }

    @Test
    public void testSimpleWordMultipartXML() throws Exception {
        ClassLoader.getSystemResourceAsStream(TEST_DOC);
        Attachment attachmentPart =
                new Attachment("myworddoc", "application/msword", ClassLoader.getSystemResourceAsStream(TEST_DOC));
        WebClient webClient = WebClient.create(endPoint + TIKA_PATH + "/form");
        Response response = webClient.type("multipart/form-data")
                .accept("text/xml")
                .post(attachmentPart);
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("test"));
        assertContains("<meta name=\"X-TIKA:digest:MD5\" content=\"f8be45c34e8919eedba48cc8d207fbf0\"/>",
                responseMsg);

    }

    @Test
    public void testEmbedded() throws Exception {
        //first try text
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .accept("text/plain")
                .put(ClassLoader.getSystemResourceAsStream(TEST_RECURSIVE_DOC));
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("Course of human events"));

        //now go for xml -- different call than text
        response = WebClient.create(endPoint + TIKA_PATH)
                .accept("text/xml")
                .put(ClassLoader.getSystemResourceAsStream(TEST_RECURSIVE_DOC));
        responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("Course of human events"));
        assertContains("<meta name=\"X-TIKA:digest:MD5\" content=\"59f626e09a8c16ab6dbc2800c685f772\"/>",
                responseMsg);

    }

    //TIKA-1845
    @Test
    public void testWMFInRTF() throws Exception {
        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/rtf")
                .accept("text/plain")
                .put(ClassLoader.getSystemResourceAsStream("testRTF_npeFromWMFInTikaServer.rtf"));
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.contains("Example text"));
    }

    //TIKA-2290
    @Test
    public void testPDFOCRConfig() throws Exception {
        if (! new TesseractOCRParser().hasTesseract(new TesseractOCRConfig())) {
            return;
        }

        Response response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/pdf")
                .accept("text/plain")
                .header(TikaResource.X_TIKA_PDF_HEADER_PREFIX+"OcrStrategy", "no_ocr")
                .put(ClassLoader.getSystemResourceAsStream("testOCR.pdf"));
        String responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertTrue(responseMsg.trim().equals(""));

        response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/pdf")
                .accept("text/plain")
                .header(TikaResource.X_TIKA_PDF_HEADER_PREFIX+"OcrStrategy", "ocr_only")
                .put(ClassLoader.getSystemResourceAsStream("testOCR.pdf"));
        responseMsg = getStringFromInputStream((InputStream) response
                .getEntity());
        assertContains("Happy New Year 2003!", responseMsg);

        //now try a bad value
        response = WebClient.create(endPoint + TIKA_PATH)
                .type("application/pdf")
                .accept("text/plain")
                .header(TikaResource.X_TIKA_PDF_HEADER_PREFIX + "OcrStrategy", "non-sense-value")
                .put(ClassLoader.getSystemResourceAsStream("testOCR.pdf"));
        assertEquals(500, response.getStatus());
    }
}


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

<title>de.esoco.ewt.geometry (gewt 1.2.0 API)</title>
<meta name="date" content="2018-10-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package de.esoco.ewt.geometry

Class Summary

Class
Description

Margins

Simple immutable class that holds integer margins for rectangular areas.

Point

Unmodifiable representation of a 2-dimensional screen coordinate.

Rectangle

Unmodifiable representation of a 2-dimensional screen rectangle.

Size

Unmodifiable representation of a 2-dimensional size value.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
package org.terasology.rendering.dag.nodes;

import org.terasology.assets.ResourceUrn;
import org.terasology.config.Config;
import org.terasology.config.RenderingConfig;
import org.terasology.registry.In;
import org.terasology.rendering.opengl.FBOConfig;
import org.terasology.rendering.opengl.fbms.DisplayResolutionDependentFBOs;

/**
 * This class is a thin facade in front of the BlurNode class it inherits from.
 *
 * Instances of this class specialize the blur operation to render a "Haze" layer,
 * combined later in the pipeline to progressively fade the rendered world into
 * the backdrop.
 *
 * I.e. if the sky is pink at sunset, faraway hills will fade into pink as they get
 * further away from the camera.
 */
public class HazeNode extends BlurNode {

    public static final ResourceUrn INTERMEDIATE_HAZE = new ResourceUrn("engine:intermediateHaze");
    public static final ResourceUrn FINAL_HAZE = new ResourceUrn("engine:finalHaze");
    private static final float BLUR_RADIUS = 8.0f;

    @In
    private DisplayResolutionDependentFBOs displayResolutionDependentFBOs;

    @In
    private Config config;

    private RenderingConfig renderingConfig;

    /**
     * Initializes the HazeNode instance.
     *
     * @param inputConfig an FBOConfig describing the input FBO, to be retrieved from an injected DisplayResolutionDependentFBOs instance.
     * @param outputConfig an FBOConfig describing the output FBO, to be retrieved from an injected DisplayResolutionDependentFBOs instance.
     * @param aLabel a String to label the instance's entry in output generated by the PerformanceMonitor
     */
    public void initialise(FBOConfig inputConfig, FBOConfig outputConfig, String aLabel) {
        super.initialise(inputConfig, outputConfig, displayResolutionDependentFBOs, BLUR_RADIUS, aLabel);
    }

    /**
     * This method establishes the conditions in which the blur will take place, by enabling or disabling the node.
     *
     * In this particular case the node is enabled if RenderingConfig.isInscattering() returns true.
     */
    @Override
    protected void setupConditions() {
        renderingConfig = config.getRendering();
        renderingConfig.subscribe(RenderingConfig.INSCATTERING, this);
        requiresCondition(() -> renderingConfig.isInscattering());
    }
}


text:
require_relative 'resource'

module OneviewSDK
  module API200
    # FCoE network resource implementation
    class FCoENetwork < Resource
      BASE_URI = '/rest/fcoe-networks'.freeze

      # Create a resource object, associate it with a client, and set its properties.
      # @param [OneviewSDK::Client] client The client object for the OneView appliance
      # @param [Hash] params The options for this resource (key-value pairs)
      # @param [Integer] api_ver The api version to use when interracting with this resource.
      def initialize(client, params = {}, api_ver = nil)
        super
        # Default values:
        @data['connectionTemplateUri'] ||= nil
        @data['type'] ||= 'fcoe-network'
      end
    end
  end
end


text:
package com.google.gerrit.client.account;

import com.google.gerrit.common.data.AccountSecurity;
import com.google.gerrit.common.data.AccountService;
import com.google.gerrit.common.data.ProjectAdminService;
import com.google.gerrit.reviewdb.Project;
import com.google.gwt.core.client.GWT;
import com.google.gwtjsonrpc.client.JsonUtil;

public class Util {
  public static final AccountConstants C = GWT.create(AccountConstants.class);
  public static final AccountMessages M = GWT.create(AccountMessages.class);
  public static final AccountService ACCOUNT_SVC;
  public static final AccountSecurity ACCOUNT_SEC;
  public static final ProjectAdminService PROJECT_SVC;

  static {
    ACCOUNT_SVC = GWT.create(AccountService.class);
    JsonUtil.bind(ACCOUNT_SVC, "rpc/AccountService");

    ACCOUNT_SEC = GWT.create(AccountSecurity.class);
    JsonUtil.bind(ACCOUNT_SEC, "rpc/AccountSecurity");

    PROJECT_SVC = GWT.create(ProjectAdminService.class);
    JsonUtil.bind(PROJECT_SVC, "rpc/ProjectAdminService");
  }
}