text:
package com.microsoft.azure.storage.blob;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import junit.framework.TestCase;

import com.microsoft.azure.storage.AccessCondition;
import com.microsoft.azure.storage.Constants;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.ResponseReceivedEvent;
import com.microsoft.azure.storage.StorageEvent;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.core.SR;

/**
 * Blob Output Stream Tests
 */
public class BlobOutputStreamTests extends TestCase {

    protected CloudBlobContainer container;

    @Override
    public void setUp() throws URISyntaxException, StorageException {
        this.container = BlobTestHelper.getRandomContainerReference();
        this.container.create();
    }

    @Override
    public void tearDown() throws StorageException {
        this.container.deleteIfExists();
    }

    public void testEmpty() throws URISyntaxException, StorageException, IOException {
        String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("testblob");

        CloudBlockBlob blockBlob = this.container.getBlockBlobReference(blobName);
        BlobOutputStream str = blockBlob.openOutputStream();
        str.close();

        CloudBlockBlob blockBlob2 = this.container.getBlockBlobReference(blobName);
        blockBlob2.downloadAttributes();
        assertEquals(0, blockBlob2.getProperties().getLength());

        ArrayList<BlockEntry> blocks = blockBlob2.downloadBlockList(BlockListingFilter.ALL, null, null, null);
        assertEquals(0, blocks.size());
    }

    public void testClose() throws URISyntaxException, StorageException, IOException {
        String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("testblob");

        CloudBlockBlob blockBlob = this.container.getBlockBlobReference(blobName);
        BlobOutputStream str = blockBlob.openOutputStream();
        str.close();

        try {
            str.close();
            fail("Can't close twice.");
        } catch(IOException e) {
            assertEquals(SR.STREAM_CLOSED, e.getMessage());
        }

        str = blockBlob.openOutputStream();
        str.write(8);
        ArrayList<BlockEntry> blocks = blockBlob.downloadBlockList(BlockListingFilter.ALL, null, null, null);
        assertEquals(0, blocks.size());

        str.close();
        blocks = blockBlob.downloadBlockList(BlockListingFilter.COMMITTED, null, null, null);
        assertEquals(1, blocks.size());
    }

    public void testWithAccessCondition() throws URISyntaxException, StorageException, IOException {
        int blobLengthToUse = 8 * 512;
        byte[] buffer = BlobTestHelper.getRandomBuffer(blobLengthToUse);
        String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("testblob");
        AccessCondition accessCondition = AccessCondition.generateIfNotModifiedSinceCondition(new Date());

        CloudBlockBlob blockBlob = this.container.getBlockBlobReference(blobName);
        BlobOutputStream blobOutputStream = blockBlob.openOutputStream(accessCondition, null, null);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
        blobOutputStream.write(inputStream, 512);

        inputStream = new ByteArrayInputStream(buffer, 512, 3 * 512);
        blobOutputStream.write(inputStream, 3 * 512);

        blobOutputStream.close();

        byte[] result = new byte[blobLengthToUse];
        blockBlob.downloadToByteArray(result, 0);

        int i = 0;
        for (; i < 4 * 512; i++) {
            assertEquals(buffer[i], result[i]);
        }

        for (; i < 8 * 512; i++) {
            assertEquals(0, result[i]);
        }
    }

    public void testWriteStream() throws URISyntaxException, StorageException, IOException {
        int blobLengthToUse = 8 * 512;
        byte[] buffer = BlobTestHelper.getRandomBuffer(blobLengthToUse);
        String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("testblob");

        CloudBlockBlob blockBlob = this.container.getBlockBlobReference(blobName);
        BlobOutputStream blobOutputStream = blockBlob.openOutputStream();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
        blobOutputStream.write(inputStream, 512);

        inputStream = new ByteArrayInputStream(buffer, 512, 3 * 512);
        blobOutputStream.write(inputStream, 3 * 512);

        blobOutputStream.close();

        byte[] result = new byte[blobLengthToUse];
        blockBlob.downloadToByteArray(result, 0);

        int i = 0;
        for (; i < 4 * 512; i++) {
            assertEquals(buffer[i], result[i]);
        }

        for (; i < 8 * 512; i++) {
            assertEquals(0, result[i]);
        }
    }

    public void testFlush() throws Exception {
        CloudBlockBlob blockBlob = this.container.getBlockBlobReference(
                BlobTestHelper.generateRandomBlobNameWithPrefix("flush"));

        OperationContext ctx = new OperationContext();
        ctx.getResponseReceivedEventHandler().addListener(new StorageEvent<ResponseReceivedEvent>() {

            @Override
            public void eventOccurred(ResponseReceivedEvent eventArg) {
                try {
                    HttpURLConnection con = (HttpURLConnection) eventArg.getConnectionObject();
                    if ("511".equals(con.getRequestProperty(Constants.HeaderConstants.CONTENT_LENGTH))) {
                        Thread.sleep(3000);
                    }
                } catch (InterruptedException e) {
                    // do nothing
                }
            }
        });

        BlobOutputStream blobOutputStream = blockBlob.openOutputStream(null, null, ctx);

        ExecutorService threadExecutor = Executors.newFixedThreadPool(1);

        byte[] buffer = BlobTestHelper.getRandomBuffer(511);
        blobOutputStream.write(buffer);

        Future<Void> future = threadExecutor.submit(new FlushTask(blobOutputStream));
        Thread.sleep(1000);

        buffer = BlobTestHelper.getRandomBuffer(513);
        blobOutputStream.write(buffer);

        // Writes complete when the upload is dispatched (not when the upload completes and flush must
        // wait for upload1 to complete. So, flush should finish last and writes should finish in order.
        while(!future.isDone()) {
            Thread.sleep(500);
        }

        // After flush we should see the first upload
        ArrayList<BlockEntry> blocks = blockBlob.downloadBlockList(BlockListingFilter.UNCOMMITTED, null, null, null);
        assertEquals(1, blocks.size());
        assertEquals(511, blocks.get(0).getSize());

        // After close we should see the second upload
        blobOutputStream.close();
        blocks = blockBlob.downloadBlockList(BlockListingFilter.COMMITTED, null, null, null);
        assertEquals(2, blocks.size());
        assertEquals(513, blocks.get(1).getSize());
    }

    public void testWritesDoubleConcurrency() throws URISyntaxException, StorageException, IOException,
            InterruptedException {
        String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("concurrency");
        CloudBlockBlob blockBlob = this.container.getBlockBlobReference(blobName);

        // setup the blob output stream with a concurrency of 5
        BlobRequestOptions options = new BlobRequestOptions();
        options.setConcurrentRequestCount(5);
        BlobOutputStream blobOutputStream = blockBlob.openOutputStream(null, options, null);

        // set up the execution completion service
        ExecutorService threadExecutor = Executors.newFixedThreadPool(5);
        ExecutorCompletionService<Void> completion = new ExecutorCompletionService<Void>(threadExecutor);

        int tasks = 10;
        int writes = 10;
        int length = 512;

        // submit tasks to write and flush many blocks
        for (int i = 0; i < tasks; i++) {
            completion.submit(new WriteTask(blobOutputStream, length, writes, 4 /*flush period*/));
        }

        // wait for all tasks to complete
        for (int i = 0; i < tasks; i++) {
            completion.take();
        }

        // shut down the thread executor for this method
        threadExecutor.shutdown();

        // check that blocks were committed
        ArrayList<BlockEntry> blocks = blockBlob.downloadBlockList(BlockListingFilter.UNCOMMITTED, null, null, null);
        assertTrue(blocks.size() != 0);

        // close the stream and check that the blob is the expected length
        blobOutputStream.close();
        blockBlob.downloadAttributes();
        assertTrue(blockBlob.getProperties().getLength() == length*writes*tasks);
    }

    public void testWritesNoConcurrency() throws URISyntaxException, StorageException, IOException {
        int writes = 10;

        this.smallPutThresholdHelper(Constants.MB, writes, null);
        this.writeFlushHelper(512, writes, null, 1);
        this.writeFlushHelper(512, writes, null, 4);
        this.writeFlushHelper(512, writes, null, writes+1);
    }

    public void testWritesConcurrency() throws URISyntaxException, StorageException, IOException {
        int writes = 10;

        BlobRequestOptions options = new BlobRequestOptions();
        options.setConcurrentRequestCount(5);

        this.smallPutThresholdHelper(Constants.MB, writes, options);
        this.writeFlushHelper(512, writes, options, 1);
        this.writeFlushHelper(512, writes, options, 4);
        this.writeFlushHelper(512, writes, options, writes+1);
    }

    private void smallPutThresholdHelper(int length, int writes, BlobRequestOptions options)
            throws URISyntaxException, StorageException, IOException {
        byte[] buffer = BlobTestHelper.getRandomBuffer(length*writes);

        String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("concurrency");
        CloudBlockBlob blockBlob = this.container.getBlockBlobReference(blobName);
        blockBlob.setStreamWriteSizeInBytes(length);

        BlobOutputStream blobOutputStream = blockBlob.openOutputStream(null, options, null);
        for (int i = 0; i < writes; i ++) {
            blobOutputStream.write(buffer, i*length, length);
        }

        blobOutputStream.flush();
        ArrayList<BlockEntry> blocks = blockBlob.downloadBlockList(BlockListingFilter.UNCOMMITTED, null, null, null);
        assertEquals(writes, blocks.size());

        blobOutputStream.close();
        blocks = blockBlob.downloadBlockList(BlockListingFilter.COMMITTED, null, null, null);
        assertEquals(writes, blocks.size());

        byte[] outBuffer = new byte[writes*length];
        blockBlob.downloadToByteArray(outBuffer, 0);
        for (int i = 0; i < length*writes; i ++) {
            assertEquals(buffer[i], outBuffer[i]);
        }
    }

    private void writeFlushHelper(int length, int writes, BlobRequestOptions options, int flushPeriod)
            throws URISyntaxException, StorageException, IOException {
        byte[] buffer = BlobTestHelper.getRandomBuffer(length*writes);

        String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("concurrency");
        CloudBlockBlob blockBlob = this.container.getBlockBlobReference(blobName);

        ArrayList<BlockEntry> blocks;
        BlobOutputStream blobOutputStream = blockBlob.openOutputStream(null, options, null);
        for (int i = 0; i < writes; i ++) {
            blobOutputStream.write(buffer, i*length, length);

            if ((i+1)%flushPeriod == 0) {
                blobOutputStream.flush();
                blocks = blockBlob.downloadBlockList(BlockListingFilter.UNCOMMITTED, null, null, null);
                assertEquals((int)Math.ceil((i+1)/flushPeriod), blocks.size());
            }
        }

        blobOutputStream.close();
        blocks = blockBlob.downloadBlockList(BlockListingFilter.COMMITTED, null, null, null);

        int flushRequired = writes-flushPeriod < 0 || writes%flushPeriod == 0 ? 0 : 1;
        double expected = Math.ceil(((double)writes+flushRequired)/flushPeriod);
        assertEquals((long)expected, blocks.size());

        byte[] outBuffer = new byte[writes*length];
        blockBlob.downloadToByteArray(outBuffer, 0);
        for (int i = 0; i < length*writes; i ++) {
            assertEquals(buffer[i], outBuffer[i]);
        }
    }

    private static class FlushTask implements Callable<Void> {
        final BlobOutputStream stream;

        public FlushTask(BlobOutputStream stream) {
            this.stream = stream;
        }

        @Override
        public Void call() {
            try {
                stream.flush();
            } catch (IOException e) {
                fail("The flush should succeed.");
            }
            return null;
        }
    }

    private class WriteTask implements Callable<Void> {
        final int length;
        final int writes;
        final int flushPeriod;
        final BlobOutputStream blobOutputStream;

        public WriteTask(BlobOutputStream blobOutputStream, int length, int writes, int flushPeriod) {
            this.length = length;
            this.writes = writes;
            this.flushPeriod = flushPeriod;
            this.blobOutputStream = blobOutputStream;
        }

        @Override
        public Void call() {
            try {
                byte[] buffer = BlobTestHelper.getRandomBuffer(this.length*this.writes);
                for (int i = 0; i < writes; i ++) {
                    this.blobOutputStream.write(buffer, i*this.length, this.length);

                    if ((i+1)%flushPeriod == 0) {
                        this.blobOutputStream.flush();
                    }
                }
            } catch (Exception e) {
                fail("flushHelper should succeed.");
            }
            return null;
        }
    }
}


text:
{% for (var chunk in o.htmlWebpackPlugin.files.chunks) { %}
<script src="{%=o.htmlWebpackPlugin.files.chunks[chunk].entry %}"></script>
{% } %}
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
<head>
    <title>Canvas</title>
    <link rel="stylesheet" media="screen" href="../../assets/css/reset.css" />
    <link rel="stylesheet" media="screen" href="../../assets/css/screen.css" />

    <script type="text/javascript" src="../../../src/lib/dependency.js"></script>
    <script type="text/javascript" src="../../../src/lib/require.js"></script>
    <script type="text/javascript" src="../../assets/js/config.js"></script>
    <script type="text/javascript" src="../../../src/lib/jquery-1.8.1.js"></script>

</head>
<body>
    <section id="js-viewport">
        <canvas id="particles-1">Please use a HTML5 Canvas enabled browser</canvas>
        <canvas id="particles-2">Please use a HTML5 Canvas enabled browser</canvas>
        <canvas id="particles-3">Please use a HTML5 Canvas enabled browser</canvas>
        <canvas id="particles-4">Please use a HTML5 Canvas enabled browser</canvas>
        <canvas id="particles-5">Please use a HTML5 Canvas enabled browser</canvas>
    </section>

    <script type="text/javascript" src="js/main.js"></script>
</body>
</html>


text:
docid: progressive-jpegs
title: Progressive JPEGs
layout: docs
permalink: /docs/progressive-jpegs.html
prev: using-controllerbuilder.html
next: animations.html
---

Fresco supports the streaming of progressive JPEG images over the network.

Scans of the image will be shown in the view as you download them. Users will see the quality of the image start out low and gradually become clearer.

This is only supported for network images. Local images are decoded at once, so no need for progressiveness. Also, keep in mind that not all JPEG images are encoded in progressive format, and for those that are not, it is not possible to display them progressively.

#### Building the image request

Currently, you must explicitly request progressive rendering while building the image request:

```java
Uri uri;
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
    .setProgressiveRenderingEnabled(true)
    .build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
    .setImageRequest(request)
    .setOldController(mSimpleDraweeView.getController())
    .build();
mSimpleDraweeView.setController(controller);
```

We hope to add support for using progressive images with `setImageURI` in a future release.


text:
const program = require("commander");
const chalk = require("chalk");
const os = require("os");
const fs = require("fs");

const { print } = require("./index.js");

const list = list => list.split(",");

program
  .command("stories")
  .description("Read last hacker news stories")
  .option("-k, --keywords <keywords>", "Keywords of your interest (comma separated)", list, [])
  .option("-c, --collections <collections>", "Collections of keywords in your home directory", list, [])
  .action(command => {
    const keywords = [];

    if (command.keywords && command.keywords.length) {
      keywords.push(...command.keywords);
    }

    if (command.collections) {
      command.collections.forEach(collection => {
        try {
          let collectionKeywords = fs.readFileSync(`${os.homedir()}/.hackernews-cli/${collection}`, {
            encoding: "utf-8"
          });
          keywords.push(...collectionKeywords.trim().split(","));
        } catch (error) {
          console.log(
            chalk.red.bold(
              `Cannot read collection with name ${collection}, check your collections inside ${os.homedir()}/.hackernews-cli`
            )
          );
          process.exit(1);
        }
      }, "");
    }

    print(keywords);
  });

program
  .command("create <collection>")
  .description('Create a collection, use the following input string "collection_name=keyword1,keyword2,keyword3"')
  .action(command => {
    const isValid = new RegExp(/([a-zA-Z0-9]+=)([a-zA-Z0-9]+,{0,1})+\w$/g).test(command);

    try {
      if (!isValid) {
        throw new Error("Invalid input");
      }

      const [collectionName, keywords] = command.split("=");
      fs.writeFileSync(`${os.homedir()}/.hackernews-cli/${collectionName}`, keywords);
      console.log(chalk.green.bold(`Collection ${command} created`));
    } catch (error) {
      console.log(chalk.red.bold(`Cannot write collection: ${error.message}`));
      process.exit(1);
    }
  });

program
  .command("remove <collection>")
  .description("Remove a collection")
  .action(command => {
    try {
      fs.unlinkSync(`${os.homedir()}/.hackernews-cli/${command}`);
      console.log(chalk.green.bold(`Collection ${command} removed`));
    } catch (error) {
      console.log(
        chalk.red.bold(
          `Cannot read collection with name ${command}, check your collections inside ${os.homedir()}/.hackernews-cli`
        )
      );
      process.exit(1);
    }
  });

program.parse(process.argv);


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="Refined subclasses of SQLException" />
<meta content="SQLException" name="DC.subject" />
<meta content="SQLException" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_0summary.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_0connection.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_0databaseMetaData.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_0statement.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_0dataSource.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbcrefsqlxml.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefjdbc4_0sqlexception" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Refined subclasses of SQLException</title>

Refined subclasses of SQLException

If your application runs on JDK 1.6 or higher, exceptions raised by
Derby
will generally be one of the refined subclasses of SQLException,
introduced by JDBC 4.0. These refined exceptions are raised under the
conditions described by their respective javadoc.

java.sql.SQLClientInfoException

java.sql.SQLDataException

java.sql.SQLFeatureNotSupportedException

java.sql.SQLIntegrityConstraintViolationException

java.sql.SQLInvalidAuthorizationSpecException

java.sql.SQLSyntaxErrorException

java.sql.SQLTransactionRollbackException

java.sql.SQLTransientConnectionException

Parent topic: Features supported on all JDBC 4 releases

Related reference

java.sql.Connection interface: JDBC 4.0 features

java.sql.DatabaseMetaData interface: JDBC 4.0 features

java.sql.Statement interface: JDBC 4.0 features

javax.sql.DataSource interface: JDBC 3 and JDBC 4.0 features

java.sql.SQLXML interface


text:
require 'spec_helper'

describe HistoryController do

  let(:user) { FactoryBot.create(:user) }

  before do
    sign_in(user)
  end

  context 'json' do
    let!(:result) { FactoryBot.create(:result, user: user) }

    before do
      get :index, format: :json
    end

    let(:json) { JSON.parse(response.body, symbolize_names: true) }

    it 'has history' do
      expect(json[:history].count).to eq 1
    end

    it 'has meta pagination information' do
      expect(json[:meta].keys).to include(:current_page, :next_page, :prev_page, :total_pages, :total_items)
    end

    describe 'result structure' do
      let(:json_result) { json[:history].first }
      subject { json_result }

      its([:id]) { should eq(result.id) }
      its([:mode]) { should eq(result.mode) }
      its([:hero]) { should eq(result.hero.titleize) }
      its([:opponent]) { should eq(result.opponent.titleize) }
      its([:coin]) { should eq(result.coin) }
      its([:result]) { should eq(result.win ? 'win' : 'loss') }
      its([:added]) { should eq(result.created_at.iso8601(3)) }
      its([:duration]) { should eq(result.duration) }

      context 'ranked' do
        describe 'rank' do
          let!(:result) { FactoryBot.create(:result, mode: :ranked, user: user, rank: 25) }
          its([:rank]) { should eq(result.rank) }
        end
        describe 'legend' do
          let!(:result) { FactoryBot.create(:result, mode: :ranked, user: user, legend: 101) }
          its([:legend]) { should eq(result.legend) }
        end
      end

      context 'arena' do
        let!(:result) { FactoryBot.create(:result_with_arena, mode: :arena, user: user) }
        its([:arena_id]) { should eq(result.arena.id) }
      end

      context 'no arena' do
        let!(:result) { FactoryBot.create(:result, mode: :ranked, user: user) }
        it { should_not include(:arena_id) }
      end

      describe 'note' do
        let!(:result) { FactoryBot.create(:result, mode: :ranked, user: user, note: 'test') }
        its([:note]) { should eq('test') }
      end

      describe 'decks' do
        let(:hero) { 'rogue' }
        let(:opponent) { 'warrior' }

        let(:deck) { Deck.where(hero: hero).first }
        let(:opponent_deck) { Deck.where(hero: opponent).first }

        let!(:result) { FactoryBot.create(:result, mode: :ranked, user: user, hero: hero, opponent: opponent, deck: deck, opponent_deck: opponent_deck) }

        its([:opponent_deck]) { should eq(result.opponent_deck.name) }
        its([:hero_deck]) { should eq(result.deck.name) }
      end

      describe 'card history' do
        before do
          result.create_card_history(data: [
            {turn: 3, player: :me, card_id: 'EX1_538'}, # unleash
            {turn: 4, player: :opponent, card_id: 'CS2_032'}, # flamestrike
            {turn: 4, player: :me, card_id: 'CS2_033'} # water elemental
          ])
          get :index, format: :json
        end

        specify { expect(json_result[:card_history].count).to eq 3 }

        describe 'card_history structure' do
          let(:json_card_history) { json_result[:card_history] }
          subject { json_card_history.first }

          its([:player]) { should eq 'me' }
          its([:turn]) { should eq 3 }

          describe 'card structure' do
            subject { json_card_history.first[:card] }
            its([:name]) { should eq 'Unleash the Hounds' }
            its([:id]) { should eq 'EX1_538' }
            its([:mana]) { should eq 3 }
          end

        end
      end

    end
  end

end


text:
<!doctype html>

    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Style Guide: Single-family</title>
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@FreddieMac" />
    <meta property="og:title" content="Style Guide: Single-family" />
    <meta name="twitter:title" content="Style Guide: Single-family"/>
    <meta name="Description" content="The styleguide is based on the Foundation framework." />
    <meta property="og:description" content="The styleguide is based on the Foundation framework." />
    <meta name="twitter:description" content="The styleguide is based on the Foundation framework." />
    <meta property="og:locale" content="en_US">
    <meta property="og:type" content="website" />
    <meta property="og:image" content="files/styleguide.jpg" />
    <meta name="twitter:image" content="files/styleguide.jpg" />
    <meta name="theme-color" content="#88BD45">
    <link rel="shortcut icon" type="image/png" href="/images/favicon.png" />
    <link rel="icon" type="image/png" href="/images/favicon.png" />
    <link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,900' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="/ss/app_sf.css">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.9.1/styles/github.min.css">

Corporate Style Guide

This style guide was built with Foundation for Sites. For more information on how to use this responsive front-end framework, check out the documentation, get help from the Foundation community, or request immediate technical support.

      Visit the Docs
      Foundation Forum
      Technical Support

          {{#each pages}}

{{ title }}

          {{/each}}

        {{#each pages}}

            {{ body }}

        {{/each}}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="VcsDirectoryMappings">
    <mapping directory="$PROJECT_DIR$" vcs="Git" />
    <mapping directory="$PROJECT_DIR$/friendly-timer-app" vcs="Git" />
  </component>
</project>


text: string_types = str,


text:
require 'spec_helper'

describe 'elasticsearch::pipeline', :type => 'define' do
  let(:title) { 'testpipeline' }
  let(:pre_condition) do
    'class { "elasticsearch" : }'
  end

  on_supported_os(
    :hardwaremodels => ['x86_64'],
    :supported_os => [
      {
        'operatingsystem' => 'CentOS',
        'operatingsystemrelease' => ['6']
      }
    ]
  ).each do |os, facts|
    context "on #{os}" do
      let(:facts) { facts.merge(
        :scenario => '',
        :common => ''
      ) }

      describe 'parameter validation' do
        %i[api_ca_file api_ca_path].each do |param|
          let :params do
            {
              :ensure => 'present',
              :content => {},
              param => 'foo/cert'
            }
          end

          it 'validates cert paths' do
            is_expected.to compile.and_raise_error(/expects a/)
          end
        end

        describe 'missing parent class' do
          let(:pre_condition) {}
          it { should_not compile }
        end
      end

      describe 'class parameter inheritance' do
        let :params do
          {
            :ensure => 'present',
            :content => {}
          }
        end
        let(:pre_condition) do
          <<-EOS
            class { 'elasticsearch' :
              api_protocol => 'https',
              api_host => '127.0.0.1',
              api_port => 9201,
              api_timeout => 11,
              api_basic_auth_username => 'elastic',
              api_basic_auth_password => 'password',
              api_ca_file => '/foo/bar.pem',
              api_ca_path => '/foo/',
              validate_tls => false,
            }
          EOS
        end

        it do
          should contain_elasticsearch__pipeline(title)
          should contain_es_instance_conn_validator("#{title}-ingest-pipeline")
            .that_comes_before("elasticsearch_pipeline[#{title}]")
          should contain_elasticsearch_pipeline(title).with(
            :ensure => 'present',
            :content => {},
            :protocol => 'https',
            :host => '127.0.0.1',
            :port => 9201,
            :timeout => 11,
            :username => 'elastic',
            :password => 'password',
            :ca_file => '/foo/bar.pem',
            :ca_path => '/foo/',
            :validate_tls => false
          )
        end
      end

      describe 'pipeline deletion' do
        let :params do
          {
            :ensure => 'absent'
          }
        end

        it 'removes pipelines' do
          should contain_elasticsearch_pipeline(title).with(:ensure => 'absent')
        end
      end
    end
  end
end


text:
//
//
//
//  Created by Dmitry Zhurov on 26.10.12.
//  Copyright (c) 2012 Dmitry Zhurov. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "XSDTypes.h"
#import "XSDObjects/XSDEnums.h"

extern NSString const* kXSDClassTypeKey;

/**
 @class XSDBaseEntity

 Base class for any Data Trahsfer Object in wadl2objc generated code.
 - Inheritance schema:
 `XSDBaseEntity` -> <_MachineClass> -> <HumanClass>

 *MachineClass* contains all fields described in Client-Server Protocol [XSD](https://www.w3schools.com/xml/schema_intro.asp).
 MachineClass contains className with _Underscore_ prefix. It also has generated implementations for methods:
 * `-mappedKeys`
 * `-enumNameForMappedField:`
 * `-classNameOfMembersForMappedField:`

 - Example: for XSD described class `HeightDto` generator will create `_HeightDto` machine class with the same fields: \
 * heightInch
 - Important: Do not modify machine class manually. You will loose your changes after wadl2objc generates it again

 *HumanClass* can contain any additional fields and logic you may want to add to a class. Fill free to modify it.
 - Example: for XSD described class `HeightDto` generator will create `HeightDto` human class without any fields. \
 You may want to add conversion methods to this class, like:
 * `-heightFt`

 - SeeAlso:
 [wadl2objc](https://github.com/dzhurov/wadl2objc)
 */
@interface XSDBaseEntity : NSObject <NSCopying, NSCoding>

@property (nonatomic) BOOL isErrorDataReloading;

- (NSString *)xsdClassType;

-(NSArray<NSString*>*)descriptionIgnoreProperties;

/*! Date and DateTime formatters for serialization and deserialization */
+ (void)setDateFormatter:(NSDateFormatter*)dateFormatter;
+ (void)setDateTimeFormatter:(NSDateFormatter*)dateTimeFormatter;
+ (NSDateFormatter *)dateFormatter;
+ (NSDateFormatter *)dateTimeFormatter;

/*! Simple creation entities from array<NSDictionary> */
+ (NSMutableArray*)objectsWithDictionariesInfoArray:(NSArray*)array;

- (id)initWithDictionaryInfo:(NSDictionary*)dictionary;
- (NSMutableDictionary*)dictionaryInfoForKeys:(NSArray*)keys;
- (void) setDictionaryInfo:(NSDictionary*)dictInfo forKeys:(NSArray*)keys;
- (void)setDictionaryInfo:(NSDictionary *)JSONDictionary;
- (NSMutableDictionary*)dictionaryInfo;

- (void)setMappedFieldsDictionary:(NSDictionary *)dict;

/*! Reloads by Machine inheritors */
+ (NSArray *)mappedKeys;
+ (NSString *)enumNameForMappedField:(NSString*)fieldName;
+ (NSString *)classNameOfMembersForMappedField:(NSString*)fieldName;

/**
 Works just like `-setValue:forKeyPath:` and also creates missing subentities
 */
- (void)setValue:(id)value forKeyPath:(NSString*)keyPath createIntermediateEntities:(BOOL)createIntermediateEntities;

- (void)propertiesEnumeration:(void(^)(NSString *propertyName, NSArray *attributes))iterationBlock;

/*! Sets all mappedKeys fields from entity to self */
- (void)setEntityForMappedFields:(XSDBaseEntity*)entity;

@end


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Notificacion_model extends CI_Model
{

    public function __construct()
    {
        parent::__construct();
    }

	public function select_tiporeporte()
	{
		$query=$this->db->query("SELECT * FROM bom_tiporeporte");
		return $query->result_array();
	}

	public function select_clasificacion()
	{
		$query=$this->db->query("SELECT * FROM bom_clasificacion");
		return $query->result_array();
	}

	public function muestra_usuarios_origen($tipo,$cla,$pasos)
	{
		$query=$this->db->query("EXEC sp_bom_correo_notificacion_todos $tipo,$cla,$pasos");
		return $query->result_array();
	}

	public function muestra_usuarios_destino($tipo,$cla,$pasos)
	{
		$query=$this->db->query("EXEC sp_bom_correo_notificacion_usuario $tipo,$cla,$pasos");
		return $query->result_array();
	}

	public function muestra_pasos()
	{
		$query=$this->db->query("SELECT [idmenu],[nombre_menu] FROM [dbo].[grl_menu] WHERE idmenu BETWEEN 20 AND 25");
		return $query->result_array();
	}

	public function addcorreo($idusu,$idtipo,$idcla,$pasos)
	{
		$query=$this->db->query("EXEC sp_bom_notificacion_agregar_usuario $idusu,$idtipo,$idcla,$pasos");
		return $query->result_array();
	}

	public function removecorreo($id)
	{
		$query=$this->db->query("EXEC sp_bom_notificacion_elimina_usuario $id");
		return $query->result_array();
	}

	public function select_correos($idtiporeporte,$idclasificacion,$plaza,$menu)
	{
		$query=$this->db->query("SELECT correo FROM [dbo].[vw_bom_correo_notificaciones] WHERE idtiporeporte=".$idtiporeporte." AND idclasificacion<=".$idclasificacion." and idplaza=".$plaza." AND idmenu=".$menu." GROUP BY correo");
		return $query->result_array();
	}

	public function select_copiaoculta()
	{
		$query=$this->db->query("SELECT * FROM [dbo].[bom_copiaoculta]");
		return $query->result_array();
	}

	public function select_actividades_resumen()
	{
		$query=$this->db->query("SELECT * FROM [dbo].[bom_notificacion_resumen_actpen]");
		return $query->result_array();
	}

	public function select_usuarios($idtiporeporte,$idclasificacion,$plaza,$menu)
	{
		$query=$this->db->query("SELECT nombre FROM [dbo].[vw_bom_correo_notificaciones] WHERE idtiporeporte=".$idtiporeporte." AND idclasificacion<=".$idclasificacion." and idplaza=".$plaza." AND idmenu=".$menu." GROUP BY nombre");
		return $query->result_array();
	}

}


text:
<?php

//Creates a new jam with the provided theme, which starts at the given date
//and time. All three are non-blank strings. $date and $time should be
//parsable by PHP's date(...) function. Function also authorizes the user
//(checks whether or not they are an admin).
function CreateJam(MessageService &$messageService, $theme, $date, $time, $colorsList, $defaultEntryIconUrl){
	global $ip, $userAgent, $loggedInUser, $jamData, $userData;

	$maxNonDeletedJamNumber = 0;
	foreach($jamData->JamModels as $i => $jamModel){
		if($jamModel->Deleted){
			continue;
		}
		$maxNonDeletedJamNumber = max($maxNonDeletedJamNumber, $jamModel->JamNumber);
	}

	$jamNumber = $maxNonDeletedJamNumber + 1;
	$theme = trim($theme);
	$date = trim($date);
	$time = trim($time);
	foreach($colorsList as $i => $color){
		$clr = trim($color);
		if(!preg_match('/^[0-9A-Fa-f]{6}/', $clr)){
			return "INVALID_COLOR";
		}
		$colorsList[$i] = $clr;
	}

	//Authorize user (logged in)
	if($loggedInUser === false){
		return "NOT_LOGGED_IN";
	}

	//Authorize user (is admin)
	if(IsAdmin($loggedInUser) === false){
		return "NOT_AUTHORIZED";
	}

	//Validate jam number
	if($jamNumber <= 0){
		return "INVALID_JAM_NUMBER";
	}

	//Validate theme
	if(strlen($theme) <= 0){
		return "INVALID_THEME";
	}

	if(!$defaultEntryIconUrl){
		return "INVALID_DEFAULT_ENTRY_ICON_URL";
	}

	//Validate date and time and create datetime object
	if(strlen($date) <= 0){
		return "INVALID_DATE";
	}else if(strlen($time) <= 0){
		return "INVALID_TIME";
	}else{
		$datetime = strtotime($date." ".$time." UTC");
	}

	$colors = implode("|", $colorsList);
	$startTime = "".gmdate("Y-m-d H:i", $datetime);

	$jamData->AddJamToDatabase($ip, $userAgent, $loggedInUser->Id, $jamNumber, -2, $theme, $startTime, $colors, $defaultEntryIconUrl);

	$messageService->SendMessage(LogMessage::UserLogMessage(
		"JAM_ADDED",
		"Jam scheduled with values: JamNumber: $jamNumber, Theme: '$theme', StartTime: '$startTime', Colors: $colors, Default entry icon url: $defaultEntryIconUrl",
		$loggedInUser->Id)
	);
	$userData->LogAdminAction($loggedInUser->Id);

	return "SUCCESS";
}

function PerformAction(MessageService &$messageService, &$loggedInUser){
	global $_POST, $configData;

	if(IsAdmin($loggedInUser) !== false){
		$theme = (isset($_POST[FORM_NEWJAM_THEME])) ? $_POST[FORM_NEWJAM_THEME] : "";
		$date = (isset($_POST[FORM_NEWJAM_DATE])) ? $_POST[FORM_NEWJAM_DATE] : "";
		$time = (isset($_POST[FORM_NEWJAM_TIME])) ? $_POST[FORM_NEWJAM_TIME] : "";
		$defaultEntryIconUrl = (isset($_POST[FORM_NEWJAM_DEFAULT_ICON_URL])) ? $_POST[FORM_NEWJAM_DEFAULT_ICON_URL] : $configData->ConfigModels[CONFIG_DEFAULT_GAME_ICON_URL]->Value;
		$jamColors = Array();
		for($colorIndex = 0; $colorIndex < $configData->ConfigModels[CONFIG_MAX_COLORS_FOR_JAM]->Value; $colorIndex++){
			if(isset($_POST[FORM_NEWJAM_JAM_COLOR.$colorIndex])){
				$jamColors[] = $_POST[FORM_NEWJAM_JAM_COLOR.$colorIndex];
			}
		}
		if(count($jamColors) == 0){
			$jamColors = Array("FFFFFF");
		}

		return CreateJam($messageService, $theme, $date, $time, $jamColors, $defaultEntryIconUrl);
	}
}

?>


text:
<?php

namespace Minimalcode\Search\Tests;

use Minimalcode\Search\Criteria;

class SpringCriteriaTest extends CriteriaBaseTest
{
    public function testIs()
    {
        $criteria = Criteria::where('field_1')->is('is');

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:is', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testMultipleIs()
    {
        $criteria = Criteria::where('field_1')->is('is')->is('another is');

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:(is "another is")', $criteria->getQuery());
        self::assertCount(2, $this->getPredicates($criteria));
    }

    public function testEndsWith()
    {
        $criteria = Criteria::where('field_1')->endsWith('end');

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:*end', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testEndsWithMulitpleValues()
    {
        $criteria = Criteria::where('field_1')->endsWith(['one', 'two', 'three']);

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:(*one *two *three)', $criteria->getQuery());
        self::assertCount(3, $this->getPredicates($criteria));
    }

    public function testStartsWith()
    {
        $criteria = Criteria::where('field_1')->startsWith('start');

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:start*', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testStartsWithMultipleValues()
    {
        $criteria = Criteria::where('field_1')->startsWith(['one', 'two', 'three']);

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:(one* two* three*)', $criteria->getQuery());
        self::assertCount(3, $this->getPredicates($criteria));
    }

    public function testContains()
    {
        $criteria = Criteria::where('field_1')->contains('contains');

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:*contains*', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testContainsWithMultipleValues()
    {
        $criteria = Criteria::where('field_1')->contains(['one', 'two', 'three']);

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:(*one* *two* *three*)', $criteria->getQuery());
        self::assertCount(3, $this->getPredicates($criteria));
    }

    public function testExpression()
    {
        $criteria = Criteria::where('field_1')->expression('(have fun using +solr && expressions*)');

        self::assertEquals('field_1:(have fun using +solr && expressions*)', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testCriteriaChain()
    {
        $criteria = Criteria::where('field_1')
            ->startsWith('start')
            ->endsWith('end')
            ->contains('contains')
            ->is('is');

        self::assertEquals('field_1', $this->getField($criteria));
        self::assertEquals('field_1:(start* *end *contains* is)', $criteria->getQuery());
        self::assertCount(4, $this->getPredicates($criteria));
    }

    public function testAnd()
    {
        $criteria = Criteria::where('field_1')
            ->startsWith('start')
            ->endsWith('end')
        ->andWhere('field_2')// Nesting: predicates = 2 crotches
            ->startsWith('2start')
            ->endsWith('2end');

        self::assertEquals('field_1:(start* *end) AND field_2:(2start* *2end)', $criteria->getQuery());
        self::assertCount(2, $this->getPredicates($criteria));
    }

    public function testOr()
    {
        $criteria = Criteria::where('field_1')
            ->startsWith('start')
        ->orWhere('field_2')// Nesting: predicates = 2 crotches
            ->endsWith('end')
            ->startsWith('start2');

        self::assertEquals('field_1:start* OR field_2:(*end start2*)', $criteria->getQuery());
        self::assertCount(2, $this->getPredicates($criteria));
    }

    public function testCriteriaWithWhiteSpace()
    {
        $criteria = Criteria::where('field_1')->is('white space');
        self::assertEquals('field_1:"white space"', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testIsNot()
    {
        $criteria = Criteria::where('field_1')->is('value_1')->not();
        self::assertEquals('-field_1:value_1', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testFuzzy()
    {
        $criteria = Criteria::where('field_1')->fuzzy('value_1');
        self::assertEquals('field_1:value_1~', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testFuzzyWithDistanceFloat()
    {
        $criteria = Criteria::where('field_1')->fuzzy('value_1', 0.5);
        self::assertEquals('field_1:value_1~0.5', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testFuzzyWithDistance()
    {
        $criteria = Criteria::where('field_1')->fuzzy('value_1', 5);
        self::assertEquals('field_1:value_1~5', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testSloppy()
    {
        $criteria = Criteria::where('field_1')->sloppy('value1 value2', 2);
        self::assertEquals('field_1:"value1 value2"~2', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testBoost()
    {
        $criteria = Criteria::where('field_1')->is('value_1')->boost(2.0);
        self::assertEquals('field_1:value_1^2.0', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testBoostMultipleValues()
    {
        $criteria = Criteria::where('field_1')->is('value_1')->is('value_2')->boost(2.0);
        self::assertEquals('field_1:(value_1 value_2)^2.0', $criteria->getQuery());
        self::assertCount(2, $this->getPredicates($criteria));
    }

    public function testBoostMultipleCriteriasValues()
    {
        $criteria = Criteria::where('field_1')
            ->is('value_1')
            ->is('value_2')
            ->boost(2.0)
        ->andWhere('field_3')// Nesting: predicates = 1 Crotch
            ->is('value_3');

        self::assertEquals('field_1:(value_1 value_2)^2.0 AND field_3:value_3', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testBetween()
    {
        $criteria = Criteria::where('field_1')->between(100, 200);
        self::assertEquals('field_1:[100 TO 200]', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testBetweenExcludeLowerBound()
    {
        $criteria = Criteria::where('field_1')->between(100, 200, false, true);
        self::assertEquals('field_1:{100 TO 200]', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testBetweenExcludeUpperBound()
    {
        $criteria = Criteria::where('field_1')->between(100, 200, true, false);
        self::assertEquals('field_1:[100 TO 200}', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testBetweenWithoutUpperBound()
    {
        $criteria = Criteria::where('field_1')->between(100, null);
        self::assertEquals('field_1:[100 TO *]', $criteria->getQuery());
    }

    public function testBetweenWithoutLowerBound()
    {
        $criteria = Criteria::where('field_1')->between(null, 200);
        self::assertEquals('field_1:[* TO 200]', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testBetweenNegativeNumber()
    {
        $criteria = Criteria::where('field_1')->between(-200, -100);
        self::assertEquals("field_1:[\\-200 TO \\-100]", $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testIn()
    {
        $criteria = Criteria::where('field_1')->in([1, 2, 3, 5, 8, 13, 21]);
        self::assertEquals('field_1:(1 2 3 5 8 13 21)', $criteria->getQuery());
        self::assertCount(7, $this->getPredicates($criteria));
    }

    public function testIsWithNegativeNumner()
    {
        $criteria = Criteria::where('field_1')->is(-100);
        self::assertEquals("field_1:\\-100", $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testNear()
    {
        $criteria = Criteria::where('field_1')->nearCircle(48.303056, 14.290556, 5);
        self::assertEquals('{!bbox pt=48.303056,14.290556 sfield=field_1 d=5.0}', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testNearWithDistanceUnitKilometers()
    {
        $criteria = Criteria::where('field_1')->nearCircle(48.303056, 14.290556, 1);
        self::assertEquals('{!bbox pt=48.303056,14.290556 sfield=field_1 d=1.0}', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testNearWithCoords()
    {
        $criteria = Criteria::where('field_1')->withinBox(48.303056, 14.290556, 48.303056, 14.290556);
        self::assertEquals('field_1:[48.303056,14.290556 TO 48.303056,14.290556]', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-105
     * @throws \InvalidArgumentException
     */
    public function testNestedOrPartWithAnd()
    {
        $criteria = Criteria::where('field_1') ->is('foo')
            ->andWhere(Criteria::where('field_2')->is('bar')->orWhere('field_3')->is('roo'))// Nesting
            ->orWhere(Criteria::where('field_4')->is('spring')->andWhere('field_5')->is('data'));

        self::assertEquals('field_1:foo AND (field_2:bar OR field_3:roo) OR (field_4:spring AND field_5:data)', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-105
     * @throws \InvalidArgumentException
     */
    public function testNestedOrPartWithAndSomeOtherThings()
    {
        $criteria = Criteria::where('field_1')->is('foo')->is('bar')
            ->andWhere(Criteria::where('field_2')->is('bar')->is('lala')->orWhere('field_3')->is('roo'))// Nesting
            ->orWhere(Criteria::where('field_4')->is('spring')->andWhere('field_5')->is('data'));

        self::assertEquals(
            'field_1:(foo bar) AND (field_2:(bar lala) OR field_3:roo) OR (field_4:spring AND field_5:data)',
            $criteria->getQuery()
        );

        self::assertCount(2, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-105
     * @throws \InvalidArgumentException
     */
    public function testMultipleAnd()
    {
        $criteria = Criteria::where('field_1')->is('foo')
            ->andWhere('field_2')->is('bar')// Nesting
            ->andWhere('field_3')->is('roo');

        self::assertEquals('field_1:foo AND field_2:bar AND field_3:roo', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-105
     * @throws \InvalidArgumentException
     */
    public function testMultipleOr()
    {
        $criteria = Criteria::where('field_1')->is('foo')
            ->orWhere('field_2')->is('bar')// Nesting
            ->orWhere('field_3')->is('roo');

        self::assertEquals('field_1:foo OR field_2:bar OR field_3:roo', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-105
     * @throws \InvalidArgumentException
     */
    public function testEmptyCriteriaShouldBeDefaultedToNotNUll()
    {
        $criteria = Criteria::where('field_1')->is('foo')
            ->andWhere('field_2')// Nesting
            ->orWhere('field_3');

        self::assertEquals('field_1:foo AND field_2:[* TO *] OR field_3:[* TO *]', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-105
     * @throws \InvalidArgumentException
     */
    public function testDeepNesting()
    {
        $criteria = Criteria::where('field_1')->is('foo')
            ->andWhere(Criteria::where('field_2')->is('bar')->andWhere('field_3')->is('roo')
            ->andWhere(Criteria::where('field_4')->is('spring')->andWhere('field_5')->is('data')->orWhere('field_6')->is('solr')));

        self::assertEquals(
            'field_1:foo AND (field_2:bar AND field_3:roo AND (field_4:spring AND field_5:data OR field_6:solr))',
            $criteria->getQuery()
        );

        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-168
     * @throws \InvalidArgumentException
     */
    public function testNotCritieraCarriedOnPorperlyForNullAndNotNull()
    {
        $criteria = Criteria::where('param1')->isNotNull()
            ->andWhere('param2')->isNull();// Nesting

        self::assertEquals('param1:[* TO *] AND -param2:[* TO *]', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-196
     * @throws \InvalidArgumentException
     */
    public function testConnectShouldAllowConcatinationOfCriteriaWithAndPreservingDesiredBracketing()
    {
        $part1 = Criteria::where('z')->is('roo');
        $part2 = Criteria::where('x')->is('foo')->orWhere('y')->is('bar');
        $criteria = $part1->connect()->andWhere($part2);

        self::assertEquals('z:roo AND (x:foo OR y:bar)', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-196
     * @throws \InvalidArgumentException
     */
    public function testConnectShouldAllowConcatinationOfCriteriaWithAndPreservingDesiredBracketingReverse()
    {
        $part1 = Criteria::where('z')->is('roo');
        $part2 = Criteria::where('x')->is('foo')->orWhere('y')->is('bar');
        $criteria = $part2->connect()->andWhere($part1);

        self::assertEquals('(x:foo OR y:bar) AND z:roo', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-196
     * @throws \InvalidArgumentException
     */
    public function testConnectShouldAllowConcatinationOfCriteriaWithOrPreservingDesiredBracketing()
    {
        $part1 = Criteria::where('z')->is('roo');
        $part2 = Criteria::where('x')->is('foo')->orWhere('y')->is('bar');
        $criteria = $part1->connect()->orWhere($part2);

        self::assertEquals('z:roo OR (x:foo OR y:bar)', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-196
     * @throws \InvalidArgumentException
     */
    public function testConnectShouldAllowConcatinationOfCriteriaWithOrPreservingDesiredBracketingReverse()
    {
        $part1 = Criteria::where('z')->is('roo');
        $part2 = Criteria::where('x')->is('foo')->orWhere('y')->is('bar');
        $criteria = $part2->connect()->orWhere($part1);

        self::assertEquals('(x:foo OR y:bar) OR z:roo', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-196
     * @throws \InvalidArgumentException
     */
    public function testNotOperatorShouldWrapWholeExpression()
    {
        $part1 = Criteria::where('text')->startsWith('fx')->orWhere('product_code')->startsWith('fx');
        $part2 = Criteria::where('text')->startsWith('option')->orWhere('product_code')->startsWith('option');
        $criteria = $part1->connect()->andWhere($part2)->notOperator();

        self::assertEquals('-((text:fx* OR product_code:fx*) AND (text:option* OR product_code:option*))', $criteria->getQuery());
    }

    /**
     * @see DATASOLR-196
     * @throws \InvalidArgumentException
     */
    public function testNotOperatorShouldWrapNestedExpressionCorrectly()
    {
        $part1 = Criteria::where('z')->is('roo');
        $part2 = Criteria::where('x')->is('foo')->orWhere('y')->is('bar')->notOperator();
        $criteria = $part1->connect()->orWhere($part2);

        self::assertEquals('z:roo OR -(x:foo OR y:bar)', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-196
     * @throws \InvalidArgumentException
     */
    public function testNotOperatorShouldWrapNestedExpressionCorrectlyReverse()
    {
        $part1 = Criteria::where('z')->is('roo');
        $part2 = Criteria::where('x')->is('foo')->orWhere('y')->is('bar')->notOperator();
        $criteria = $part2->connect()->orWhere($part1);

        self::assertEquals('-(x:foo OR y:bar) OR z:roo', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    /**
     * @see DATASOLR-196
     * @throws \InvalidArgumentException
     */
    public function testNotOperatorShouldWrapNestedExpressionCorrectlyReverseWithDoubleNegation()
    {
        $part1 = Criteria::where('z')->is('roo');
        $part2 = Criteria::where('x')->is('foo')->orWhere('y')->is('bar')->notOperator();
        $criteria = $part2->connect()->andWhere($part1)->notOperator();

        self::assertEquals('-(-(x:foo OR y:bar) AND z:roo)', $criteria->getQuery());
        self::assertCount(1, $this->getPredicates($criteria));
    }

    public function testCriteriaWithDoubleQuotes()
    {
        $criteria =  Criteria::where('field_1')->is('with \"quote');
        self::assertEquals('field_1:"with \\\\\"quote"', $criteria->getQuery());
    }
}


text:
import requests

from ..common import Settings
from ..errors import BadStatusCodeError, ServiceUnavailableError

def fetch(params, settings=Settings(), post=requests.post):
    try:
        response = post(settings.url, data={ 'year': params.yy, 'month': params.mmm }, timeout=settings.timeout)
    except requests.RequestException:
        raise ServiceUnavailableError
    else:
        if response.status_code == 200:
            return response.text
        else:
            raise BadStatusCodeError(response.status_code)


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Inline SVG Tests index</title>

should not touch this:

                if below SVG is inlined correctly we can reference its content:
                <svg class="icon mood-good"><use xlink:href="#icon-mood-good"></use></svg>

Deep Replace

Inline images

<?= $foo->bar; ?>


text:
package org.wso2.carbon.apimgt.core.models;

import java.io.Serializable;
import java.util.Objects;

/**
 * Endpoint specific information
 */
public class Endpoint implements Serializable {
    private static final long serialVersionUID = 1L;
    private final String id;
    private final String endpointConfig;
    private final Long maxTps;
    private final String security;
    private final String name;
    private final String type;
    private final String applicableLevel;
    private final String config;

    private Endpoint(Builder builder) {
        this.id = builder.id;
        this.endpointConfig = builder.endpointConfig;
        this.maxTps = builder.maxTps;
        this.security = builder.security;
        this.name = builder.name;
        this.type = builder.type;
        this.applicableLevel = builder.applicableLevel;
        this.config = builder.config;
    }

    public static Builder newEndpoint() {
        return new Builder();
    }

    public String getId() {
        return id;
    }

    public String getEndpointConfig() {
        return endpointConfig;
    }

    public Long getMaxTps() {
        return maxTps;
    }

    public String getSecurity() {
        return security;
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    public String getApplicableLevel() {
        return applicableLevel;
    }

    /**
     * {@code Endpoint} builder static inner class.
     */
    public static final class Builder {
        private String id;
        private String endpointConfig;
        private Long maxTps;
        private String security;
        public String name;
        public String type;
        private String applicableLevel;
        private String config = "";

        public String getId() {
            return id;
        }

        public String getEndpointConfig() {
            return endpointConfig;
        }

        public Long getMaxTps() {
            return maxTps;
        }

        public String getSecurity() {
            return security;
        }

        public String getName() {
            return name;
        }

        public String getType() {
            return type;
        }

        public String getApplicableLevel() {
            return applicableLevel;
        }

        public Builder() {
        }

        public Builder(Endpoint copy) {
            this.name = copy.name;
            this.id = copy.id;
            this.endpointConfig = copy.endpointConfig;
            this.maxTps = copy.maxTps;
            this.security = copy.security;
            this.type = copy.type;
            this.applicableLevel = copy.applicableLevel;
        }

        /**
         * Sets the {@code id} and returns a reference to this Builder so that the methods can be chained together.
         *
         * @param id the {@code id} to set
         * @return a reference to this Builder
         */
        public Builder id(String id) {
            this.id = id;
            return this;
        }

        /**
         * Sets the {@code endpointConfig} and returns a reference to this Builder so that the methods can be chained
         * together.
         *
         * @param endpointConfig the {@code endpointConfig} to set
         * @return a reference to this Builder
         */
        public Builder endpointConfig(String endpointConfig) {
            this.endpointConfig = endpointConfig;
            return this;
        }

        /**
         * Sets the {@code name} and returns a reference to this Builder so that the methods can be chained
         * together.
         *
         * @param name the {@code name} to set
         * @return a reference to this Builder
         */
        public Builder name(String name) {
            this.name = name;
            return this;
        }

        /**
         * Sets the {@code maxTps} and returns a reference to this Builder so that the methods can be chained together.
         *
         * @param maxTps the {@code maxTps} to set
         * @return a reference to this Builder
         */
        public Builder maxTps(long maxTps) {
            this.maxTps = maxTps;
            return this;
        }

        /**
         * Sets the {@code security} and returns a reference to this Builder so that the methods can be chained
         * together.
         *
         * @param security the {@code security} to set
         * @return a reference to this Builder
         */
        public Builder security(String security) {
            this.security = security;
            return this;
        }

        /**
         * Sets the {@code type} and returns a reference to this Builder so that the methods can be chained
         * together.
         *
         * @param type the {@code security} to set
         * @return a reference to this Builder
         */
        public Builder type(String type) {
            this.type = type;
            return this;
        }

        /**
         * Sets the {@code applicableLevel} and returns a reference to this Builder so that the methods can be chained
         * together.
         *
         * @param applicableLevel the {@code applicableLevel} to set
         * @return a reference to this Builder
         */
        public Builder applicableLevel(String applicableLevel) {
            this.applicableLevel = applicableLevel;
            return this;
        }

        /**
         * Returns a {@code Endpoint} built from the parameters previously set.
         *
         * @return a {@code Endpoint} built with parameters of this {@code Endpoint.Builder}
         */
        public Endpoint build() {
            return new Endpoint(this);
        }

        public Builder config(String config) {
            this.config = config;
            return this;
        }
    }

    /**
     * Indicates whether some other object is "equal to" this one.
     *

     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     *

     *
It is reflexive: for any non-null reference value
     * {@code x}, {@code x.equals(x)} should return
     * {@code true}.
     *
It is symmetric: for any non-null reference values
     * {@code x} and {@code y}, {@code x.equals(y)}
     * should return {@code true} if and only if
     * {@code y.equals(x)} returns {@code true}.
     *
It is transitive: for any non-null reference values
     * {@code x}, {@code y}, and {@code z}, if
     * {@code x.equals(y)} returns {@code true} and
     * {@code y.equals(z)} returns {@code true}, then
     * {@code x.equals(z)} should return {@code true}.
     *
It is consistent: for any non-null reference values
     * {@code x} and {@code y}, multiple invocations of
     * {@code x.equals(y)} consistently return {@code true}
     * or consistently return {@code false}, provided no
     * information used in {@code equals} comparisons on the
     * objects is modified.
     *
For any non-null reference value {@code x},
     * {@code x.equals(null)} should return {@code false}.
     *

     *

     * The {@code equals} method for class {@code Object} implements
     * the most discriminating possible equivalence relation on objects;
     * that is, for any non-null reference values {@code x} and
     * {@code y}, this method returns {@code true} if and only
     * if {@code x} and {@code y} refer to the same object
     * ({@code x == y} has the value {@code true}).
     *

     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.
     *
     * @param obj the reference object with which to compare.
     * @return {@code true} if this object is the same as the obj
     * argument; {@code false} otherwise.
     * @see #hashCode()
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Endpoint endpoint = (Endpoint) obj;
        return Objects.equals(endpoint.id, id) &&
                Objects.equals(endpoint.endpointConfig, endpointConfig) &&
                Objects.equals(endpoint.security, security) &&
                Objects.equals(endpoint.maxTps, maxTps) &&
                Objects.equals(endpoint.name, name) &&
                Objects.equals(endpoint.type, type) &&
                Objects.equals(endpoint.applicableLevel, applicableLevel);
    }

    @Override
    public int hashCode() {
        int result = id.hashCode();
        return result;
    }

    public String getConfig() {
        return config;
    }

}


text:
import os
from typing import List

from celery.schedules import crontab

import conductor

from .conf import config

config.load()

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)

SECRET_KEY = "y$l*8=9d0b^nbf4c#vs+z=d)vb(3rsgvcx!+2as@f5f2s*#x=q"

DEBUG = config.DEBUG

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "conductor",
        "USER": "conductor",
        "PASSWORD": "conductor",
        "HOST": "127.0.0.1",
    }
}

ALLOWED_HOSTS: List[str] = []

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.postgres",
    "anymail",
    "localflavor",
    "storages",
    "waffle",
    "conductor.accounts.apps.AccountsConfig",
    "conductor.core.apps.CoreConfig",
    "conductor.planner.apps.PlannerConfig",
    "conductor.support.apps.SupportConfig",
    "conductor.trackers.apps.TrackersConfig",
    "conductor.vendor.apps.VendorConfig",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "rollbar.contrib.django.middleware.RollbarNotifierMiddleware",
    "waffle.middleware.WaffleMiddleware",
]

ROOT_URLCONF = "conductor.urls"

conductor_dir = os.path.dirname(conductor.__file__)
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(conductor_dir, "templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ]
        },
    }
]

WSGI_APPLICATION = "conductor.wsgi.application"

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"  # noqa
    },
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]

CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SESSION_COOKIE_SECURE = True
X_FRAME_OPTIONS = "DENY"

AUTH_USER_MODEL = "accounts.User"
LOGIN_REDIRECT_URL = "/app/"
LOGOUT_REDIRECT_URL = "/accounts/login/"

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_ROOT = os.path.join(conductor_dir, "static")
STATIC_URL = "/static/"
STATICFILES_DIRS = [os.path.join(ROOT_DIR, "assets")]
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

MEDIA_ROOT = "media"
MEDIA_URL = "/media/"

# The Sites framework is overkill. Set protocol+domain so Celery can make full links.
DOMAIN = ""

CELERY_BROKER_URL = "amqp://conductor:conductor@localhost:5672/conductor"
CELERY_BEAT_SCHEDULE = {
    "common-app-scan": {
        "task": "conductor.trackers.tasks.scan_common_app_schools",
        "schedule": crontab(day_of_week=0, hour=2, minute=0),
    },
    "prompt-scan": {
        "task": "conductor.vendor.tasks.scan_prompt",
        "schedule": crontab(day_of_week=0, hour=3, minute=0),
    },
}

ROLLBAR = {
    "access_token": "rollbar_access_token",
    "environment": "development",
    "root": BASE_DIR,
    "enabled": False,
}

CONDUCTOR_EMAIL = "matt@conductor.test"
EMAIL_BACKEND = "django.core.mail.backends.dummy.EmailBackend"
DEFAULT_FROM_EMAIL = '"College Conductor" <noreply@mail.collegeconductor.com>'
ANYMAIL = {"MAILGUN_API_KEY": "mailgun_api_key"}

STRIPE_API_KEY = "sk_test_fake_key"
STRIPE_PUBLISHABLE_KEY = "pk_test_fake_key"

GOOGLE_CLIENT_CONFIG = {
    "web": {
        "project_id": "",
        "client_id": "",
        "client_secret": "",
        "redirect_uris": [""],
        "auth_uri": "https://testserver",
        "token_uri": "",
    }
}

WAFFLE_FLAG_MODEL = "core.Flag"

# Override development settings with a secrets file.
try:
    from ._secrets import *  # noqa
except ImportError:
    pass


text:
Simple tool for generating id attribute for every element in android layout.

> This utility was written especially for testing department, where they needed to target element by ID, but problem was that MVVM based app, uses binding instead of ids.

## What it does
The application logic is very simple. It basicly iterates through every element in xml layout file and adds id to every element which doesn't have one. Id format is [ElementName][Increment], e.g. LinearLayout1.

<img src="https://github.com/ThommyB/Idnator/blob/master/code.PNG">


text:
package io.netty.handler.codec.http2;

import io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName;
import io.netty.util.ByteString;
import org.junit.Test;

import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;

import static io.netty.util.ByteString.fromAscii;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class DefaultHttp2HeadersTest {

    @Test
    public void pseudoHeadersMustComeFirstWhenIterating() {
        Http2Headers headers = newHeaders();

        verifyPseudoHeadersFirst(headers);
        verifyAllPseudoHeadersPresent(headers);
    }

    @Test
    public void pseudoHeadersWithRemovePreservesPseudoIterationOrder() {
        Http2Headers headers = newHeaders();

        Set<ByteString> nonPseudoHeaders = new HashSet<ByteString>(headers.size());
        for (Entry<ByteString, ByteString> entry : headers) {
            if (entry.getKey().isEmpty() || entry.getKey().byteAt(0) != ':') {
                nonPseudoHeaders.add(entry.getKey());
            }
        }

        // Remove all the non-pseudo headers and verify
        for (ByteString nonPseudoHeader : nonPseudoHeaders) {
            assertTrue(headers.remove(nonPseudoHeader));
            verifyPseudoHeadersFirst(headers);
            verifyAllPseudoHeadersPresent(headers);
        }

        // Add back all non-pseudo headers
        for (ByteString nonPseudoHeader : nonPseudoHeaders) {
            headers.add(nonPseudoHeader, fromAscii("goo"));
            verifyPseudoHeadersFirst(headers);
            verifyAllPseudoHeadersPresent(headers);
        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void testHeaderNameValidation() {
        Http2Headers headers = newHeaders();

        headers.add(fromAscii("Foo"), fromAscii("foo"));
    }

    private static void verifyAllPseudoHeadersPresent(Http2Headers headers) {
        for (PseudoHeaderName pseudoName : PseudoHeaderName.values()) {
            assertNotNull(headers.get(pseudoName.value()));
        }
    }

    private static void verifyPseudoHeadersFirst(Http2Headers headers) {
        ByteString lastNonPseudoName = null;
        for (Entry<ByteString, ByteString> entry: headers) {
            if (entry.getKey().isEmpty() || entry.getKey().byteAt(0) != ':') {
                lastNonPseudoName = entry.getKey();
            } else if (lastNonPseudoName != null) {
                fail("All pseudo headers must be fist in iteration. Pseudo header " + entry.getKey() +
                        " is after a non pseudo header " + lastNonPseudoName);
            }
        }
    }

    private static Http2Headers newHeaders() {
        Http2Headers headers = new DefaultHttp2Headers();
        headers.add(fromAscii("name1"), fromAscii("value1"), fromAscii("value2"));
        headers.method(fromAscii("POST"));
        headers.add(fromAscii("2name"), fromAscii("value3"));
        headers.path(fromAscii("/index.html"));
        headers.status(fromAscii("200"));
        headers.authority(fromAscii("netty.io"));
        headers.add(fromAscii("name3"), fromAscii("value4"));
        headers.scheme(fromAscii("https"));
        return headers;
    }
}


text:
/* Annotated CSS for DebuggingModelRenderer.java */
@url activeBreakpointBorderUrl breakpointGutterActiveResource;
@url inactiveBreakpointBorderUrl breakpointGutterInactiveResource;

.breakpoint {
  position: absolute;
  left: 0;
  right: 0;
  margin: 0 -5px;
  height: editorLineHeight;
  border-width: 0 18px 0 2px;
  border-image: activeBreakpointBorderUrl 0 18 0 2;
  -webkit-border-image: activeBreakpointBorderUrl 0 18 0 2;
  -moz-border-image: activeBreakpointBorderUrl 0 18 0 2;
  z-index: -2;
}

.breakpointInactive {
  border-image: inactiveBreakpointBorderUrl 0 18 0 2;
  -webkit-border-image: inactiveBreakpointBorderUrl 0 18 0 2;
  -moz-border-image: inactiveBreakpointBorderUrl 0 18 0 2;
}

.executionLine {
  position: absolute;
  left: 0;
  right: 0;
  height: editorLineHeight;
  background-color: #ABBFFE;
  outline: 1px solid #4073F4;
  z-index: -1;
}

@sprite .gutterExecutionLine {
  gwt-image: "gutterExecutionLine";
  background-position: -1px 1px;
  position: absolute;
  height: editorLineHeight;
  z-index: -1;
}


text:
package module4;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.data.Feature;
import de.fhpotsdam.unfolding.data.GeoJSONReader;
import de.fhpotsdam.unfolding.data.PointFeature;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.AbstractShapeMarker;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.marker.MultiMarker;
import de.fhpotsdam.unfolding.providers.Google;
import de.fhpotsdam.unfolding.providers.MBTilesMapProvider;
import de.fhpotsdam.unfolding.utils.MapUtils;
import parsing.ParseFeed;
import processing.core.PApplet;

/** EarthquakeCityMap
 * An application with an interactive map displaying earthquake data.
 * Author: UC San Diego Intermediate Software Development MOOC team
 * @author Your name here
 * Date: July 17, 2015
 * */
public class EarthquakeCityMap extends PApplet {

	// We will use member variables, instead of local variables, to store the data
	// that the setUp and draw methods will need to access (as well as other methods)
	// You will use many of these variables, but the only one you should need to add
	// code to modify is countryQuakes, where you will store the number of earthquakes
	// per country.

	// You can ignore this.  It's to get rid of eclipse warnings
	private static final long serialVersionUID = 1L;

	// IF YOU ARE WORKING OFFILINE, change the value of this variable to true
	private static final boolean offline = false;

	/** This is where to find the local tiles, for working without an Internet connection */
	public static String mbTilesString = "blankLight-1-3.mbtiles";

	//feed with magnitude 2.5+ Earthquakes
	private String earthquakesURL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.atom";

	// The files containing city names and info and country names and info
	private String cityFile = "city-data.json";
	private String countryFile = "countries.geo.json";

	// The map
	private UnfoldingMap map;

	// Markers for each city
	private List<Marker> cityMarkers;
	// Markers for each earthquake
	private List<Marker> quakeMarkers;

	// A List of country markers
	private List<Marker> countryMarkers;

	public void setup() {
		// (1) Initializing canvas and map tiles
		size(1800, 1400, OPENGL);
		if (offline) {
		    map = new UnfoldingMap(this, 200, 50, 650, 600, new MBTilesMapProvider(mbTilesString));
		    earthquakesURL = "2.5_week.atom";  // The same feed, but saved August 7, 2015
		}
		else {
			map = new UnfoldingMap(this, 200, 50, 1300, 1200, new Google.GoogleMapProvider());
			// IF YOU WANT TO TEST WITH A LOCAL FILE, uncomment the next line
		    //earthquakesURL = "2.5_week.atom";
		}
		MapUtils.createDefaultEventDispatcher(this, map);

		// FOR TESTING: Set earthquakesURL to be one of the testing files by uncommenting
		// one of the lines below.  This will work whether you are online or offline
		//earthquakesURL = "test1.atom";
		//earthquakesURL = "test2.atom";

		// WHEN TAKING THIS QUIZ: Uncomment the next line
		//earthquakesURL = "quiz1.atom";

		// (2) Reading in earthquake data and geometric properties
	    //     STEP 1: load country features and markers
		List<Feature> countries = GeoJSONReader.loadData(this, countryFile);
		countryMarkers = MapUtils.createSimpleMarkers(countries);

		//     STEP 2: read in city data
		List<Feature> cities = GeoJSONReader.loadData(this, cityFile);
		cityMarkers = new ArrayList<Marker>();
		for(Feature city : cities) {
		  cityMarkers.add(new CityMarker(city));
		}

		//     STEP 3: read in earthquake RSS feed
	    List<PointFeature> earthquakes = ParseFeed.parseEarthquake(this, earthquakesURL);
	    quakeMarkers = new ArrayList<Marker>();

	    for(PointFeature feature : earthquakes) {
		  //check if LandQuake
		  if(isLand(feature)) {
		    quakeMarkers.add(new LandQuakeMarker(feature));
		  }
		  // OceanQuakes
		  else {
		    quakeMarkers.add(new OceanQuakeMarker(feature));
		  }
	    }

	    // could be used for debugging
	    printQuakes();

	    // (3) Add markers to map
	    //     NOTE: Country markers are not added to the map.  They are used
	    //           for their geometric properties
	    map.addMarkers(quakeMarkers);
	    map.addMarkers(cityMarkers);

	}  // End setup

	public void draw() {
		background(0);
		map.draw();
		addKey();

	}

	// helper method to draw key in GUI
	// TODO: Update this method as appropriate
	private void addKey() {
		// Remember you can use Processing's graphics methods here
		fill(255, 250, 240);
		rect(25, 50, 150, 600);

		fill(0);
		textAlign(LEFT, CENTER);
		textSize(12);
		text("Earthquake Key", 50, 75);

		//fill(color(255, 0, 0));
		//ellipse(50, 125, 15, 15);
		fill(color(255, 255, 255));
		ellipse(50, 125, 10, 10);
		fill(color(255, 255, 255));
		rect(50, 175, 10, 10);
		fill(0, 255, 0);
		triangle(55, 225, 50, 235, 60, 235);
		fill(255, 255, 0);
		ellipse(50, 325, 10, 10);
		fill(0, 0, 255);
		ellipse(50, 375, 10, 10);
		fill(255, 0, 0);
		ellipse(50, 425, 10, 10);
		fill(255,255,255);
		ellipse(50, 475, 10, 10);
		line(45, 470, 55, 480);
		line(45, 480, 55, 470);

		fill(0, 0, 0);
		//text("5.0+ Magnitude", 75, 125);
		text("Land Quake", 75, 125);
		text("Ocean Quake", 75, 175);
		text("Cities", 75, 225);
		text("Size ~ Magnitude", 50, 275);
		text("Shallow", 75, 325);
		text("Intermediate", 75, 375);
		text("Deep", 75, 425);
		text("Past Day Earthquake", 75, 475);
	}

	// Checks whether this quake occurred on land.  If it did, it sets the
	// "country" property of its PointFeature to the country where it occurred
	// and returns true.  Notice that the helper method isInCountry will
	// set this "country" property already.  Otherwise it returns false.
	private boolean isLand(PointFeature earthquake) {

		// IMPLEMENT THIS: loop over all countries to check if location is in any of them

		// TODO: Implement this method using the helper method isInCountry
		for (Marker countryMarker : countryMarkers){
			if(isInCountry(earthquake, countryMarker)){
				return true;
			}
		}
		// not inside any country
		return false;
	}

	// prints countries with number of earthquakes
	// You will want to loop through the country markers or country features
	// (either will work) and then for each country, loop through
	// the quakes to count how many occurred in that country.
	// Recall that the country markers have a "name" property,
	// And LandQuakeMarkers have a "country" property set.
	private void printQuakes()
	{
		// TODO: Implement this method
		HashMap<String, Integer> hm = new HashMap<String, Integer>();
		int oceanquakes = 0;
		for (Marker earthquake : quakeMarkers){
			if (((EarthquakeMarker)earthquake).isOnLand()){
				String country = (String)((LandQuakeMarker)earthquake).getProperty("country");
				//System.out.println("Found earthquake on country " + country);
				if (hm.containsKey(country)){
					hm.put(country, hm.get(country)+1);
				}
				else {
					hm.put(country, 1);
				}
			}
			else {
				oceanquakes++;
			}
		}
		Set hmSet = hm.entrySet();
		//System.out.println(hmSet.size());
		Iterator it = hmSet.iterator();
		while(it.hasNext()){
			Map.Entry<String, Integer> mentry = (Map.Entry<String, Integer>)it.next();
			System.out.println("Country " + mentry.getKey() + " has " + mentry.getValue() + " earthquakes");
		}
		System.out.println("There were " + oceanquakes + " number of earthquakes on water");
	}

	// helper method to test whether a given earthquake is in a given country
	// This will also add the country property to the properties of the earthquake
	// feature if it's in one of the countries.
	// You should not have to modify this code
	private boolean isInCountry(PointFeature earthquake, Marker country) {
		// getting location of feature
		Location checkLoc = earthquake.getLocation();

		// some countries represented it as MultiMarker
		// looping over SimplePolygonMarkers which make them up to use isInsideByLoc
		if(country.getClass() == MultiMarker.class) {

			// looping over markers making up MultiMarker
			for(Marker marker : ((MultiMarker)country).getMarkers()) {

				// checking if inside
				if(((AbstractShapeMarker)marker).isInsideByLocation(checkLoc)) {
					earthquake.addProperty("country", country.getProperty("name"));

					// return if is inside one
					return true;
				}
			}
		}

		// check if inside country represented by SimplePolygonMarker
		else if(((AbstractShapeMarker)country).isInsideByLocation(checkLoc)) {
			earthquake.addProperty("country", country.getProperty("name"));

			return true;
		}
		return false;
	}

}


text:
<?php

require_once dirname(__FILE__) . '/../../../../tools/helpers/bookstore/BookstoreTestBase.php';

/**
 * Tests for NestedSetBehavior class
 *
 * @author		François Zaninotto
 * @version		$Revision$
 * @package		generator.behavior.nestedset
 */
class NestedSetBehaviorTest extends BookstoreTestBase
{
    public function testDefault()
    {
        $table9 = Table9Peer::getTableMap();
        $this->assertEquals(count($table9->getColumns()), 5, 'nested_set adds three column by default');
        $this->assertTrue(method_exists('Table9', 'getTreeLeft'), 'nested_set adds a tree_left column by default');
        $this->assertTrue(method_exists('Table9', 'getLeftValue'), 'nested_set maps the left_value getter with the tree_left column');
        $this->assertTrue(method_exists('Table9', 'getTreeRight'), 'nested_set adds a tree_right column by default');
        $this->assertTrue(method_exists('Table9', 'getRightValue'), 'nested_set maps the right_value getter with the tree_right column');
        $this->assertTrue(method_exists('Table9', 'getTreeLevel'), 'nested_set adds a tree_level column by default');
        $this->assertTrue(method_exists('Table9', 'getLevel'), 'nested_set maps the level getter with the tree_level column');
        $this->assertFalse(method_exists('Table9', 'getTreeScope'), 'nested_set does not add a tree_scope column by default');
        $this->assertFalse(method_exists('Table9', 'getScopeValue'), 'nested_set does not map the scope_value getter with the tree_scope column by default');

    }

    public function testParameters()
    {
        $table10 = Table10Peer::getTableMap();
        $this->assertEquals(count($table10->getColumns()), 6, 'nested_set does not add columns when they already exist');
        $this->assertTrue(method_exists('Table10', 'getLeftValue'), 'nested_set maps the left_value getter with the tree_left column');
        $this->assertTrue(method_exists('Table10', 'getRightValue'), 'nested_set maps the right_value getter with the tree_right column');
        $this->assertTrue(method_exists('Table10', 'getLevel'), 'nested_set maps the level getter with the tree_level column');
        $this->assertTrue(method_exists('Table10', 'getScopeValue'), 'nested_set maps the scope_value getter with the tree_scope column when the use_scope parameter is true');
    }

}


text:
import com.zkay.Listing1_4.{Account, Balance}
import org.specs2.mutable.Specification

class Listing1_4Spec extends Specification {
  "should properly track balance" in {
    val a = new Account("a1", "John")
    a.balance must beEqualTo(Balance(0))
    a.credit(100)
    a.balance must beEqualTo(Balance(100))
    a.debit(20)
    a.balance must beEqualTo(Balance(80))
  }

  "should blow up if balance handled incorrectly" in {
    val a = new Account("a1", "John")
    a.balance must beEqualTo(Balance(0))
    a.credit(100)
    a.balance must beEqualTo(Balance(100))
    a.balance = Balance(0)
    a.balance must beEqualTo(Balance(0))
    a.debit(1000) must throwA[Exception]
  }
}


text:
package com.github.TKnudsen.ComplexDataObject.model.processors.complexDataObject;

import java.util.Arrays;
import java.util.List;

import com.github.TKnudsen.ComplexDataObject.data.complexDataObject.ComplexDataContainer;
import com.github.TKnudsen.ComplexDataObject.data.complexDataObject.ComplexDataObject;
import com.github.TKnudsen.ComplexDataObject.model.io.parsers.objects.DoubleParser;

public class AttributeDivision implements IComplexDataObjectProcessor {

	private final String dividend;
	private final String divisor;
	private final String targetAttributeName;

	private final DoubleParser doubleParser;

	public AttributeDivision(String dividend, String divisor, String targetAttributeName) {
		this(dividend, divisor, targetAttributeName, false);
	}

	public AttributeDivision(String dividend, String divisor, String targetAttributeName, boolean dotMeansThousands) {
		this.dividend = dividend;
		this.divisor = divisor;
		this.targetAttributeName = targetAttributeName;

		doubleParser = new DoubleParser(dotMeansThousands);
	}

	@Override
	public void process(List<ComplexDataObject> data) {
		for (ComplexDataObject cdo : data) {

			if (cdo == null)
				return;

			double value = Double.NaN;

			Object dividendObject = cdo.getAttribute(dividend);
			Object divisorObject = cdo.getAttribute(divisor);

			try {
				Double dividendValue = doubleParser.apply(dividendObject);
				Double divisorValue = doubleParser.apply(divisorObject);
				value = dividendValue / divisorValue;
			} catch (Exception e) {
			}

			cdo.add(targetAttributeName, value);
		}
	}

	@Override
	public void process(ComplexDataContainer container) {
		for (ComplexDataObject complexDataObject : container)
			process(Arrays.asList(complexDataObject));
	}

	@Override
	public DataProcessingCategory getPreprocessingCategory() {
		return DataProcessingCategory.SECONDARY_DATA_PROVIDER;
	}

}


text:
require 'simplecov'
SimpleCov.start do
  add_group "Lib", "lib"
end
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))

require 'acts_as_decimal'
require 'active_record'
require 'rspec'
ActiveSupport::Deprecation.silenced = true

ActiveRecord::Base.establish_connection(
  :adapter => 'sqlite3',
  :database => ':memory:'
)

ActiveRecord::Schema.define do
  create_table :products do |t|
    t.string     :name
    t.integer    :price
  end
end

class Product < ActiveRecord::Base
end


text:
<!doctype html>

  <link rel="stylesheet" href="http://cdn.jsdelivr.net/foundation/4.3.2/css/foundation.min.css">

  <form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate>

      <input type="text"
             name="dynamic_input"
             ng-required="field.isRequired"
             ng-model="field.name"
             placeholder="{{field.placeholder}}" />

        The field is required.

    <button type="submit" ng-disabled="signup_form.$invalid">Submit All</button>
  </form>


text:
package instance

import (
	"net/http"

	"github.com/pivotal-pez/cfmgo"
	"github.com/pivotal-pez/haas-broker/handlers"
)

type (
	//InstanceCreator - a type which can handle creating service instance requests
	InstanceCreator struct {
		Collection cfmgo.Collection
		Dispenser  handlers.DispenserCreds
		ClientDoer clientDoer
		Model      InstanceModel
	}
	//InstanceModel - persistence model struct
	InstanceModel struct {
		InstanceID       string
		OrganizationGUID string                 `json:"organization_guid"`
		PlanID           string                 `json:"plan_id"`
		ServiceID        string                 `json:"service_id"`
		SpaceGUID        string                 `json:"space_guid"`
		Parameters       map[string]interface{} `json:"parameters"`
		TaskGUID         string
		RequestID        string
	}
	clientDoer interface {
		Do(req *http.Request) (resp *http.Response, err error)
	}
)


text:
`metrics-clojure` is now based on [Metrics 3.1.0](https://groups.google.com/forum/#!topic/metrics-user/zwzHnMBcAX4).

### Improve ring instrumentation.

`metrics-clojure-ring` now instruments the scheme of requests, (http or https).

Contributed by Jason Whitlark.

## Changes Between 2.2.x and 2.3.0

### Enhanced Timers

`metrics.timers` now provides two new functions, `start` and `stop`.

Contributed by Jason Whitlark.

### metrics.health

`metrics-clojure-health` is a new sub-project that makes implementing
[health checks](http://metrics.codahale.com/manual/healthchecks/) easier in Clojure.

Contributed by Jason Whitlark.

### Ganglia Reporter

`metrics-clojure-ganglia` is a new sub-project that makes using the Ganglia
reporter easier from Clojure.

Contributed by Jason Whitlark.

### CSV Reporter

CSV reporter is now provided in `metrics.reporters.csv`.

Contributed by Jason Whitlark.

### JMX Reporter

JMX reporter is now provided in `metrics.reporters.jmx`.

Contributed by Jason Whitlark.

### Stop Function for Reporter

All reporter namespace now provide a new function, `stop`, that stops
their respective reporter.

Contributed by Jason Whitlark.

### Graphite Reporter API in Line With the Console One

`metrics.reporters.graphite/start` is a function that starts the reporter,
just like other reporter namespaces (e.g. console) do.

Contributed by Jason Whitlark.

### Graphite and Console Reporters Documentation Improvements

Contributed by Jason Whitlark.

## Changes Between 2.1.x and 2.2.0

### Graphite Extension

`metrics.reporters.graphite` is a new sub-project that contains
a Graphite reporter.

### Ring Extension Now Respects User-provided Registry

The Ring extension now respects user-provided registries
instead of always using the default one.

Contributed by David Smith.

### Bugfixes

- Fixed `metrics.core/default-registry` to have a valid reflection
  hint (no longer causes compile error when used in interop.) Fix
  planned on 2.1.x as well. Contributed by Tim McCormack.

## Changes Between 2.0.x and 2.1.0

### Ring Extension Supports Multiple Registries and Options

It is now possible to use `metrics.ring.expose` with a custom
registry:

``` clojure
(require '[metrics.ring.expose :refer [expose-metrics-as-json]])

(expose-metrics-as-json ring-app "/ops/metrics" registry {:pretty-print? true})
```

### JVM Instrumentation Extension

The project now also has a JVM instrumentation extension that covers:

 * Number of threads and their states
 * GC stats, heap, off heap memory
 * File descriptors

To enable full instrumenting, use

``` clojure
(require '[metrics.jvm.core :refer [instrument-jvm]])

(instrument-jvm metric-registry)
```

Contributed by John Cowie (ThoughtWorks).

### timers/mean Returns Value (Not Rate)

`metrics.timers/mean` now returns mean value (not rate)
of the timer.

Contributed by Steve Miner.

### Ring Extension Updated for 2.0

The Ring extension is now updated for Metrics core 2.0 API.

Contributed by John Cowie (ThoughtWorks).

## Changes Between 1.1.0 and 2.0.0

### Metrics Registries

`metrics-clojure` 1.x maintained a metrics registry in a dynamic var.
This approach makes the library a little easier for beginners but
also much harder to use in more sophisticated cases, e.g. in concurrent
applications or those that use a Component-like approach to
program structure.

As such, `metrics-clojure` 2.0+ makes metrics registry a required
explicit argument to most functions in the API:

``` clojure
(require '[metrics.meters :as meters])

;; with 1.x
(meters/rate-mean)
(meters/mark! 10)

;; with 2.0
(let [m (meters/meter ["test" "meters" "test-rate-mean-update-multiple"])]
  (meters/rate-mean m)
  (meters/mark! m 10))
```

The library maintains a default registry in `metrics.core/default-registry`
which tries to keep the `1.x` API as functional as possible but using
your own registry is encouraged.

To instantiate a registry, use `metrics.core/new-registry`:

``` clojure
(require '[metrics.core :as mtr])

(mtr/new-registry)
```

See [GH #19](https://github.com/sjl/metrics-clojure/issues/19) for
discussion.

### defgauge Restricted to Functions Only

In `metrics-clojure` 1.x, `metrics.gauges/defgauge` could accept
a function or a bunch of forms (body). In 2.0, it only accepts
a function. This is in part due to the new API structure but also
make the API more straightforward and works much better with explicit
registry management now advocated by the library.

### Nanoseconds Precision in Timers

Metrics 3.0 uses nanoseconds precision in timers.

### Upgrade to Metrics 3.0

Metrics 3.0 is now used internally by the library.

### Clojure 1.3 No Longer Supported

Clojure 1.3 is no longer supported by the library.

## Changes Between 1.0.0 and 1.1.0

### Support for TRACE, OPTION, CONNECT HTTP Verbs

Ring integration now tracks rates of requests that use TRACE, OPTION,
CONNECT, and non-standard HTTP verbs.

Contributed by Joe Littlejohn (Nokia).

### Clojure 1.6

The project now depends on `org.clojure/clojure` version `1.6.0`. It is
still compatible with Clojure 1.4 and if your `project.clj` depends on
a different version, it will be used, but 1.6 is the default now.

### Cheshire 5.3

The project now uses [Cheshire](https://github.com/dakrone/cheshire) 5.3.


text:
{-# LANGUAGE GADTs #-}

module Test.Utils
  ( Test(..)
  , runTest, runTests
  ) where

import System.Exit ( exitFailure )

import Test.QuickCheck

data Test where
  Test :: (Testable p) => String -> p -> Test

runTests :: [Test] -> IO ()
runTests = sequence_ . fmap runTest

runTest :: Test -> IO ()
runTest (Test name p) = do
  putStrLn $ "+++ " ++ name
  res <- quickCheckResult p
  case res of
    Success {} -> return ()
    GaveUp {}  -> return ()
    _ -> exitFailure


text:
<?php

namespace Ongoing;

class UpdateOrderIdentificationType
{
    const __default = 'GoodsOwnerOrderNumber';
    const GoodsOwnerOrderNumber = 'GoodsOwnerOrderNumber';
    const ReferenceNumber = 'ReferenceNumber';
    const SystemId = 'SystemId';
    const GoodsOwnerOrderId = 'GoodsOwnerOrderId';

}