text:
import * as path from 'path';
import * as fs from 'fs';
import * as _ from 'lodash';

import { LoaderConfig } from '../interfaces';

const temp = require('temp').track();
require('source-map-support').install();

import { expect } from 'chai';
export { expect };

const webpack = require('webpack');
const BPromise = require('bluebird');

const mkdirp = BPromise.promisify(require('mkdirp'));
const rimraf = BPromise.promisify(require('rimraf'));
const readFile = BPromise.promisify(fs.readFile);
const writeFile = BPromise.promisify(fs.writeFile);
const loaderDir = path.join(process.cwd(), 'dist');

export const defaultOutputDir = path.join(process.cwd(), 'src', 'test', 'output');
export const defaultFixturesDir = path.join(process.cwd(), 'src', 'test', 'fixtures');

export interface ConfigOptions {
    loaderQuery?: LoaderConfig;
    watch?: boolean;
    include?: (string | RegExp)[];
    exclude?: (string | RegExp)[];
}

let defaultOptions: ConfigOptions = {
    watch: false,
};

export function createConfig(conf, _options: ConfigOptions = defaultOptions) {
    let options: ConfigOptions = _.merge({}, defaultOptions, _options);
    const defaultConfig = {
        watch: false,
        output: {
            path: defaultOutputDir,
            filename: '[name].js'
        },
        resolve: {
            extensions: ['.ts', '.tsx', '.js', '.jsx'],
        },
        module: {
            loaders: [
                {
                    test: defaultOptions && defaultOptions.loaderQuery && (defaultOptions.loaderQuery as any).allowJs
                        ? /\.(tsx?|jsx?)/
                        : /\.tsx?/,
                    loader: loaderDir,
                    query: Object.assign(
                        {
                            target: 'es6',
                        },
                        {
                            configFileContent: {
                                exclude: ["*"]
                            }
                        },
                        options.loaderQuery
                    )
                },
            ],
        },
        plugins: []
    };

    let loader = defaultConfig.module.loaders[0] as any;

    if (options.include) {
        loader.include = (loader.include || []).concat(options.include);
    }

    if (options.exclude) {
        loader.exclude = (loader.exclude || []).concat(options.exclude);
    }

    if (options.watch) {
        defaultConfig.watch = true;
    }

    return _.merge(defaultConfig, conf);
}

export async function chroot<T>(root: string, foo: () => Promise<T>): Promise<T> {
    let cwd = process.cwd();
    process.chdir(root);
    let result = await foo();
    process.chdir(cwd);
    return result;
}

export function expectSource(source: string, fragment: string) {
    expect(source.replace(/\s/g, '')).include(fragment.replace(/\s/g, ''));
}

export function fixturePath(fileName: string | string[], fixturesDir: string = defaultFixturesDir): string {
    return path.join.apply(path, [fixturesDir].concat(fileName as any));
}

export function readFixture(fileName: string | string[], fixturesDir: string = defaultFixturesDir): Promise<string> {
    let filePath = fixturePath(fileName, fixturesDir);
    return readFile(filePath).then(buf => buf.toString());
}

export function writeFixture(fileName: string | string[], text: string, fixturesDir: string = defaultFixturesDir): Promise<any> {
    let filePath = fixturePath(fileName, fixturesDir);
    return writeFile(filePath, text);
}

export function touchFile(fileName: string): Promise<any> {
    return readFile(fileName)
        .then(buf => buf.toString())
        .then(source => writeFile(fileName, source));
}

export function outputFileName(fileName: string, outputDir: string = defaultOutputDir): string {
    return path.join(defaultOutputDir, fileName);
}

export function readOutputFile(fileName?: string, outputDir: string = defaultOutputDir): Promise<string> {
    return readFile(outputFileName(fileName || 'main.js', outputDir)).then(buf => buf.toString());
}

export function cleanOutputDir(outputDir: string = defaultOutputDir): Promise<any> {
    return rimraf(outputDir)
        .then(() => mkdirp(outputDir));
}

export function cleanAndCompile(config, outputDir: string = defaultOutputDir): Promise<any> {
    return cleanOutputDir(outputDir)
        .then(() => compile(config));
}

export function compile(config): Promise<any> {
    return new Promise((resolve, reject) => {
        let compiler = webpack(config);
        compiler.run((err, stats) => {
            if (err) {
                reject(err);
            } else {
                resolve(stats);
            }
        });
    });
}

export function watch(config, cb?: (err, stats) => void): Watch {
    let compiler = webpack(config);
    let watch = new Watch();
    let webpackWatcher = compiler.watch({}, (err, stats) => {
        watch.call(err, stats);
        if (cb) {
            cb(err, stats);
        }
    });

    watch.close = webpackWatcher.close;
    return watch;
}

export class Watch {
    resolves: ((arg: any[]) => void)[] = [];
    close: () => void;

    call(err, stats) {
        this.resolves.forEach(resolver => {
            resolver([err, stats]);
        });
        this.resolves = [];
    }

    wait(): Promise<any> {
        return new Promise((resolve, reject) => {
            this.resolves.push(resolve);
        });
    }
}

export class Fixture {
    private text: string;
    private fileName: string;
    constructor(text: string, ext = '.tsx') {
        this.text = text;
        let tmpobj = temp.openSync({
            prefix: 'atl-',
            suffix: '.tsx'
        });

        this.fileName = tmpobj.path;

        fs.writeFileSync(this.fileName, text);
    }

    path() {
        return this.fileName;
    }

    touch() {
        touchFile(this.fileName);
    }

    update(updater: (text: string) => string) {
        let newText = updater(this.text);
        this.text = newText;
        fs.writeFileSync(this.fileName, newText);
    }
}


text:
<?php

namespace Simlux\LaravelGenerator\Model\Property;

use Illuminate\Container\Container;
use Illuminate\Support\Facades\Config;
use Simlux\LaravelGenerator\Configuration\ConfigurationHelper;

class ExtendsProperty extends AbstractProperty
{

    /**
     * @return void
     */
    public function handle()
    {
        $extends = ConfigurationHelper::getDynamicValue('generator.model.defaults.extends', [
            'APP_NAME' => rtrim(Container::getInstance()->getNamespace(), '\\'),
        ]);

        if (Config::get('generator.interaction.extends')) {
            $extends = $this->generator->ask('Model Parent Class', $extends);
        }

        $this->model->setExtends($extends);
    }

    public function printMessage()
    {
        $this->generator->comment('Model extends: ' . $this->model->getExtends());
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * The "configVersions" collection of methods.
 * Typical usage is:
 *  <code>
 *   $cloudiotService = new Google_Service_CloudIot(...);
 *   $configVersions = $cloudiotService->configVersions;
 *  </code>
 */
class Google_Service_CloudIot_Resource_ProjectsLocationsRegistriesDevicesConfigVersions extends Google_Service_Resource
{
  /**
   * Lists the last few versions of the device configuration in descending order
   * (i.e.: newest first).
   * (configVersions.listProjectsLocationsRegistriesDevicesConfigVersions)
   *
   * @param string $name The name of the device. For example,
   * `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
   * `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
   * @param array $optParams Optional parameters.
   *
   * @opt_param int numVersions The number of versions to list. Versions are
   * listed in decreasing order of the version number. The maximum number of
   * versions retained is 10. If this value is zero, it will return all the
   * versions available.
   * @return Google_Service_CloudIot_ListDeviceConfigVersionsResponse
   */
  public function listProjectsLocationsRegistriesDevicesConfigVersions($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_CloudIot_ListDeviceConfigVersionsResponse");
  }
}


text:
require "spec_helper"

describe Group do
  describe "to be valid" do
    subject { build(:group) }

    it "must have a name" do
      subject.name = ""
      expect(subject).to have(1).error_on(:name)
    end

    it "must have a short name" do
      subject.short_name = ""
      expect(subject).to have(1).error_on(:short_name)
    end

    it "must have a default thread privacy" do
      subject.default_thread_privacy = ""
      expect(subject).to have(1).error_on(:default_thread_privacy)
    end
  end

  describe "scopes" do
    it "has ordered scope" do
      group = create :group
      membership = create :group_membership
      group_with_messages = membership.group
      create :message_thread, group: group_with_messages, created_by: membership.user
      expect(described_class.ordered).to eq [group_with_messages, group]
    end
  end

  it ".from_geo_or_name" do
    expect(described_class.from_geo_or_name("")).to be_blank
  end

  describe "#update_potetial_members" do
    let(:group) { create(:group) }

    it "errors if there is a problem" do
      group.update_potetial_members("a@b.com\naab.com")
      expect(group.errors[:potential_members]).to include("Email 'aab.com' is an invalid format for an email address")
    end

    context "with existing potential_members" do
      before do
        group.update_potetial_members("a@b.com\na1@b.com")
      end

      it "wipes existing potential_members if it sucesseds" do
        group.update_potetial_members("a@b.com\nc@d.com")
        expect(group.potential_members.map(&:email_hash)).to contain_exactly(
          PotentialMember.new(email: "a@b.com").email_hash,
          PotentialMember.new(email: "c@d.com").email_hash
        )
      end
    end
  end

  it ".from_geo_name" do
    stub_request(:get, %r{https://api\.cyclestreets\.net/v2/geocoder\?key=.*&q=leeds})
      .with(headers: { "Accept" => "application/json" })
      .to_return(
        status: 200, body: <<-JSON
          {
              "type": "FeatureCollection",
              "features": [
                  {
                      "type": "Feature",
                      "properties": {
                          "name": "Leeds",
                          "near": "Yorkshire and the Humber, England",
                          "bbox": "-0.04,52.289,-0.01,52.29"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -1.5437941,
                              53.7974185
                          ]
                      }
                  }
              ]
          }
        JSON
      )
    quahogc_profile = create(:quahogcc_group_profile)
    leeds = create(:group, name: "LEEDS")

    expect(described_class.from_geo_or_name("leeds")).to match_array [quahogc_profile.group, leeds]
  end

  describe "newly created" do
    subject { create(:group) }

    it "must have a profile" do
      expect(subject.profile).to be_valid
      expect(subject.profile.new_user_email).to include "Hi {{full_name}},\n #{subject.name} has added you to their Cyclescape group http://"
    end

    it "should have a default thread privacy of public" do
      expect(subject.default_thread_privacy).to eql("public")
    end

    describe "short name" do
      it "should be unique" do
        expect(subject).to validate_uniqueness_of(:short_name).ignoring_case_sensitivity
      end

      it "should not allow bad characters" do
        ["£", "$", "%", "^", "&"].each do |char|
          subject.short_name = char
          expect(subject).to have(1).error_on(:short_name)
        end
      end

      it "should be short enough to be a subdomain" do
        subject.short_name = "c" * 64
        expect(subject).to have(1).error_on(:short_name)
      end

      it "should not be an important subdomain" do
        %w[www ftp smtp imap munin].each do |d|
          subject.short_name = d
          expect(subject).to have(1).error_on(:short_name)
        end
      end

      it "can't contain a hyphen" do
        %w[-foo foo-].each do |d|
          subject.short_name = d
          expect(subject).to have(1).error_on(:short_name)
        end
      end
    end
  end

  describe "validations" do
    subject { create(:group) }

    it { is_expected.to allow_value("public").for(:default_thread_privacy) }
    it { is_expected.to allow_value("group").for(:default_thread_privacy) }
    it { is_expected.not_to allow_value("other").for(:default_thread_privacy) }
    it { is_expected.to validate_uniqueness_of(:name) }
  end

  context "members" do
    let(:membership) { create(:brian_at_quahogcc) }
    let(:brian) { membership.user }

    subject { membership.group }

    it "should list committee members" do
      expect(subject.committee_members).to include(brian)
    end

    describe "#has_member?" do
      it "should be true for Brian" do
        expect(subject.has_member?(brian)).to be_truthy
      end

      it "should be false for another user" do
        new_user = create(:user)
        expect(subject.has_member?(new_user)).to be_falsey
      end
    end

    describe "thread privacy options" do
      let(:non_member) { build(:user) }
      let(:admin) { build(:user, :admin) }
      let(:member) { create(:group_membership, group: group).user }
      let(:committee) { create(:group_membership, :committee, group: group).user }

      context "with a default_thread_privacy of group" do
        let(:group) { create :group, default_thread_privacy: "group" }

        it "should let admins set any privacy" do
          expect(group.thread_privacy_options_for(admin)).to contain_exactly(MessageThread::PUBLIC, MessageThread::GROUP, MessageThread::COMMITTEE)
        end

        it "should include public and committee for committee members" do
          expect(group.thread_privacy_options_for(committee)).to contain_exactly(MessageThread::PUBLIC, MessageThread::GROUP, MessageThread::COMMITTEE)
        end

        it "does not allow the privacy to be changed away from group" do
          expect(group.thread_privacy_options_for(member)).to contain_exactly(MessageThread::GROUP)
        end
      end

      context "with a public default_thread_privacy" do
        let(:group) { create :group, default_thread_privacy: "public" }

        it "when not in the group allows no privacies" do
          expect(group.thread_privacy_options_for(non_member)).to eq []
        end

        it "allows group or public" do
          expect(group.thread_privacy_options_for(member)).to contain_exactly(MessageThread::GROUP, MessageThread::PUBLIC)
        end
      end
    end
  end

  describe "#active_user_counts" do
    subject { create(:group) }
    let(:thread_1) { create(:message_thread, group: subject, created_by: active_poster) }
    let(:thread_2) { create(:message_thread, group: subject, created_by: active_poster) }
    let(:active_poster) { create(:group_membership, group: subject).user }
    let(:quiet_poster) { create(:group_membership, group: subject).user }
    let(:not_in_group) { create :user }

    before do
      create_list(:message, 2, thread: thread_1, created_by: active_poster)
      create_list(:message, 2, thread: thread_1, created_by: not_in_group)
      create_list(:message, 3, thread: thread_2, created_by: active_poster)
      create_list(:message, 1, thread: thread_2, created_by: quiet_poster)
      create_list(:message, 1, thread: thread_2, created_by: quiet_poster, created_at: 2.years.ago)
    end

    it "returns the top N with counts" do
      expect(subject.active_user_counts).to eq(
        [{ user: active_poster, count: 5 }, { user: quiet_poster, count: 1 }]
      )

      expect(subject.active_user_counts(since: 1.hour.ago, limit: 1)).to eq(
        [{ user: active_poster, count: 5 }]
      )
    end
  end
end


text:
title: In pausa.
---

![](https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1454002278l/22098759._SY475_.jpg)

# In pausa. Come l'ossessione per il fare sta distruggendo le nostre menti (Smart, Andrew)

> path lenghts. Quella di cui stiamo parlando è una «rete piccolo mondo» e
> funziona esattamente come il gioco del numero di Kevin Bacon o la teoria dei
> sei gradi di separazione.

> Attraverso un fenomeno chiamato «risonanza stocastica», il rumore crea ordine.

> Essere in grado di immaginare il passato e il futuro richiede necessariamente
> una maggiore memoria. La capacità di prepararsi a stati futuri di fame, freddo
> o sete – di contro al mero reagire agli stimoli del momento – è forse ciò che
> ha dato inizio alla rapida evoluzione culturale dell'essere umano.

> chi è abituato a fare più cose contemporaneamente non sa ignorare le
> informazioni irrilevanti perché la sua attenzione è assorbita da tutte le
> altre cose che non sta facendo.

> «Quando stabiliamo i nostri limiti e troviamo un equilibrio ottimale tra
> domanda cognitiva e possibilità […] non solo ricaviamo una soddisfazione
> profonda ma sviluppiamo al massimo le capacità del nostro cervello». Ciò
> innesca un meccanismo di feedback positivo, che è anche una caratteristica dei
> sistemi non lineari. Perché questo meccanismo si inneschi, gran parte del
> lavoro consiste nel non far nulla.

> Quando si abbassano i livelli di glucosio, di elettroliti o di acqua,
> operazioni cerebrali non necessarie all'immediata sopravvivenza, come per
> esempio la lucidità di pensiero, vengono sacrificate perché il cervello possa
> mantenere funzioni vitali come la respirazione.

> Poche persone temono il sovrappeso quanto temono il terrorismo, eppure,
> statisticamente, l'obesità minaccia la nostra vita molto più del terrorismo.

> Per cui è vero che non è mai troppo tardi per imparare a suonare un nuovo
> strumento, una lingua o cambiare radicalmente la propria vita: il nostro
> cervello cambierà di conseguenza. Da adulti, questi cambiamenti possono essere
> fonte di stress maggiore, ma sono spesso positivi per la salute a lungo
> termine del nostro cervello.

si è scoperto che la maggior parte dell'attività del cervello è rappresentata da
quella intrinseca.

> Le due reti che ho descritto finora vengono denominate anche Task Positive
> Network (TPN) e Task Negative Network (TNN). La TNN è la rete di default. La
> TPN è quella che si attiva quando si cerca freneticamente di gestire il
> proprio tempo.

> La rete neurale di default sostiene la conoscenza di sé, i ricordi
> autobiografici, i processi sociali ed emozionali e la creatività. Resta attiva
> fin quando siamo rilassati.

> Come fa il cervello a raggiungere questo equilibrio tra una stabilità
> immutabile e una plasticità altamente sensibile e reattiva capace di reagire
> immediatamente a cambiamenti improvvisi dell'ambiente? Una delle possibilità,
> secondo i neuroscienziati, è che sia proprio la struttura del cervello, il
> modo in cui è organizzato e progettato, a garantire la metastabilità. Le aree
> del cervello che partecipano alla rete neurale di default paiono essenziali
> per il mantenimento della rappresentazione di sé.

> La relazione tra genio e pazzia è stata a lungo studiata. Secondo molti
> ricercatori il confine tra i due è molto sottile.

> Per misurare il grado di controllo che le persone sentono di avere sulle
> proprie vite, gli psicologi usano da tempo un questionario che si chiama Scala
> di controllo interno-esterno di Rotter.

> Jarosław Kwapień e Stanisław Dróżdż, un sistema auto-organizzante complesso «è
> formato da un grande numero di componenti che interagiscono in maniera non
> lineare e manifestano un comportamento collettivo, e, per uno scambio di
> energia o informazioni con l'ambiente, può facilmente modificare la sua
> struttura interna e i suoi pattern di attività».

> il comportamento complesso di un sistema ha delle caratteristiche
> macroscopiche che nessuna delle parti costituenti del sistema presenta.

> Secondo Bertrand Russell esistono due tipi di lavoro: «Il primo, modificare la
> posizione di materia sulla o vicino alla superficie della Terra
> rispettivamente ad altra materia simile; il secondo, dire ad altre persone di
> fare questo. Il primo tipo è brutto e mal pagato; il secondo è piacevole e
> pagato molto bene».

> Come indicava Einstein, ognuno di noi dovrebbe essere libero di far emergere
> naturalmente il proprio ordine e la propria struttura e trascorrere le
> giornate come vuole. Tutti odiano lavorare per qualcun altro. Ed essere
> impegnati come pazzi tutto il tempo non solo ci fa male, ma ci impedisce anche
> di scoprire la persona che eravamo destinati a diventare.

> L'anarchico Michail Bakunin scriveva: «La mia libertà è la libertà di tutti».
> Quello che intendeva è che se anche una sola persona vive in stato di
> schiavitù, allora nessuno di noi è veramente libero.

> Benzi chiamò la combinazione di eccentricità e rumore «risonanza stocastica»,
> proprio a voler significare che il rumore amplifica l'effetto
> dell'eccentricità.

> capacità che ha il rumore di amplificare i segnali

> il cervello cerca sempre di mantenersi in uno stato omeostatico, quando si
> verifica uno squilibrio si attiverà un meccanismo compensatorio

> Nel 2010 Lawrence Ward, un neuroscienziato della University of British
> Columbia, pioniere dello studio della risonanza magnetica applicata al
> cervello umano, ha pubblicato insieme ai colleghi uno studio rivoluzionario
> intitolato Stochastic Resonance Modulates Neural Synchronization within and
> between Cortical Sources. Questo studio dimostra che il rumore influenza sia
> il modo in cui i neuroni sincronizzano la loro attività all'interno di una
> regione cerebrale sia il modo in cui si sincronizzano tra loro regioni
> cerebrali separate.

> Quindi, se fino a ora il rumore è stato visto come qualcosa che ci distrae
> dalla verità e per questo da eliminare, presto potremmo scoprire che il nostro
> cervello ha bisogno proprio del rumore per trovare la verità. Abbracciando
> l'ozio, abbracciamo il rumore del nostro stesso inconscio. Il vento soffia
> dentro di noi, permettendoci di sentire la verità che in esso è contenuta e
> che ci coglie di sorpresa; il vento cui aneliamo per riuscire a sentire noi
> stessi.

> La scienza è un atto creativo che ha lo stesso scopo dell'arte: liberare lo
> spirito umano.

> Per gli antichi Greci, chiunque avesse bisogno di lavorare per vivere era
> considerato uno schiavo.

> Arthur C. Clarke: «Quando uno scienziato famoso ma anziano dice che qualcosa è
> possibile, quasi certamente ha ragione. Quando dice che qualcosa è impossibile
> molto probabilmente ha torto».


text:
package org.kc7bfi.jflac.frame;

import java.io.IOException;

import org.kc7bfi.jflac.ChannelData;
import org.kc7bfi.jflac.io.BitInputStream;

/**
 * FLAC Constant Subframe (Channel) data.
 * This class represents a FLAC subframe (channel) for a Constant data
 * @author kc7bfi
 */
public class ChannelConstant extends Channel {

    /** The constant signal value. */
    private int value;

    /**
     * The constructor.
     * @param is            The InputBitStream
     * @param header        The FLAC Frame Header
     * @param channelData   The decoded channel data (output)
     * @param bps           The bits-per-second
     * @param wastedBits    The bits waisted in the frame
     * @throws IOException  Thrown if error reading from the InputBitStream
     */
    public ChannelConstant(BitInputStream is, Header header, ChannelData channelData, int bps, int wastedBits) throws IOException {
        super(header, wastedBits);

        value = is.readRawInt(bps);

        // decode the subframe
        for (int i = 0; i < header.blockSize; i++) channelData.getOutput()[i] = value;
    }

    /**
     * toString conversion.
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return "ChannelConstant: Value=" + value + " WastedBits=" + wastedBits;
    }
}


text:
#include <libmemcached/common.h>

#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif

void initialize_binary_request(memcached_instance_st* server, protocol_binary_request_header& header)
{
  server->request_id++;
  header.request.magic= PROTOCOL_BINARY_REQ;
  header.request.opaque= htons(server->request_id);
}

enum memc_read_or_write {
  MEM_READ,
  MEM_WRITE
};

/**
 * Try to fill the input buffer for a server with as much
 * data as possible.
 *
 * @param instance the server to pack
 */
static bool repack_input_buffer(memcached_instance_st* instance)
{
  if (instance->read_ptr != instance->read_buffer)
  {
    /* Move all of the data to the beginning of the buffer so
     ** that we can fit more data into the buffer...
   */
    memmove(instance->read_buffer, instance->read_ptr, instance->read_buffer_length);
    instance->read_ptr= instance->read_buffer;
    instance->read_data_length= instance->read_buffer_length;
  }

  /* There is room in the buffer, try to fill it! */
  if (instance->read_buffer_length != MEMCACHED_MAX_BUFFER)
  {
    do {
      /* Just try a single read to grab what's available */
      ssize_t nr;
      if ((nr= ::recv(instance->fd,
                      instance->read_ptr + instance->read_data_length,
                      MEMCACHED_MAX_BUFFER - instance->read_data_length,
                      MSG_NOSIGNAL)) <= 0)
      {
        if (nr == 0)
        {
          memcached_set_error(*instance, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT);
        }
        else
        {
          switch (get_socket_errno())
          {
          case EINTR:
            continue;

#if EWOULDBLOCK != EAGAIN
          case EWOULDBLOCK:
#endif
          case EAGAIN:
#ifdef __linux
          case ERESTART:
#endif
            break; // No IO is fine, we can just move on

          default:
            memcached_set_errno(*instance, get_socket_errno(), MEMCACHED_AT);
          }
        }

        break;
      }
      else // We read data, append to our read buffer
      {
        instance->read_data_length+= size_t(nr);
        instance->read_buffer_length+= size_t(nr);

        return true;
      }
    } while (false);
  }

  return false;
}

/**
 * If the we have callbacks connected to this server structure
 * we may start process the input queue and fire the callbacks
 * for the incomming messages. This function is _only_ called
 * when the input buffer is full, so that we _know_ that we have
 * at least _one_ message to process.
 *
 * @param instance the server to star processing iput messages for
 * @return true if we processed anything, false otherwise
 */
static bool process_input_buffer(memcached_instance_st* instance)
{
  /*
   ** We might be able to process some of the response messages if we
   ** have a callback set up
 */
  if (instance->root->callbacks != NULL)
  {
    /*
     * We might have responses... try to read them out and fire
     * callbacks
   */
    memcached_callback_st cb= *instance->root->callbacks;

    memcached_set_processing_input((Memcached *)instance->root, true);

    char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
    Memcached *root= (Memcached *)instance->root;
    memcached_return_t error= memcached_response(instance, buffer, sizeof(buffer), &root->result);

    memcached_set_processing_input(root, false);

    if (error == MEMCACHED_SUCCESS)
    {
      for (unsigned int x= 0; x < cb.number_of_callback; x++)
      {
        error= (*cb.callback[x])(instance->root, &root->result, cb.context);
        if (error != MEMCACHED_SUCCESS)
        {
          break;
        }
      }

      /* @todo what should I do with the error message??? */
    }
    /* @todo what should I do with other error messages?? */
    return true;
  }

  return false;
}

static memcached_return_t io_wait(memcached_instance_st* instance,
                                  const short events)
{
  /*
   ** We are going to block on write, but at least on Solaris we might block
   ** on write if we haven't read anything from our input buffer..
   ** Try to purge the input buffer if we don't do any flow control in the
   ** application layer (just sending a lot of data etc)
   ** The test is moved down in the purge function to avoid duplication of
   ** the test.
 */
  if (events & POLLOUT)
  {
    if (memcached_purge(instance) == false)
    {
      return MEMCACHED_FAILURE;
    }
  }

  struct pollfd fds;
  fds.fd= instance->fd;
  fds.events= events;
  fds.revents= 0;

  if (fds.events & POLLOUT) /* write */
  {
    instance->io_wait_count.write++;
  }
  else
  {
    instance->io_wait_count.read++;
  }

  if (instance->root->poll_timeout == 0) // Mimic 0 causes timeout behavior (not all platforms do this)
  {
    return memcached_set_error(*instance, MEMCACHED_TIMEOUT, MEMCACHED_AT, memcached_literal_param("poll_timeout() was set to zero"));
  }

  size_t loop_max= 5;
  while (--loop_max) // While loop is for ERESTART or EINTR
  {
    int active_fd= poll(&fds, 1, instance->root->poll_timeout);

    if (active_fd >= 1)
    {
      assert_msg(active_fd == 1 , "poll() returned an unexpected number of active file descriptors");
      if (fds.revents & POLLIN or fds.revents & POLLOUT)
      {
        return MEMCACHED_SUCCESS;
      }

      if (fds.revents & POLLHUP)
      {
        return memcached_set_error(*instance, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT,
                                   memcached_literal_param("poll() detected hang up"));
      }

      if (fds.revents & POLLERR)
      {
        int local_errno= EINVAL;
        int err;
        socklen_t len= sizeof (err);
        if (getsockopt(instance->fd, SOL_SOCKET, SO_ERROR, (char*)&err, &len) == 0)
        {
          if (err == 0) // treat this as EINTR
          {
            continue;
          }
          local_errno= err;
        }
        memcached_quit_server(instance, true);
        return memcached_set_errno(*instance, local_errno, MEMCACHED_AT,
                                   memcached_literal_param("poll() returned POLLHUP"));
      }

      return memcached_set_error(*instance, MEMCACHED_FAILURE, MEMCACHED_AT, memcached_literal_param("poll() returned a value that was not dealt with"));
    }

    if (active_fd == 0)
    {
      return memcached_set_error(*instance, MEMCACHED_TIMEOUT, MEMCACHED_AT, memcached_literal_param("No active_fd were found"));
    }

    // Only an error should result in this code being called.
    int local_errno= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
    assert_msg(active_fd == -1 , "poll() returned an unexpected value");
    switch (local_errno)
    {
#ifdef __linux
    case ERESTART:
#endif
    case EINTR:
      continue;

    case EFAULT:
    case ENOMEM:
      memcached_set_error(*instance, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT);

    case EINVAL:
      memcached_set_error(*instance, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT, memcached_literal_param("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid"));

    default:
      memcached_set_errno(*instance, local_errno, MEMCACHED_AT, memcached_literal_param("poll"));
    }

    break;
  }

  memcached_quit_server(instance, true);

  if (memcached_has_error(instance))
  {
    return memcached_instance_error_return(instance);
  }

  return memcached_set_error(*instance, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT,
                             memcached_literal_param("number of attempts to call io_wait() failed"));
}

static bool io_flush(memcached_instance_st* instance,
                     const bool with_flush,
                     memcached_return_t& error)
{
  /*
   ** We might want to purge the input buffer if we haven't consumed
   ** any output yet... The test for the limits is the purge is inline
   ** in the purge function to avoid duplicating the logic..
 */
  {
    WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);

    if (memcached_purge(instance) == false)
    {
      return false;
    }
  }
  char *local_write_ptr= instance->write_buffer;
  size_t write_length= instance->write_buffer_offset;

  error= MEMCACHED_SUCCESS;

  WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);

  /* Looking for memory overflows */
#if defined(DEBUG)
  if (write_length == MEMCACHED_MAX_BUFFER)
    WATCHPOINT_ASSERT(instance->write_buffer == local_write_ptr);
  WATCHPOINT_ASSERT((instance->write_buffer + MEMCACHED_MAX_BUFFER) >= (local_write_ptr + write_length));
#endif

  while (write_length)
  {
    WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);
    WATCHPOINT_ASSERT(write_length > 0);

    int flags;
    if (with_flush)
    {
      flags= MSG_NOSIGNAL;
    }
    else
    {
      flags= MSG_NOSIGNAL|MSG_MORE;
    }

    ssize_t sent_length= ::send(instance->fd, local_write_ptr, write_length, flags);
    int local_errno= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno

    if (sent_length == SOCKET_ERROR)
    {
#if 0 // @todo I should look at why we hit this bit of code hard frequently
      WATCHPOINT_ERRNO(get_socket_errno());
      WATCHPOINT_NUMBER(get_socket_errno());
#endif
      switch (get_socket_errno())
      {
      case ENOBUFS:
        continue;

#if EWOULDBLOCK != EAGAIN
      case EWOULDBLOCK:
#endif
      case EAGAIN:
        {
          /*
           * We may be blocked on write because the input buffer
           * is full. Let's check if we have room in our input
           * buffer for more data and retry the write before
           * waiting..
         */
          if (repack_input_buffer(instance) or process_input_buffer(instance))
          {
            continue;
          }

          memcached_return_t rc= io_wait(instance, POLLOUT);
          if (memcached_success(rc))
          {
            continue;
          }
          else if (rc == MEMCACHED_TIMEOUT)
          {
            return false;
          }

          memcached_quit_server(instance, true);
          error= memcached_set_errno(*instance, local_errno, MEMCACHED_AT);
          return false;
        }
      case ENOTCONN:
      case EPIPE:
      default:
        memcached_quit_server(instance, true);
        error= memcached_set_errno(*instance, local_errno, MEMCACHED_AT);
        WATCHPOINT_ASSERT(instance->fd == INVALID_SOCKET);
        return false;
      }
    }

    instance->io_bytes_sent+= uint32_t(sent_length);

    local_write_ptr+= sent_length;
    write_length-= uint32_t(sent_length);
  }

  WATCHPOINT_ASSERT(write_length == 0);
  instance->write_buffer_offset= 0;

  return true;
}

memcached_return_t memcached_io_wait_for_write(memcached_instance_st* instance)
{
  return io_wait(instance, POLLOUT);
}

memcached_return_t memcached_io_wait_for_read(memcached_instance_st* instance)
{
  return io_wait(instance, POLLIN);
}

static memcached_return_t _io_fill(memcached_instance_st* instance)
{
  ssize_t data_read;
  do
  {
    data_read= ::recv(instance->fd, instance->read_buffer, MEMCACHED_MAX_BUFFER, MSG_NOSIGNAL);
    int local_errno= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno

    if (data_read == SOCKET_ERROR)
    {
      switch (get_socket_errno())
      {
      case EINTR: // We just retry
        continue;

      case ETIMEDOUT: // OSX
#if EWOULDBLOCK != EAGAIN
      case EWOULDBLOCK:
#endif
      case EAGAIN:
#ifdef __linux
      case ERESTART:
#endif
        {
          memcached_return_t io_wait_ret;
          if (memcached_success(io_wait_ret= io_wait(instance, POLLIN)))
          {
            continue;
          }

          return io_wait_ret;
        }

        /* fall through */

      case ENOTCONN: // Programmer Error
        WATCHPOINT_ASSERT(0);
      case ENOTSOCK:
        WATCHPOINT_ASSERT(0);
      case EBADF:
        assert_msg(instance->fd != INVALID_SOCKET, "Programmer error, invalid socket");
      case EINVAL:
      case EFAULT:
      case ECONNREFUSED:
      default:
        memcached_quit_server(instance, true);
        memcached_set_errno(*instance, local_errno, MEMCACHED_AT);
        break;
      }

      return memcached_instance_error_return(instance);
    }
    else if (data_read == 0)
    {
      /*
        EOF. Any data received so far is incomplete
        so discard it. This always reads by byte in case of TCP
        and protocol enforcement happens at memcached_response()
        looking for '\n'. We do not care for UDB which requests 8 bytes
        at once. Generally, this means that connection went away. Since
        for blocking I/O we do not return 0 and for non-blocking case
        it will return EGAIN if data is not immediatly available.
      */
      memcached_quit_server(instance, true);
      return memcached_set_error(*instance, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT,
                                 memcached_literal_param("::rec() returned zero, server has disconnected"));
    }
    instance->io_wait_count._bytes_read+= data_read;
  } while (data_read <= 0);

  instance->io_bytes_sent= 0;
  instance->read_data_length= (size_t) data_read;
  instance->read_buffer_length= (size_t) data_read;
  instance->read_ptr= instance->read_buffer;

  return MEMCACHED_SUCCESS;
}

memcached_return_t memcached_io_read(memcached_instance_st* instance,
                                     void *buffer, size_t length, ssize_t& nread)
{
  assert(memcached_is_udp(instance->root) == false);
  assert_msg(instance, "Programmer error, memcached_io_read() recieved an invalid Instance"); // Programmer error
  char *buffer_ptr= static_cast<char *>(buffer);

  if (instance->fd == INVALID_SOCKET)
  {
#if 0
    assert_msg(int(instance->state) <= int(MEMCACHED_SERVER_STATE_ADDRINFO), "Programmer error, invalid socket state");
#endif
    return MEMCACHED_CONNECTION_FAILURE;
  }

  while (length)
  {
    if (instance->read_buffer_length == 0)
    {
      memcached_return_t io_fill_ret;
      if (memcached_fatal(io_fill_ret= _io_fill(instance)))
      {
        nread= -1;
        return io_fill_ret;
      }
    }

    if (length > 1)
    {
      size_t difference= (length > instance->read_buffer_length) ? instance->read_buffer_length : length;

      memcpy(buffer_ptr, instance->read_ptr, difference);
      length -= difference;
      instance->read_ptr+= difference;
      instance->read_buffer_length-= difference;
      buffer_ptr+= difference;
    }
    else
    {
      *buffer_ptr= *instance->read_ptr;
      instance->read_ptr++;
      instance->read_buffer_length--;
      buffer_ptr++;
      break;
    }
  }

  nread= ssize_t(buffer_ptr - (char*)buffer);

  return MEMCACHED_SUCCESS;
}

memcached_return_t memcached_io_slurp(memcached_instance_st* instance)
{
  assert_msg(instance, "Programmer error, invalid Instance");
  assert(memcached_is_udp(instance->root) == false);

  if (instance->fd == INVALID_SOCKET)
  {
    assert_msg(int(instance->state) <= int(MEMCACHED_SERVER_STATE_ADDRINFO), "Invalid socket state");
    return MEMCACHED_CONNECTION_FAILURE;
  }

  ssize_t data_read;
  char buffer[MEMCACHED_MAX_BUFFER];
  do
  {
    data_read= ::recv(instance->fd, instance->read_buffer, sizeof(buffer), MSG_NOSIGNAL);
    if (data_read == SOCKET_ERROR)
    {
      switch (get_socket_errno())
      {
      case EINTR: // We just retry
        continue;

      case ETIMEDOUT: // OSX
#if EWOULDBLOCK != EAGAIN
      case EWOULDBLOCK:
#endif
      case EAGAIN:
#ifdef __linux
      case ERESTART:
#endif
        if (memcached_success(io_wait(instance, POLLIN)))
        {
          continue;
        }
        return MEMCACHED_IN_PROGRESS;

        /* fall through */

      case ENOTCONN: // Programmer Error
        assert(0);
      case ENOTSOCK:
        assert(0);
      case EBADF:
        assert_msg(instance->fd != INVALID_SOCKET, "Invalid socket state");
      case EINVAL:
      case EFAULT:
      case ECONNREFUSED:
      default:
        return MEMCACHED_CONNECTION_FAILURE; // We want this!
      }
    }
  } while (data_read > 0);

  return MEMCACHED_CONNECTION_FAILURE;
}

static bool _io_write(memcached_instance_st* instance,
                      const void *buffer, size_t length, bool with_flush,
                      size_t& written)
{
  assert(instance->fd != INVALID_SOCKET);
  assert(memcached_is_udp(instance->root) == false);

  const char *buffer_ptr= static_cast<const char *>(buffer);

  const size_t original_length= length;

  while (length)
  {
    char *write_ptr;
    size_t buffer_end= MEMCACHED_MAX_BUFFER;
    size_t should_write= buffer_end -instance->write_buffer_offset;
    should_write= (should_write < length) ? should_write : length;

    write_ptr= instance->write_buffer + instance->write_buffer_offset;
    memcpy(write_ptr, buffer_ptr, should_write);
    instance->write_buffer_offset+= should_write;
    buffer_ptr+= should_write;
    length-= should_write;

    if (instance->write_buffer_offset == buffer_end)
    {
      WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);

      memcached_return_t rc;
      if (io_flush(instance, with_flush, rc) == false)
      {
        written= original_length -length;
        return false;
      }
    }
  }

  if (with_flush)
  {
    memcached_return_t rc;
    WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);
    if (io_flush(instance, with_flush, rc) == false)
    {
      written= original_length -length;
      return false;
    }
  }

  written= original_length -length;

  return true;
}

bool memcached_io_write(memcached_instance_st* instance)
{
  size_t written;
  return _io_write(instance, NULL, 0, true, written);
}

ssize_t memcached_io_write(memcached_instance_st* instance,
                           const void *buffer, const size_t length, const bool with_flush)
{
  size_t written;

  if (_io_write(instance, buffer, length, with_flush, written) == false)
  {
    return -1;
  }

  return ssize_t(written);
}

bool memcached_io_writev(memcached_instance_st* instance,
                         libmemcached_io_vector_st vector[],
                         const size_t number_of, const bool with_flush)
{
  ssize_t complete_total= 0;
  ssize_t total= 0;

  for (size_t x= 0; x < number_of; x++, vector++)
  {
    complete_total+= vector->length;
    if (vector->length)
    {
      size_t written;
      if ((_io_write(instance, vector->buffer, vector->length, false, written)) == false)
      {
        return false;
      }
      total+= written;
    }
  }

  if (with_flush)
  {
    if (memcached_io_write(instance) == false)
    {
      return false;
    }
  }

  return (complete_total == total);
}

void memcached_instance_st::start_close_socket()
{
  if (fd != INVALID_SOCKET)
  {
    shutdown(fd, SHUT_WR);
    options.is_shutting_down= true;
  }
}

void memcached_instance_st::reset_socket()
{
  if (fd != INVALID_SOCKET)
  {
    (void)closesocket(fd);
    fd= INVALID_SOCKET;
  }
}

void memcached_instance_st::close_socket()
{
  if (fd != INVALID_SOCKET)
  {
    int shutdown_options= SHUT_RD;
    if (options.is_shutting_down == false)
    {
      shutdown_options= SHUT_RDWR;
    }

    /* in case of death shutdown to avoid blocking at close() */
    if (shutdown(fd, shutdown_options) == SOCKET_ERROR and get_socket_errno() != ENOTCONN)
    {
      WATCHPOINT_NUMBER(fd);
      WATCHPOINT_ERRNO(get_socket_errno());
      WATCHPOINT_ASSERT(get_socket_errno());
    }

    reset_socket();
    state= MEMCACHED_SERVER_STATE_NEW;
  }

  state= MEMCACHED_SERVER_STATE_NEW;
  cursor_active_= 0;
  io_bytes_sent= 0;
  write_buffer_offset= size_t(root and memcached_is_udp(root) ? UDP_DATAGRAM_HEADER_LENGTH : 0);
  read_buffer_length= 0;
  read_ptr= read_buffer;
  options.is_shutting_down= false;
  memcached_server_response_reset(this);

  // We reset the version so that if we end up talking to a different server
  // we don't have stale server version information.
  major_version= minor_version= micro_version= UINT8_MAX;
}

memcached_instance_st* memcached_io_get_readable_server(Memcached *memc, memcached_return_t&)
{
#define MAX_SERVERS_TO_POLL 100
  struct pollfd fds[MAX_SERVERS_TO_POLL];
  nfds_t host_index= 0;

  for (uint32_t x= 0; x < memcached_server_count(memc) and host_index < MAX_SERVERS_TO_POLL; ++x)
  {
    memcached_instance_st* instance= memcached_instance_fetch(memc, x);

    if (instance->read_buffer_length > 0) /* I have data in the buffer */
    {
      return instance;
    }

    if (instance->response_count() > 0)
    {
      fds[host_index].events= POLLIN;
      fds[host_index].revents= 0;
      fds[host_index].fd= instance->fd;
      ++host_index;
    }
  }

  if (host_index < 2)
  {
    /* We have 0 or 1 server with pending events.. */
    for (uint32_t x= 0; x< memcached_server_count(memc); ++x)
    {
      memcached_instance_st* instance= memcached_instance_fetch(memc, x);

      if (instance->response_count() > 0)
      {
        return instance;
      }
    }

    return NULL;
  }

  int error= poll(fds, host_index, memc->poll_timeout);
  switch (error)
  {
  case -1:
    memcached_set_errno(*memc, get_socket_errno(), MEMCACHED_AT);
    /* FALLTHROUGH */
  case 0:
    break;

  default:
    for (nfds_t x= 0; x < host_index; ++x)
    {
      if (fds[x].revents & POLLIN)
      {
        for (uint32_t y= 0; y < memcached_server_count(memc); ++y)
        {
          memcached_instance_st* instance= memcached_instance_fetch(memc, y);

          if (instance->fd == fds[x].fd)
          {
            return instance;
          }
        }
      }
    }
  }

  return NULL;
}

/*
  Eventually we will just kill off the server with the problem.
*/
void memcached_io_reset(memcached_instance_st* instance)
{
  memcached_quit_server(instance, true);
}

/**
 * Read a given number of bytes from the server and place it into a specific
 * buffer. Reset the IO channel on this server if an error occurs.
 */
memcached_return_t memcached_safe_read(memcached_instance_st* instance,
                                       void *dta,
                                       const size_t size)
{
  size_t offset= 0;
  char *data= static_cast<char *>(dta);

  while (offset < size)
  {
    ssize_t nread;
    memcached_return_t rc;

    while (memcached_continue(rc= memcached_io_read(instance, data + offset, size - offset, nread))) { };

    if (memcached_failed(rc))
    {
      return rc;
    }

    offset+= size_t(nread);
  }

  return MEMCACHED_SUCCESS;
}

memcached_return_t memcached_io_readline(memcached_instance_st* instance,
                                         char *buffer_ptr,
                                         size_t size,
                                         size_t& total_nr)
{
  total_nr= 0;
  bool line_complete= false;

  while (line_complete == false)
  {
    if (instance->read_buffer_length == 0)
    {
      /*
       * We don't have any data in the buffer, so let's fill the read
       * buffer. Call the standard read function to avoid duplicating
       * the logic.
     */
      ssize_t nread;
      memcached_return_t rc= memcached_io_read(instance, buffer_ptr, 1, nread);
      if (memcached_failed(rc) and rc == MEMCACHED_IN_PROGRESS)
      {
        memcached_quit_server(instance, true);
        return memcached_set_error(*instance, rc, MEMCACHED_AT);
      }
      else if (memcached_failed(rc))
      {
        return rc;
      }

      if (*buffer_ptr == '\n')
      {
        line_complete= true;
      }

      ++buffer_ptr;
      ++total_nr;
    }

    /* Now let's look in the buffer and copy as we go! */
    while (instance->read_buffer_length and total_nr < size and line_complete == false)
    {
      *buffer_ptr = *instance->read_ptr;
      if (*buffer_ptr == '\n')
      {
        line_complete = true;
      }
      --instance->read_buffer_length;
      ++instance->read_ptr;
      ++total_nr;
      ++buffer_ptr;
    }

    if (total_nr == size)
    {
      return MEMCACHED_PROTOCOL_ERROR;
    }
  }

  return MEMCACHED_SUCCESS;
}


text:
require File.expand_path('../../spec_helper', __dir__)

module Selenium
  module WebDriver
    describe Interactions do
      describe '#key' do
        it 'creates a new key input with provided name' do
          device = Interactions.key(:name)

          expect(device).to be_a(Interactions::KeyInput)
          expect(device.name).to eq(:name)
        end

        it 'sets name to a random UUID if no name is provided' do
          allow(SecureRandom).to receive(:uuid).and_return(:id)

          device = Interactions.key

          expect(device).to be_a(Interactions::KeyInput)
          expect(device.name).to eq(:id)
        end
      end

      describe '#pointer' do
        it 'creates a new pointer input with a provided name' do
          device = Interactions.pointer(:mouse, name: :name)

          expect(device).to be_a(Interactions::PointerInput)
          expect(device.name).to eq(:name)
        end

        it 'sets name to a random UUID if no name is provided' do
          allow(SecureRandom).to receive(:uuid).and_return(:id)

          device = Interactions.pointer(:mouse)

          expect(device).to be_a(Interactions::PointerInput)
          expect(device.name).to eq(:id)
        end
      end

      describe '#none' do
        it 'creates a new pointer input with a provided name' do
          device = Interactions.none(:name)

          expect(device).to be_a(Interactions::NoneInput)
          expect(device.name).to eq(:name)
        end

        it 'sets name to a random UUID if no name is provided' do
          allow(SecureRandom).to receive(:uuid).and_return(:id)

          device = Interactions.none

          expect(device).to be_a(Interactions::NoneInput)
          expect(device.name).to eq(:id)
        end
      end
    end
  end # WebDriver
end # Selenium


text:
// Package
///////////////
package com.hp.hpl.jena.ontology;

// Imports
///////////////
import com.hp.hpl.jena.rdf.model.*;

/**
 *

 * Interface that encapsulates a class description formed by restricting one or
 * more properties to have constrained values and/or cardinalities.
 *

 *
 * @author Ian Dickinson, HP Labs
 *         (email)
 * @version CVS $Id: Restriction.java,v 1.2 2009/10/06 13:04:34 ian_dickinson Exp $
 */
public interface Restriction
    extends OntClass
{
    // Constants
    //////////////////////////////////

    // External signature methods
    //////////////////////////////////

    // onProperty

    /**
     *
Assert that the property that this restriction applies to is the given property. Any existing
     * statements for onProperty will be removed.

     * @param prop The property that this restriction applies to
     * @exception OntProfileException If the {@link Profile#ON_PROPERTY()} property is not supported in the current language profile.
     */
    public void setOnProperty( Property prop );

    /**
     *
Answer the property that this property restriction applies to. If there is
     * more than one such resource, an arbitrary selection is made (though well-defined property restrictions
     * should not have more than one onProperty statement.

     * @return The property that this property restriction applies to
     * @exception OntProfileException If the {@link Profile#ON_PROPERTY()} property is not supported in the current language profile.
     */
    public OntProperty getOnProperty();

    /**
     *
Answer true if this restriction is a property restriction on the given property.

     * @param prop A property to test against
     * @return True if this restriction is a restriction on prop
     * @exception OntProfileException If the {@link Profile#ON_PROPERTY()} property is not supported in the current language profile.
     */
    public boolean onProperty( Property prop );

    /**
     *
Remove the given property as the property that this restriction applies to.  If this statement
     * is not true of the current model, nothing happens.

     * @param prop The property to be removed as a the property that this restriction applies to
     */
    public void removeOnProperty( Property prop );

    // facets

    /**
     *
Answer a view of this restriction as an all values from  expression

     * @return This class, but viewed as an AllValuesFromRestriction node
     * @exception ConversionException if the class cannot be converted to an all values from restriction
     * given the lanuage profile and the current state of the underlying model.
     */
    public AllValuesFromRestriction asAllValuesFromRestriction();

    /**
     *
Answer a view of this restriction as a some values from  expression

     * @return This class, but viewed as a SomeValuesFromRestriction node
     * @exception ConversionException if the class cannot be converted to an all values from restriction
     * given the lanuage profile and the current state of the underlying model.
     */
    public SomeValuesFromRestriction asSomeValuesFromRestriction();

    /**
     *
Answer a view of this restriction as a has value expression

     * @return This class, but viewed as a HasValueRestriction node
     * @exception ConversionException if the class cannot be converted to a has value restriction
     * given the lanuage profile and the current state of the underlying model.
     */
    public HasValueRestriction asHasValueRestriction();

    /**
     *
Answer a view of this restriction as a cardinality restriction class expression

     * @return This class, but viewed as a CardinalityRestriction node
     * @exception ConversionException if the class cannot be converted to a cardinality restriction
     * given the lanuage profile and the current state of the underlying model.
     */
    public CardinalityRestriction asCardinalityRestriction();

    /**
     *
Answer a view of this restriction as a min cardinality restriction class expression

     * @return This class, but viewed as a MinCardinalityRestriction node
     * @exception ConversionException if the class cannot be converted to a min cardinality restriction
     * given the lanuage profile and the current state of the underlying model.
     */
    public MinCardinalityRestriction asMinCardinalityRestriction();

    /**
     *
Answer a view of this restriction as a max cardinality restriction class expression

     * @return This class, but viewed as a MaxCardinalityRestriction node
     * @exception ConversionException if the class cannot be converted to a max cardinality restriction
     * given the lanuage profile and the current state of the underlying model.
     */
    public MaxCardinalityRestriction asMaxCardinalityRestriction();

    // type tests

    /**
     *
Answer true if this restriction is an all values from restriction

     * @return True if this is an allValuesFrom property restriction
     * @exception ProfileException if {@link Profile#ALL_VALUES_FROM()} is not supported in the current profile
     */
    public boolean isAllValuesFromRestriction();

    /**
     *
Answer true if this restriction is a some values from restriction

     * @return True if this is a someValuesFrom property restriction
     * @exception ProfileException if {@link Profile#SOME_VALUES_FROM()} is not supported in the current profile
     */
    public boolean isSomeValuesFromRestriction();

    /**
     *
Answer true if this restriction is a has value restriction

     * @return True if this is a hasValue property restriction
     * @exception ProfileException if {@link Profile#HAS_VALUE()} is not supported in the current profile
     */
    public boolean isHasValueRestriction();

    /**
     *
Answer true if this restriction is a cardinality restriction (ie is a property restriction
     * constructed with an owl:cardinality operator, or similar). This is not a test for
     * a restriction that tests cardinalities in general.

     * @return True if this is a cardinality property restriction
     * @exception ProfileException if {@link Profile#CARDINALITY()} is not supported in the current profile
     */
    public boolean isCardinalityRestriction();

    /**
     *
Answer true if this restriction is a min cardinality restriction (ie is a property restriction
     * constructed with an owl:minCardinality operator, or similar). This is not a test for
     * a restriction that tests cardinalities in general.

     * @return True if this is a minCardinality property restriction
     * @exception ProfileException if {@link Profile#MIN_CARDINALITY()} is not supported in the current profile
     */
    public boolean isMinCardinalityRestriction();

    /**
     *
Answer true if this restriction is a max cardinality restriction (ie is a property restriction
     * constructed with an owl:maxCardinality operator, or similar). This is not a test for
     * a restriction that tests cardinalities in general.

     * @return True if this is a maxCardinality property restriction
     * @exception ProfileException if {@link Profile#MAX_CARDINALITY()} is not supported in the current profile
     */
    public boolean isMaxCardinalityRestriction();

    // conversions

    /**
     *
Convert this restriction to an all values from class expression.

     * @param cls The class to which all values of the restricted property must belong, to be in the
     * extension of this restriction
     * @return This class, but converted to a AllValuesFromRestriction class expression
     * @exception ProfileException if {@link Profile#ALL_VALUES_FROM()} is not supported in the current profile
     */
    public AllValuesFromRestriction convertToAllValuesFromRestriction( Resource cls );

    /**
     *
Convert this restriction to a some values from class expression

     * @param cls The class to which at least one value of the restricted property must belong, to be in the
     * extension of this restriction
     * @return This class, but converted to a SomeValuesFromRestriction node
     * @exception ProfileException if {@link Profile#SOME_VALUES_FROM()} is not supported in the current profile
     */
    public SomeValuesFromRestriction convertToSomeValuesFromRestriction( Resource cls );

    /**
     *
Convert this restriction to a has value class expression

     * @param value The value which the restricted property must have, for resource to be
     * in the extension of this restriction. Can be a resource or a literal.
     * @return This class, but converted to a HasValueRestriction
     * @exception ProfileException if {@link Profile#HAS_VALUE()} is not supported in the current profile
     */
    public HasValueRestriction convertToHasValueRestriction( RDFNode value );

    /**
     *
Convert this restriction to a cardinality restriction class expression

     * @param cardinality The exact cardinality for the restricted property
     * @return This class, but converted to a CardinalityRestriction node
     * @exception ProfileException if {@link Profile#CARDINALITY()} is not supported in the current profile
     */
    public CardinalityRestriction convertToCardinalityRestriction( int cardinality );

    /**
     *
Convert this restriction to a min cardinality restriction class expression

     * @param cardinality The minimum cardinality for the restricted property
     * @return This class, but converted to a MinCardinalityRestriction node
     * @exception ProfileException if {@link Profile#MIN_CARDINALITY()} is not supported in the current profile
     */
    public MinCardinalityRestriction convertToMinCardinalityRestriction( int cardinality );

    /**
     *
Convert this restriction to a max cardinality restriction class expression

     * @param cardinality The maximum cardinality for the restricted property
     * @return This class, but converted to a MaxCardinalityRestriction node
     * @exception ProfileException if {@link Profile#MAX_CARDINALITY()} is not supported in the current profile
     */
    public MaxCardinalityRestriction convertToMaxCardinalityRestriction( int cardinality );

}

/*
    (c) Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

    3. The name of the author may not be used to endorse or promote products
       derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


text:
import { spawn } from 'child_process'
import * as Path from 'path'
import * as WebpackMerge from 'webpack-merge'

import { root } from './config/helpers'

import {
	CustomCommonConfig,
	CustomDevConfig,
	CustomProdConfig
} from './config/custom'
import {
	DefaultCommonConfig,
	DefaultDevConfig,
	DefaultMainConfig,
	DefaultProdConfig
} from './config/default'
import { Externals } from './config/dll'

// env
const EVENT = process.env.npm_lifecycle_event
const ENV = process.env.NODE_ENV || 'development'

const port = process.env.PORT || 1212

// config
const EnvConfig = {
	isDev: ENV === 'development',
	isMain: EVENT.includes('main')
}

// common
const CommonConfig = () => {
	const config = {} as WebpackConfig

	config.module = {
		rules: [...DefaultCommonConfig().rules, ...CustomCommonConfig.rules]
	}

	config.plugins = [
		...DefaultCommonConfig().plugins,
		...CustomCommonConfig.plugins
	]

	config.externals = Externals

	config.node = {
		__dirname: false,
		__filename: false
	}

	return config
}

// dev
const DevConfig = () => {
	const config = {} as WebpackConfig

	config.devtool = 'source-map'

	config.mode = 'development'

	config.target = 'electron-renderer'

	config.externals = ['fsevents', 'crypto-browserify']

	config.module = {
		rules: [...DefaultDevConfig.rules, ...CustomDevConfig.rules]
		// noParse: [/remote-redux-devtools/]
	}

	config.plugins = [...DefaultDevConfig.plugins, ...CustomDevConfig.plugins]

	config.resolve = {
		cacheWithContext: false,
		modules: [root('src'), 'node_modules']
	}

	config.entry = {
		app: [
			'react-hot-loader/patch',
			`webpack-dev-server/client?http://localhost:${port}/`,
			'webpack/hot/only-dev-server',
			'./src/boot'
		]
	}

	config.output = {
		filename: 'app.bundle.js',
		path: root('app'),
		sourceMapFilename: '[file].map'
		// chunkFilename: '[id].chunk.js'
	}

	config.devServer = {
		compress: false,
		// stats: 'errors-only',
		contentBase: Path.join(__dirname, 'app'),
		headers: { 'Access-Control-Allow-Origin': '*' },
		historyApiFallback: {
			disableDotRule: false,
			verbose: true,
		},
		hot: true,
		inline: true,
		lazy: false,
		noInfo: false,
		port,
		publicPath: `http://localhost:${port}/`,
		watchOptions: {
			aggregateTimeout: 300,
			ignored: /node_modules/,
			poll: 100
		},
		before() {
			if (process.env.START_ELECTRON) {
				spawn('npm', ['run', 'electron:dev'], {
					env: process.env,
					shell: true,
					stdio: 'inherit'
				})
					.on('close', code => process.exit(code))
					.on('error', spawnError => console.error(spawnError))
			}
		}
	}

	return config
}

// prod
const ProdConfig = () => {
	const config: WebpackConfig = {}

	config.devtool = 'source-map'

	config.mode = 'production'

	config.module = {
		rules: [...DefaultProdConfig.rules, ...CustomProdConfig.rules]
	}

	config.performance = {
		hints: 'warning'
	}

	config.plugins = [...DefaultProdConfig.plugins, ...CustomProdConfig.plugins]

	config.resolve = {
		modules: [root('src'), 'node_modules']
	}

	config.entry = {
		app: './src/boot'
	}

	config.output = {
		chunkFilename: '[id].chunk.js',
		filename: '[name].bundle.js',
		path: root('app'),
		sourceMapFilename: '[file].map'
	}

	return config
}

// main
const MainConfig = () => {
	const config = {} as WebpackConfig

	config.devtool = 'source-map'

	config.mode = 'development'

	config.target = 'electron-main'

	config.entry = ['./main']

	config.module = {
		rules: [...DefaultMainConfig.rules]
	}

	config.plugins = [...DefaultMainConfig.plugins]

	config.output = {
		filename: 'main.bundle.js',
		path: root('app')
	}

	config.node = {
		__dirname: false,
		__filename: false
	}

	return config
}

// default
const DefaultConfig = () => {
	const config = {} as WebpackConfig

	config.resolve = {
		extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
		modules: [root('app'), 'node_modules'],
	}

	return config
}

// webpack
switch (ENV) {
	case 'prod':
	case 'production':
		module.exports = EnvConfig.isMain
			? WebpackMerge({}, DefaultConfig(), MainConfig())
			: WebpackMerge({}, DefaultConfig(), CommonConfig(), ProdConfig())
		break
	case 'dev':
	case 'development':
	default:
		module.exports = WebpackMerge(
			{},
			DefaultConfig(),
			CommonConfig(),
			DevConfig()
		)
}


text:
layout: post
title: Journal &#35 9
category: the-azule-journals
date: 2016-06-13
image:
  feature: journal-9-feature.png
headerImageStyle: "background-position: ;"
---
I got a little bit of work done early this morning. Around 1 o'clock we went out hiking. Some of the views out here are incredible. The mountains seem to go on forever. I have really never seen anything like it.

By the time we got back another resident had arrived. A writer in his very late 20's. He is working on his second novel while he is here. He gave me a copy of his first novel which I have read a little bit of. It is a very interesting idea.

Tomorrow I will sojourn on into Act Two.


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

<title>com.amazon.speech.speechlet.interfaces.system</title>
<meta name="date" content="2016-11-16">
<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 com.amazon.speech.speechlet.interfaces.system

Contains classes used by the System interface.

See: Description

Interface Summary

Interface
Description

System

The interface for interacting with system events, such as device exceptions.

Class Summary

Class
Description

Error

Represents information about an error in the System.ErrorOccurredRequest.

Error.Builder

Builder used to construct a new Error.

ErrorCause

The cause of an error.

ErrorCause.Builder

Builder used to construct a new SessionStartedRequest.

SystemInterface

Represents the presence of System capabilities of the Alexa client.

SystemInterface.Builder

Builder used to construct a new SystemInterface.

SystemState

SystemState.Builder

Builder used to construct a new SystemState.

Enum Summary

Enum
Description

ErrorType

Represents the types of errors permissible

 INVALID_RESPONSE
 The request was invalid.

Package com.amazon.speech.speechlet.interfaces.system Description

Contains classes used by the System interface.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
package com.facebook.buck.android;

import com.facebook.buck.cxx.CxxPlatformUtils;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.AbstractNodeBuilder;
import com.facebook.buck.rules.PathSourcePath;
import com.facebook.buck.rules.SourcePath;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;

import java.nio.file.Path;
import java.nio.file.Paths;

public class NdkLibraryBuilder extends AbstractNodeBuilder<NdkLibraryDescription.Arg> {

  private static final NdkCxxPlatform DEFAULT_NDK_PLATFORM =
      NdkCxxPlatform.builder()
          .setCxxPlatform(CxxPlatformUtils.DEFAULT_PLATFORM)
          .setCxxRuntime(NdkCxxPlatforms.CxxRuntime.GNUSTL)
          .setCxxSharedRuntimePath(Paths.get("runtime"))
          .build();

  private static final ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> NDK_PLATFORMS =
      ImmutableMap.<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform>builder()
          .put(NdkCxxPlatforms.TargetCpuType.ARM, DEFAULT_NDK_PLATFORM)
          .put(NdkCxxPlatforms.TargetCpuType.ARMV7, DEFAULT_NDK_PLATFORM)
          .put(NdkCxxPlatforms.TargetCpuType.X86, DEFAULT_NDK_PLATFORM)
          .build();

  public NdkLibraryBuilder(BuildTarget target) {
    super(
        new NdkLibraryDescription(Optional.<String>absent(), NDK_PLATFORMS) {
          @Override
          protected ImmutableSortedSet<SourcePath> findSources(
              ProjectFilesystem filesystem,
              Path buildRulePath) {
            return ImmutableSortedSet.<SourcePath>of(
                new PathSourcePath(filesystem, buildRulePath.resolve("Android.mk")));
          }
        },
        target);
  }

  public NdkLibraryBuilder addDep(BuildTarget target) {
    arg.deps = amend(arg.deps, target);
    return this;
  }

  public NdkLibraryBuilder setFlags(Iterable<String> flags) {
    arg.flags = Optional.of(ImmutableList.copyOf(flags));
    return this;
  }

  public NdkLibraryBuilder setIsAsset(boolean isAsset) {
    arg.isAsset = Optional.of(isAsset);
    return this;
  }

}


text:
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">

CatPhotoApp

Click here for cat photos.

Things cats love:

cat nip

laser pointers

lasagna

Top 3 things cats hate:

flea treatment

thunder

other cats

 <form action="/submit-cat-photo">
   <input type="radio" name="indoor-outdoor" checked> Indoor
   <input type="radio" name="indoor-outdoor"> Outdoor
   <input type="checkbox" name="personality" checked> Loving
   <input type="checkbox" name="personality"> Lazy
   <input type="checkbox" name="personality"> Energetic
   <input type="text" placeholder="cat photo URL" required>
   <button type="submit">Submit</button>
 </form>


text:
		Заказать обратный звонок менеджеру DОМУС

	<form class="cta_form" method="post" action="{% url 'applications:callback' %}">
		{% csrf_token %}
		{{ callback_form.non_field_errors }}

			{{ callback_form.name.errors }}
			{{ callback_form.name.label_tag }}
			{{ callback_form.name }}

			{{ callback_form.phone_number.errors }}
			{{ callback_form.phone_number.label_tag }}
			{{ callback_form.phone_number }}

		<input id="{{ callback_form.extra_info.id_for_label }}" name="{{ callback_form.extra_info.name }}" type="hidden" value="{{ callback_form.extra_info.value }}" />

			<button type="submit" class="btn_large">Заказать</button>

	</form>

		Нажимая на кнопку, вы даете согласие на обработку своих персональных данных DОМУС

Пользовательское соглашение DОМУС


text:
package org.grobid.trainer.evaluation;

import org.chasen.crfpp.Tagger;
import org.grobid.core.exceptions.GrobidException;
import org.grobid.core.utilities.TextUtilities;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 * Evaluation of the parsing of citation.
 *
 * @author Patrice Lopez
 */
public class EvaluationUtilities {
	/**
	 * Method for running a CRF tagger for evaluation purpose (i.e. with
	 * expected and actual labels).
	 *
	 * @param ress
	 *            list
	 * @param tagger
	 *            a tagger
	 * @return a report
	 */
	public static String taggerRun(ArrayList<String> ress, Tagger tagger) {
		// clear internal context
		tagger.clear();
		StringBuilder res = new StringBuilder();

		// we have to re-inject the pre-tags because they are removed by the JNI
		// parse method
		ArrayList<String> pretags = new ArrayList<String>();
		// add context
		for (String piece : ress) {
			if (piece.trim().length() == 0) {
				// parse and change internal stated as 'parsed'
				if (!tagger.parse()) {
					// throw an exception
					throw new RuntimeException("CRF++ parsing failed.");
				}

				for (int i = 0; i < tagger.size(); i++) {
					for (int j = 0; j < tagger.xsize(); j++) {
						res.append(tagger.x(i, j)).append("\t");
					}
					res.append(pretags.get(i)).append("\t");
					res.append(tagger.y2(i));
					res.append("\n");
				}
				res.append(" \n");
				// clear internal context
				tagger.clear();
				pretags = new ArrayList<String>();
			} else {
				tagger.add(piece);
				tagger.add("\n");
				// get last tag
				StringTokenizer tokenizer = new StringTokenizer(piece, " \t");
				while (tokenizer.hasMoreTokens()) {
					String toke = tokenizer.nextToken();
					if (!tokenizer.hasMoreTokens()) {
						pretags.add(toke);
					}
				}
			}
		}

		// parse and change internal stated as 'parsed'
		if (!tagger.parse()) {
			// throw an exception
			throw new RuntimeException("CRF++ parsing failed.");
		}

		for (int i = 0; i < tagger.size(); i++) {
			for (int j = 0; j < tagger.xsize(); j++) {
				res.append(tagger.x(i, j)).append("\t");
			}
			res.append(pretags.get(i)).append("\t");
			res.append(tagger.y2(i));
			res.append("\n");
		}
		res.append("\n");

		return res.toString();
	}

	public static String evaluateStandard(String path, Tagger tagger) {
		StringBuilder report = new StringBuilder();

		// word level
		final ArrayList<String> labels = new ArrayList<String>();
		// true positive
		final ArrayList<Integer> counterObserved = new ArrayList<Integer>();
		// all expected
		final ArrayList<Integer> counterExpected = new ArrayList<Integer>();
		// false positive
		final ArrayList<Integer> counterFalsePositive = new ArrayList<Integer>();
		// false negative
		final ArrayList<Integer> counterFalseNegative = new ArrayList<Integer>();

		// field level
		final ArrayList<String> labels2 = new ArrayList<String>();
		// true positive
		final ArrayList<Integer> counterObserved2 = new ArrayList<Integer>();
		// all expected
		final ArrayList<Integer> counterExpected2 = new ArrayList<Integer>();
		// false positive
		final ArrayList<Integer> counterFalsePositive2 = new ArrayList<Integer>();
		// false negative
		final ArrayList<Integer> counterFalseNegative2 = new ArrayList<Integer>();
//path = "/Users/lopez/biblio/epo/Modeles_03-2014/model.headers.80-20%-03-2014.test";
//path = "/Users/lopez/grobid/grobid-home/tmp/header1020940668466715808.test";
		try {
			final BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));

			String line;
			ArrayList<String> citationBlocks = new ArrayList<String>();
			while ((line = bufReader.readLine()) != null) {
				citationBlocks.add(line);
			}
			bufReader.close();

			String theResult = EvaluationUtilities.taggerRun(citationBlocks, tagger);
			StringTokenizer stt = new StringTokenizer(theResult, "\n");
			while (stt.hasMoreTokens()) {
				line = stt.nextToken();

				if (line.trim().length() == 0)
					continue;
				// the two last tokens, separated by a tabulation, gives the
				// expected label and, last, the resulting label
				StringTokenizer st = new StringTokenizer(line, "\t");
				String currentToken = null;
				String previousToken = null;
				while (st.hasMoreTokens()) {
					currentToken = st.nextToken();
					if (currentToken != null) {
						if (currentToken.startsWith("I-") || currentToken.startsWith("E-")) {
							currentToken = currentToken.substring(2, currentToken.length());
						}
					}
					if (st.hasMoreTokens()) {
						previousToken = currentToken;
					}
				}

				// System.out.println(previousToken + " / " + currentToken);

				if ((previousToken == null) || (currentToken == null)) {
					continue;
				}
				// previousToken : expected
				// currentToken : obtained
				int ind = labels.indexOf(previousToken);
				if (ind != -1) {
					if (previousToken.equals(currentToken)) {
						Integer count = counterObserved.get(ind);
						counterObserved.set(ind, count + 1);
					} else {
						int ind2 = labels.indexOf(currentToken);

						if (ind2 != -1) {
							Integer count = counterFalsePositive.get(ind2);
							counterFalsePositive.set(ind2, count + 1);
						} else {
							labels.add(currentToken);
							counterFalsePositive.add(1);
							counterObserved.add(0);
							counterExpected.add(0);
							counterFalseNegative.add(0);
						}

						Integer count2 = counterFalseNegative.get(ind);
						counterFalseNegative.set(ind, count2 + 1);
					}
					Integer count = counterExpected.get(ind);
					counterExpected.set(ind, count + 1);
				} else {
					labels.add(previousToken);

					if (previousToken.equals(currentToken)) {
						counterObserved.add(1); // true positives
						counterFalsePositive.add(0);
						counterFalseNegative.add(0);
					} else {
						counterObserved.add(0);
						counterFalsePositive.add(0);
						counterFalseNegative.add(1);

						int ind2 = labels.indexOf(currentToken);
						if (ind2 != -1) {
							Integer count = counterFalsePositive.get(ind2);
							Integer newCount = count + 1;
							counterFalsePositive.set(ind2, newCount);
						} else {
							labels.add(currentToken);
							counterFalsePositive.add(1);
							counterObserved.add(0);
							counterExpected.add(0);
							counterFalseNegative.add(0);
						}
					}

					counterExpected.add(1);
				}
			}

			bufReader.close();
			// print report
			int i = 0;

			// word
			report.append("\n===== Token-level results =====\n\n");

			int cumulated_tp = 0;
			int cumulated_fp = 0;
			int cumulated_tn = 0;
			int cumulated_fn = 0;
			// int cumulated_all = 0;
			double cumulated_f0 = 0.0;
			double cumulated_accuracy = 0.0;
			double cumulated_precision = 0.0;
			double cumulated_recall = 0.0;
			int totalValidFields = 0; // in case a class should not be
										// considered in the training set
			// because there is no expected class instance
			int totalTokens = 0;

			while (i < labels.size()) {
				totalTokens += counterExpected.get(i);
				i++;
			}

			System.out.println("total: " + totalTokens);

			// report for absolute values for each token type
			i = 0;
			while (i < labels.size()) {
				String label = labels.get(i);
				report.append(label);
				if (label.length() < 12)
					report.append("\t");

				int tp = counterObserved.get(i); // true positives
				int fp = counterFalsePositive.get(i); // false positves
				int fn = counterFalseNegative.get(i); // false negative
				int tn = totalTokens - tp - (fp + fn); // true negatives
				int all = counterExpected.get(i); // all expected

				report.append(label).append(" (token): " + "true positives: ").append(tp).append("\n\t\tfalse positives:").append(fp)
						.append("\n\t\ttrue negatives: ").append(tn).append("\n\t\tfalse negatives: ").append(fn).append("\n");
				report.append("\t\tall expected: ").append(all).append("\n\n");
				i++;
			}

			report.append("label\t\taccuracy\tprecision\trecall\t\tf1\n\n");

			// report for precision, recall, etc.
			i = 0;
			while (i < labels.size()) {
				String label = labels.get(i);
				report.append(label);
				if (label.length() < 12)
					report.append("\t");

				int tp = counterObserved.get(i); // true positives
				int fp = counterFalsePositive.get(i); // false positves
				int fn = counterFalseNegative.get(i); // false negative
				int tn = totalTokens - tp - (fp + fn); // true negatives
				int all = counterExpected.get(i); // all expected

				if (all != 0) {
					totalValidFields++;
				}

				double accuracy = (double) (tp + tn) / (tp + fp + tn + fn);
				report.append("\t").append(TextUtilities.formatTwoDecimals(accuracy * 100));

				double precision = 0.0;
				if (tp + fp != 0.0) {
					precision = (double) (tp) / (tp + fp);
				}
				report.append("\t\t").append(TextUtilities.formatTwoDecimals(precision * 100));

				double recall = 0.0;
				if (tp + fn != 0) {
					recall = (double) (tp) / (tp + fn);
				}
				report.append("\t\t").append(TextUtilities.formatTwoDecimals(recall * 100));

				double f0 = 0.0;
				if (precision + recall != 0) {
					f0 = (2 * precision * recall) / (precision + recall);
				}
				report.append("\t\t").append(TextUtilities.formatTwoDecimals(f0 * 100));

				report.append("\n");

				cumulated_tp += tp;
				cumulated_fp += fp;
				cumulated_tn += tn;
				cumulated_fn += fn;
				if (all != 0) {
					// cumulated_all += all;
					cumulated_f0 += f0;
					cumulated_accuracy += accuracy;
					cumulated_precision += precision;
					cumulated_recall += recall;
				}

				i++;
			}
			report.append("\n");
			report.append("all labels\t");

			// micro average measure
			double accuracy = (double) (cumulated_tp + cumulated_tn) / (cumulated_tp + cumulated_fp + cumulated_tn + cumulated_fn);
			report.append("\t").append(TextUtilities.formatTwoDecimals(accuracy * 100));

			double precision = (double) cumulated_tp / (cumulated_tp + cumulated_fp);
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(precision * 100));

			double recall = (double) cumulated_tp / (cumulated_tp + cumulated_fn);
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(recall * 100));

			double f0 = (2 * precision * recall) / (precision + recall);
			// double f0 = cumulated_f0 / labels.size();
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(f0 * 100));
			report.append("\t(micro average)");
			report.append("\n");

			// macro average measure
			report.append("\t\t");
			accuracy = cumulated_accuracy / (totalValidFields);
			report.append("\t").append(TextUtilities.formatTwoDecimals(accuracy * 100));

			precision = totalValidFields / cumulated_precision;
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(precision * 100));

			recall = cumulated_recall / totalValidFields;
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(recall * 100));

			f0 = cumulated_f0 / totalValidFields;
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(f0 * 100));

			report.append("\t(macro average)");
			report.append("\n");

			// field: a field is simply a sequence of word...
			// we do a second pass...
			boolean allGood = true;
			String lastPreviousToken = null;
			String lastCurrentToken = null;
			stt = new StringTokenizer(theResult, "\n");

			while (stt.hasMoreTokens()) {
				line = stt.nextToken();
				if ((line.trim().length() == 0) && (lastPreviousToken != null) && (lastCurrentToken != null)) {
					// end of last field
					int index = labels2.indexOf(lastPreviousToken);
					if (index == -1) {
						labels2.add(lastPreviousToken);
						// init
						counterObserved2.add(0);
						counterExpected2.add(0);
						counterFalsePositive2.add(0);
						counterFalseNegative2.add(0);
						index = labels2.indexOf(lastPreviousToken);
					}

					if (allGood) {
						Integer val = counterObserved2.get(index);
						counterObserved2.set(index, val + 1); // true positive
					} else {
						Integer val = counterFalseNegative2.get(index);
						counterFalseNegative2.set(index, val + 1);
					}
					Integer val = counterExpected2.get(index);
					counterExpected2.set(index, val + 1); // all expected

					index = labels2.indexOf(lastCurrentToken);
					if (index == -1) {
						labels2.add(lastCurrentToken);
						// init
						counterObserved2.add(0);
						counterExpected2.add(0);
						counterFalsePositive2.add(0);
						counterFalseNegative2.add(0);
						index = labels2.indexOf(lastCurrentToken);
					}
					if (!allGood) {
						val = counterFalsePositive2.get(index);
						counterFalsePositive2.set(index, val + 1);
						// erroneous observed field (false positive)
					}
					allGood = true;

					lastPreviousToken = null;
					lastCurrentToken = null;

					continue;
				}
				// the two last tokens, separated by a tabulation, gives the
				// expected label and, last,
				// the resulting label
				StringTokenizer st = new StringTokenizer(line, "\t");
				String currentToken = null;
				String previousToken = null;
				while (st.hasMoreTokens()) {
					currentToken = st.nextToken();
					if (currentToken != null) {
						if (currentToken.startsWith("I-") || currentToken.startsWith("E-")) {
							currentToken = currentToken.substring(2, currentToken.length());
						}
					}
					if (st.hasMoreTokens()) {
						previousToken = currentToken;
					}
				}

				if ((previousToken == null) || (currentToken == null)) {
					lastPreviousToken = null;
					lastCurrentToken = null;
					continue;
				}
				if ((lastPreviousToken != null) && (!previousToken.equals(lastPreviousToken))) {
					// new field
					if (!labels2.contains(lastPreviousToken)) {
						labels2.add(lastPreviousToken);
						// init
						counterObserved2.add(0);
						counterExpected2.add(0);
						counterFalsePositive2.add(0);
						counterFalseNegative2.add(0);
					}
					int index = labels2.indexOf(lastPreviousToken);
					if (allGood) {
						Integer val = counterObserved2.get(index);
						counterObserved2.set(index, val + 1); // true positive
					} else {
						Integer val = counterFalseNegative2.get(index);
						counterFalseNegative2.set(index, val + 1);
					}
					Integer val = counterExpected2.get(index);
					counterExpected2.set(index, val + 1); // all expected
				}

				if ((lastCurrentToken != null) && (!currentToken.equals(lastCurrentToken))) {
					// new field
					if (!labels2.contains(lastCurrentToken)) {
						labels2.add(lastCurrentToken);
						// init
						counterObserved2.add(0);
						counterExpected2.add(0);
						counterFalsePositive2.add(0);
						counterFalseNegative2.add(0);
					}
					int index = labels2.indexOf(lastCurrentToken);
					if (!allGood) {
						Integer val = counterFalsePositive2.get(index);
						counterFalsePositive2.set(index, val + 1);
						// erroneous observed field (false positive)
					}
				}

				if (((lastPreviousToken != null) && (!previousToken.equals(lastPreviousToken)))
						|| ((lastCurrentToken != null) && (!currentToken.equals(lastCurrentToken)))) {
					allGood = true;
				}

				if (!currentToken.equals(previousToken)) {
					allGood = false;
				}

				lastPreviousToken = previousToken;
				lastCurrentToken = currentToken;
			}

			report.append("\n===== Field-level results =====\n");
			report.append("\nlabel\t\taccuracy\tprecision\trecall\t\tf1\n\n");

			cumulated_tp = 0;
			cumulated_fp = 0;
			cumulated_tn = 0;
			cumulated_fn = 0;
			cumulated_f0 = 0.0;
			// cumulated_all = 0;
			cumulated_accuracy = 0.0;
			cumulated_precision = 0.0;
			cumulated_recall = 0.0;
			totalValidFields = 0;

			int totalFields = 0;
			i = 0;
			while (i < labels2.size()) {
				totalFields += counterExpected2.get(i);
				i++;
			}

			i = 0;
			while (i < labels2.size()) {
				totalFields += counterFalsePositive2.get(i);
				i++;
			}

			i = 0;
			while (i < labels2.size()) {
				String label = labels2.get(i);
				if (label.equals("<other>")) {
					i++;
					continue;
				}

				report.append(label);

				if (label.length() < 12) {
					report.append("\t");
				}
				int tp = counterObserved2.get(i); // true positives
				int fp = counterFalsePositive2.get(i); // false positives
				int fn = counterFalseNegative2.get(i); // false negative
				int tn = totalFields - tp - (fp + fn); // true negatives
				int all = counterExpected2.get(i); // all expected

				if (all != 0) {
					totalValidFields++;
				}

				accuracy = (double) (tp + tn) / (tp + fp + tn + fn);
				report.append("\t").append(TextUtilities.formatTwoDecimals(accuracy * 100));

				// report.append("\t"+ "-");

				// precision = (double) (tp) / (tp + fp);
				if ((tp + fp) == 0) {
					precision = 0.0;
				} else {
					precision = (double) (tp) / (tp + fp);
				}
				report.append("\t\t").append(TextUtilities.formatTwoDecimals(precision * 100));

				// recall = 0.0;
				if ((tp == 0) || (all == 0)) {
					recall = 0.0;
				} else {
					recall = (double) (tp) / all;
				}
				report.append("\t\t").append(TextUtilities.formatTwoDecimals(recall * 100));

				// f0 = 0.0;
				if (precision + recall == 0) {
					f0 = 0.0;
				} else {
					f0 = (2 * precision * recall) / (precision + recall);
				}
				report.append("\t\t").append(TextUtilities.formatTwoDecimals(f0 * 100));

				report.append("\n");

				cumulated_tp += tp;
				cumulated_fp += fp;
				cumulated_tn += tn;
				cumulated_fn += fn;
				if (all != 0) {
					// cumulated_all += all;
					cumulated_f0 += f0;
					cumulated_accuracy += accuracy;
					cumulated_precision += precision;
					cumulated_recall += recall;
				}
				i++;
			}

			report.append("\n");
			report.append("all fields\t");

			// micro average over measures
			accuracy = (double) (cumulated_tp + cumulated_tn) / (cumulated_tp + cumulated_fp + cumulated_tn + cumulated_fn);
			report.append("\t").append(TextUtilities.formatTwoDecimals(accuracy * 100));

			precision = (double) cumulated_tp / (cumulated_tp + cumulated_fp);
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(precision * 100));

			recall = (double) cumulated_tp / (cumulated_tp + cumulated_fn);
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(recall * 100));

			f0 = (2 * precision * recall) / (precision + recall);
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(f0 * 100));
			report.append("\t(micro average)");
			report.append("\n");

			// macro average over measures
			report.append("\t\t");
			accuracy = cumulated_accuracy / (totalValidFields);
			report.append("\t").append(TextUtilities.formatTwoDecimals(accuracy * 100));

			precision = cumulated_precision / totalValidFields;
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(precision * 100));

			recall = cumulated_recall / totalValidFields;
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(recall * 100));

			f0 = cumulated_f0 / totalValidFields;
			report.append("\t\t").append(TextUtilities.formatTwoDecimals(f0 * 100));

			report.append("\t(macro average)");
			report.append("\n");

			// instance: separated by a new line in the result file
			theResult = theResult.replace("\n \n", "\n\n");
			stt = new StringTokenizer(theResult, "\n\n");
			allGood = true;
			int correctInstance = 0;
			int totalInstance = 0;
			while (stt.hasMoreTokens()) {
				line = stt.nextToken();
				if ((line.trim().length() == 0) || (!stt.hasMoreTokens())) {
					totalInstance++;
					if (allGood) {
						correctInstance++;
					}
					allGood = true;
				} else {
					StringTokenizer st = new StringTokenizer(line, "\t");
					String currentToken = null;
					String previousToken = null;
					while (st.hasMoreTokens()) {
						currentToken = st.nextToken();
						if (currentToken != null) {
							if (currentToken.startsWith("I-") || currentToken.startsWith("E-")) {
								currentToken = currentToken.substring(2, currentToken.length());
							}
						}
						if (st.hasMoreTokens()) {
							previousToken = currentToken;
						}
					}

					if (!currentToken.equals(previousToken)) {
						allGood = false;
					}

				}

			}

			report.append("\n===== Instance-level results =====\n\n");
			report.append("Total expected instances: \t\t").append(totalInstance).append("\n");
			report.append("Correct instances: \t\t").append(correctInstance).append("\n");
			accuracy = (double) correctInstance / (totalInstance);
			report.append("Instance-level recall:\t").append(TextUtilities.formatTwoDecimals(accuracy * 100)).append("\n\n");

		} catch (Exception e) {
			throw new GrobidException("An exception occurred while evaluating Grobid.", e);
		}

		return report.toString();
	}
}


text:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>GroupDocs.Conversion for Java Spring</title>
    <base href="/"/>

    <meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<client-root></client-root>
<script th:src="@{'/angular/conversion/runtime-es2015.js'}" type="module"></script>
<script th:src="@{'/angular/conversion/polyfills-es2015.js'}" type="module"></script>
<script th:src="@{'/angular/conversion/runtime-es5.js'}" nomodule></script>
<script th:src="@{'/angular/conversion/polyfills-es5.js'}" nomodule></script>
<script th:src="@{'/angular/conversion/styles-es2015.js'}" type="module"></script>
<script th:src="@{'/angular/conversion/styles-es5.js'}" nomodule></script>
<script th:src="@{'/angular/conversion/vendor-es2015.js'}" type="module"></script>
<script th:src="@{'/angular/conversion/main-es2015.js'}" type="module"></script>
<script th:src="@{'/angular/conversion/vendor-es5.js'}" nomodule></script>
<script th:src="@{'/angular/conversion/main-es5.js'}" nomodule></script>
</body>
</html>


text:
export class GridAction {
  public description: string;
  public action: (row: any) => void;
}


text:
#include <aws/robomaker/model/WorldConfig.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace RoboMaker
{
namespace Model
{

WorldConfig::WorldConfig() :
    m_worldHasBeenSet(false)
{
}

WorldConfig::WorldConfig(JsonView jsonValue) :
    m_worldHasBeenSet(false)
{
  *this = jsonValue;
}

WorldConfig& WorldConfig::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("world"))
  {
    m_world = jsonValue.GetString("world");

    m_worldHasBeenSet = true;
  }

  return *this;
}

JsonValue WorldConfig::Jsonize() const
{
  JsonValue payload;

  if(m_worldHasBeenSet)
  {
   payload.WithString("world", m_world);

  }

  return payload;
}

} // namespace Model
} // namespace RoboMaker
} // namespace Aws


text:
<?php

// Configure the sender/receiver of the emails.
$FROM_ADDRESS = "";
$TO_ADDRESS = "";

if(!$TO_ADDRESS || !$FROM_ADDRESS) {
    die("Email configuration required.");
}

// 3 = full display with link names and progress
// 2 = only display current link index
// 1 = only display errors
// 0 = no output
$VERBOSITY = 2;

// Connection
$con=mysqli_connect("localhost","username","password","database");

if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
}

// Get all links
$result = mysqli_query($con,"SELECT * FROM links");

$numRows = mysqli_num_rows($result);

$i = 0;

while($row = mysqli_fetch_array($result))
{

    if ($VERBOSITY > 1)
        print("Checking id:" . $row['id'] . "
\n");

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $row['url']);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    $headers = curl_getinfo($ch);
    curl_close($ch);
    if ($VEROSITY > 2)
        print("HTTP response code:" . $headers['http_code']);

    if (!(($headers['http_code'] == '200') || ($headers['http_code'] == '302'))) {
        if ($VERBOSITY > 0)
            print("ERROR: id ". $row['id'] . " url: " . $row['url'] . " not found
\n");

        $to = $TO_ADDRESS;
        $subject = "my.harvard.edu link error";
        $message = "link id: " . $row['id'] . "url: " . $row['url'] . " does not work.";
        $from = $FROM_ADDRESS;
        $headers = "From:" . $from;
        mail($to,$subject,$message,$headers);
    }

    set_time_limit(0);

    if ($VERBOSITY > 0)
        print("
");

}

mysqli_close($con);
?>