text:
title: Teraslice Op Test Harness
sidebar_label: Overview
---

> A testing harness to simplify testing Teraslice processors and operations.

**DEPRECRATED**: Use [teraslice-test-harness](../pacakges/teraslice-test-harness) instead.

This project provides a processor execution function called `run()`, test data
sources and common test functions to help you implement tests of your Teraslice
operations.

To start using it, require your processor and then pass it in as an argument to
the harness module as shown below.  The code examples below assume you are using
the harness in a `test/` or `test/` subdirectory and your processor is
implemented in `../index.js`, adjust paths accordingly.

```js
var processor = require('../index');
var harness = require('@terascope/teraslice-op-test-harness')(processor);
```

Now, you can access functionality using the `harness` object.

## Processor Execution Function - `init()`

The manner to instanciate a new instance of your operation is by using init
You make pass in optional clients under the `clients` key but they must follow the format listed in the setClients definition. This will work with both the new and old Job APIs.

```js
const { DataEntity } = require('@terascope/job-components');
const processor = require('../asset/example-op');
const reader = require('../asset/example-reader');

describe('setting up an operation', () => {
    const processorOpTest = opHarness(processor);
    const readerOpTest = opHarness(reader);
    let client;

    class MockClient {
        async get(data) { return data }
    }

    beforeEach(() => {
        client = new MockClient();
        readerOpTest.setClients([
            { client, type: 'elasticsearch', endpoint: 'default' }
        ]);
    });

    it('can make a processor instance', async () => {
        const opConfig = { _op: 'foo', some: 'config' };
        const data = { some: 'data' };
        const pTest = await processorOpTest.init({ opConfig });

        const results = await pTest.run(data);

        expect(Array.isArray(results)).toBe(true);
        expect(DataEntity.isDataEntity(results[0])).toBe(true);
    });

    it('can make a reader instance', async () => {
        const executionConfig = {
            lifecycle: 'once',
            operations: [{ _op: 'foo', some: 'config' }]
        };
        const data = { some: 'data' };
        const type = 'reader';
        const rTest = await readerOpTest.init({ executionConfig, type });

        const results = await rTest.run(data);

        expect(Array.isArray(results)).toBe(true);
        expect(results[0] instanceof DataEntity).toBe(true);
    });

    it('can make a slicer instance', async () => {
        const executionConfig = {
            lifecycle: 'once',
            operations: [{ _op: 'foo', some: 'config' }]
        };
        // type defaults to slicer
        const sTest = await readerOpTest.init({ executionConfig });

        const results = await sTest.run();

        expect(Array.isArray(results)).toBe(true);
        expect(results[0]).toEqual({ foo: 'bar' });
    });

    it('can make a multiple slicer instances', async () => {
        const executionConfig = {
            lifecycle: 'once',
            slicers: 3,
            operations: [{ _op: 'foo', some: 'config' }]
        };

        // type defaults to slicer
        const sTest = await readerOpTest.init({ executionConfig });

        const results = await sTest.run();

        expect(Array.isArray(results)).toBe(true);
        expect(results[0]).toEqual({ foo: 'bar' });
    });

    it('can return the full metadata of slice', async () => {
        const executionConfig = {
            lifecycle: 'once',
            slicers: 3,
            operations: [{ _op: 'foo', some: 'config' }]
        };

        // type defaults to slicer
        const sTest = await readerOpTest.init({ executionConfig });

        const results = await sTest.run({ fullSlice: true });

        expect(Array.isArray(results)).toBe(true);
        expect(results[0]).toEqual({
            slice_id: 'd994d423-f3a3-411d-8973-4a4ccccd1afd',
            slicer_id: 0,
            slicer_order: 10,
            request: { foo: 'bar' }
        });
    });
})
```

## Processor Execution Function - `setClients()`

This takes an array of client configurations that will be used internally.
The obejct must have a client key and a type key set.

```js
const { DataEntity } = require('@terascope/job-components');
const reader = require('../asset/example-reader');

describe('setting up an operation', () => {
    const opTest = opHarness(reader);
    let client;
    let client2;
    let client3;

    class MockClient {
        async get(data) { return data }
    }

    class OtherClient {
        async get(data) { return 'something else' }
    }

    beforeEach(() => {
        client = new MockClient(); client2 = new MockClient();
        client3 = new MockClient();
        // endpoint defaults to 'default' if not specifed, but showing none the less
        readerOpTest.setClients([
            { client, type: 'elasticsearch', endpoint: 'default' },
            { client: client2, type: 'elasticsearch', endpoint: 'other_connection' },
            { client: client3, type: 'kafka' },
        ])
    });

    it('can make a reader instance', async () => {
        const executionConfig = {
            lifecycle: 'once',
            operations: [{ _op: 'foo', some: 'config' }]
        };
        const data = { some: 'data' };
        const type = 'reader';
        const test = await opTest.init({ executionConfig, type });

        const results = await test.run(data)

        expect(Array.isArray(results)).toBe(true);
        expect(DataEntity.isDataEntity(results[0])).toBe(true);
    });

    it('can make a slicer instance', async () => {
        const executionConfig = {
            lifecycle: 'once',
            operations: [{ _op: 'foo', some: 'config' }]
        };
        // you can override the clients at init time
        const clients = [{ client: new OtherClient(), type: 'elasticsearch', endpoint: 'default'}]
        // these two ops now have different clients at elasticsearch : default connection
        const test1 = await opTest.init({ executionConfig });
        const test2 = await opTest.init({ executionConfig, clients });

        const [results1, results2 ] = await Promise.all([ test1.run(), test2.run()]);

        expect(Array.isArray(results1)).toBe(true);
        expect(results1[0]).toEqual({ foo: 'bar' });

        expect(Array.isArray(results2)).toBe(true);
        expect(results2[0]).toEqual({ foo: 'bar' });
    });
})
```

## Processor Execution Function `processData()`

This provides a short hand for processors to instantiate a new operation, run some data with it and return the results.

```js
const processor = require('../asset/example-op');

describe('processor operation test', () => {
    const opTest = opHarness(processor);

    it('has a shorthand method', async () => {
        const opConfig = { _op: 'foo', some: 'config' };
        const data = [{ some: 'data' }];
        const results = await processorOpTest.processData(opConfig, data);

        expect(Array.isArray(results)).toBe(true);
        expect(DataEntity.isDataEntity(results[0])).toBe(true);
    })
})

```

## Processor Execution Function - `run()`  DEPRECIATED

The testing harness provides a function `run()`, that will run your processor on
the data you have passed in to the run function.  The `run()` function returns
the output data from your processor so you can confirm that it behaved the way
you expected.  Generally speaking, using `harness.run()` looks like the example
below. The second argument passed to `run()`, `opConfig` is optional.

```js
var processor = require('../index');
var harness = require('@terascope/teraslice-op-test-harness')(processor);

var data = [];
var opConfig = {option: 3}
console.log(harness.run(data, opConfig));
```

The rest of the examples will be implemented as valid unit tests using the
[jasmine](https://jasmine.github.io) testing framework.  This is a convenient
way for you to develop and test your Teraslice operations without having to run
them in Teraslice directly.

The example below shows a processor that, using the default operation settings,
doesn't change the data in any way:

```js
var processor = require('../index');
var harness = require('@terascope/teraslice-op-test-harness')(processor);

describe('With data in is []', function() {
    it('data out is []', function() {
        var data = [];
        expect(harness.run(data)).toEqual(data);
    });
});
```

If you want to override the default operations used by your processor, you can
do so by passing in an `opConfig` object with the properties you want to change.
They will be merged into the default `opConfig` and validated automatically by
the test harness.  The example below shows the modification of the `percentage`
property on the operator:

```js
var processor = require('../index');
var harness = require('@terascope/teraslice-op-test-harness')(processor);

describe('The data doubles when', function() {
    var opConfig = {
        percentage: 100
    };

    it('using simple data and percentage is 100', function() {
        // prepare the data to test output data against
        var newData = [];
        harness.data.simple.forEach(function(item) {
            newData.push(item, item);
        });

        // run the operator, passing in input data and the overridden opConfig
        expect(harness.run(harness.data.simple, opConfig)).toEqual(newData);
    });
});
```

## Multiple calls to the same processor instance DEPRECIATED

If you need to test a processor that maintains some type of state across slices
you have two options:

### 1 Use `runSlices() -> Promise` DEPRECIATED

This will process all of the given slices, `emulateShutdown()`, then process a
final empty slice to give the processor a chance to flush its state.

```js
var processor = require('../sum');
var harness = require('@terascope/teraslice-op-test-harness')(processor);

describe('Add running total', function() {
    var opConfig = { src_field: 'x', dst_field: 'y' };
    it('works', function() {
        var slices = [ [{ x: 10 }, { x: 11 }], [{ x: 21 }] ];
        harness.runSlices(slices)
            .then((results) => {
                expect(results.length).toEqual(3);
                expect(results[0].y).toEqual([{ x: 10, y: 10 }, { x: 11, y: 21 }]);
                expect(results[1].y).toEqual([{ x: 21, y: 42 }]);
                expect(results[2].y).toEqual([]);
            });
    });
});
```

### 2. Create a processor instance to call `process()` independently DEPRECIATED

```js
var processor = require('../index');
var harness = require('@terascope/teraslice-op-test-harness')(processor);

describe('The data doubles when', function() {
    var opConfig = {
        percentage: 100
    };

    it('using simple data and percentage is 100', function() {
        var processor = harness.getProcessor(opConfig);

        // First call on the processor can use the input to setup state
        harness.run(processor, harness.data.simple)

        // Second call is using the same processor so if you setup state
        // it should still exist.
        expect(harness.run(processor, harness.data.simple)).toEqual(newData);
    });
});
```

## Async/Promise based processors DEPRECIATED

In some scenarios a processor will be asynchronous and needs to return a
promise.

```js
var processor = require('../index');
var harness = require('@terascope/teraslice-op-test-harness')(processor);

describe('The data doubles when', function() {
    var opConfig = {
        percentage: 100
    };

    it('using simple data and percentage is 100', function(done) {
        var processor = harness.getProcessor(opConfig);

        // First call on the processor can use the input to setup state
        harness.runAsync(processor, harness.data.simple)
            .then((result) => {
                    expect(result).toEqual(newData);
                    done();
                });
    });
});
```

## Data Sources

One of the main benefits of the testing harness is that it provides a consistent
set of testing data sources.  All of these objects are properties of the harness
in `data` property.  The following data sources are currently available:

* `data.simple` - A very small and simple array of JSON objects.
* `data.arrayLike` - An array of 10 "log like" JSON documents.
* `data.esLike` - The same 10 documents as `data.arrayLike`, but structured like
  an Elasticsearch query response.

These data sources can be used as the first argument to your processor in tests
as shown below.

```js
var processor = require('../index');
var harness = require('@terascope/teraslice-op-test-harness')(processor);

describe('The data doubles when', function() {
    it('using simple data and percentage is 100', function() {
        expect(harness.run(harness.data.simple)).toEqual(harness.data.simple);
    });
});
```

## Common Tests

The harness also provides a simple set of tests that can be used on any
processor.  These tests will ensure that the processor you have implemented
behaves as expected by Teraslice.

To use these tests, you can simply import the harness, then call,
`runProcessorSpecs()`, passing your processor in as an argument.  I recommend
you implement this as a stand-alone file named `harness_spec.js` in your spec
directory but it could be included at the top of another spec file.  Keeping it
separate might help call out the fact that these specs are different from the
tests you've implemented yourself because they come from somewhere else.

```js
'use strict';

var processor = require('../index');
var harness = require('@terascope/teraslice-op-test-harness')(processor);

// Run the tests provided by the harness
harness.runProcessorSpecs(processor);
```


text: /*Add your own styling here*/

redpajama_set_name: RedPajamaGithub


text:
const { resolve }  = require('path')
const nodeExternals = require('webpack-node-externals')
const NodemonPlugin = require( 'nodemon-webpack-plugin' ) // Ding

module.exports = {
  entry: resolve(__dirname, 'src', 'server'),
  target: 'node',
  externals: [ nodeExternals() ],
  output: {
    filename: 'bundle.js',
    path: resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          'babel-loader',
        ],
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    modules: [
      'src',
      'node_modules',
    ],
    extensions: [ '.js' ],
  },
  plugins: [
    new NodemonPlugin(),
  ],
}


text:
'''Admin interface for posts.
'''

from django.contrib import admin
from django.utils.translation import ugettext as _
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.contrib.comments.models import Comment, CommentFlag
from django.contrib.comments.admin import CommentsAdmin
from django import forms

from django.contrib.sites.models import Site

from sorl.thumbnail.admin import AdminImageMixin

from post.models import BasicPost, PostWithImage, PostWithSlideshow, \
                        PostWithSimpleImage, PostWithEmbeddedObject, \
                        SubmittedArticle, EditorChoice

from archive.admin import TaggedItemInline

from credit.admin import OrderedCreditInline

from relatedcontent.admin import RelatedContentInline

from enhancedtext.admin import enhancedtextcss, enhancedtextjs

post_fieldsets = (
        (_('Title'), {
            'classes' : ['grp-collapse grp-open'],
            'fields': ('title', 'subtitle','slug','date_published'),
        }),

        (_('Content'), {
         'classes' : ['grp-collapse grp-open',],
         'fields': ('body',)
        }),
        (_('Display features'), {
         'classes' : ['grp-collapse grp-open',],
         'fields': ('homepage','sticky', 'category', 'allow_comments', 'copyright')
        }),

        (_('Teaser. introduction and pullout text'), {
         'classes' : ['grp-collapse grp-closed',],
         'fields': ('teaser','introduction', 'pullout_text',)
        }),

        (_('HTML templates'), {
         'classes' : ['grp-collapse grp-closed',],
         'fields': (('detail_post_template','list_post_template',),
                    ('detail_post_css_classes','list_post_css_classes',))
        }),
        (_('Sites on which this post is published'), {
         'classes' : ['grp-collapse grp-closed',],
         'fields' : ('sites',)
        })
    )

class BasicPostAdmin(admin.ModelAdmin):
    search_fields = ('title', 'teaser', 'body')
    list_display = ('render_admin_url', 'title', 'describe_for_admin',
                    'date_published', 'category', 'homepage','is_published',
                    'date_added', 'last_modified')
    list_editable = ('title', 'date_published','category', 'homepage', )
    list_filter = ('date_published',)
    date_hierarchy = 'date_published'
    prepopulated_fields = {"slug": ("title",)}
    inlines = [OrderedCreditInline, TaggedItemInline, RelatedContentInline]
    ordering = ('-last_modified',)

    fieldsets = post_fieldsets

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == 'sites':
            kwargs["initial"]  = [Site.objects.get_current()]
        return super(BasicPostAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

    class Media:
        css = enhancedtextcss
        js = enhancedtextjs

class PostWithSimpleImageAdmin(AdminImageMixin, BasicPostAdmin):
    fieldsets = post_fieldsets[0:3] + \
        ((_('Image'), {
         'classes' : ['grp-collapse grp-open',],
         'fields': ('image', 'caption', 'url',)
        }),) + \
        post_fieldsets[3:]

class PostWithImageAdmin(BasicPostAdmin):
    #list_display = ('id', 'title', 'image_thumbnail', 'date_published', 'category', 'homepage','is_published', 'date_added', 'last_modified')
    raw_id_fields = ['image',]
    related_lookup_fields = {
        'fk': ['image'],
    }

    fieldsets = post_fieldsets[0:3] + \
        ((_('Image'), {
         'classes' : ['grp-collapse grp-open',],
         'fields': ('image',)
        }),) + \
        post_fieldsets[3:]

class PostWithSlideshowAdmin(BasicPostAdmin):
    #list_display = ('id', 'title', 'slideshow_thumbnail', 'date_published', 'category', 'homepage','is_published', 'date_added', 'last_modified')
    raw_id_fields = ['gallery',]
    related_lookup_fields = {
        'fk': ['gallery'],
    }

    fieldsets = post_fieldsets[0:3] + \
        ((_('Gallery to use for slideshow'), {
         'classes' : ['grp-collapse grp-open',],
         'fields': ('gallery', 'slideshow_options')
        }),) + \
        post_fieldsets[3:]

class PostWithEmbeddedObjectAdmin(BasicPostAdmin):

    fieldsets = post_fieldsets[0:3] + \
        ((_('Embedded object'), {
         'classes' : ['grp-collapse grp-open',],
         'fields': ('list_post_embedded_html', 'detail_post_embedded_html')
        }),) + \
        post_fieldsets[3:]

class FlatPageForm(forms.ModelForm):
    model = FlatPage
    class Media:
        js = [
              'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js',
              'grappelli/tinymce_setup/tinymce_setup.js',
             ]

class CustomFlatPageAdmin(FlatPageAdmin):
    form = FlatPageForm

class EditorsChoiceInline(admin.StackedInline):
    model = EditorChoice
    max_num = 1
    fields = ['editors_choice']
    can_delete = False

class CustomCommentAdmin(CommentsAdmin):
    list_display = ('id', 'name', 'content_type', 'object_pk', 'ip_address', 'submit_date', 'is_public', 'is_removed')
    inlines = [EditorsChoiceInline]

admin.site.register(BasicPost, BasicPostAdmin)
admin.site.register(PostWithSimpleImage, PostWithSimpleImageAdmin)
admin.site.register(PostWithImage, PostWithImageAdmin)
admin.site.register(PostWithSlideshow, PostWithSlideshowAdmin)
admin.site.register(PostWithEmbeddedObject, PostWithEmbeddedObjectAdmin)
admin.site.register(SubmittedArticle)

admin.site.unregister(FlatPage)
admin.site.register(FlatPage, CustomFlatPageAdmin)

admin.site.unregister(Comment)
admin.site.register(Comment, CustomCommentAdmin)
admin.site.register(CommentFlag)


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

describe 'XCRes::Section' do

  def subject
    XCRes::Section
  end

  describe '#initialize' do
    it 'should initialize a new section without options' do
      section = subject.new('Name', { 'a' => 'a.gif' })
      section.name.should.be.eql?('Name')
      section.items.should.be.eql?({ 'a' => 'a.gif' })
      section.options.should.be.eql?({})
    end

    it 'should initialize a new section with options' do
      section = subject.new('Name', { 'a' => 'a.gif' }, { custom_flag: true })
      section.name.should.be.eql?('Name')
      section.items.should.be.eql?({ 'a' => 'a.gif' })
      section.options.should.be.eql?({ custom_flag: true })
    end
  end

  describe '#==' do
    before do
      @left = subject.new('Cats', 'cat' => 'cat.gif')
    end

    it 'should be true for equal sections' do
      (@left == subject.new('Cats', 'cat' => 'cat.gif')).should.be.true?
    end

    it 'should be false if name is different' do
      (@left == subject.new('Dog', 'cat' => 'cat.gif')).should.be.false?
    end

    it 'should be false if items are different' do
      (@left == subject.new('Cat', 'dog' => 'dog.gif')).should.be.false?
    end

    it 'should be false if options are different' do
      (@left == subject.new('Cat', { 'cat' => 'cat.gif' }, custom_flag: true)).should.be.false?
    end
  end

end


text:
module Billogram
  class Client
    include HTTParty

    extend Forwardable

    delegate [:get, :post, :put, :delete] => self

    format :json

    def initialize(username, password, base_uri)
      self.class.default_options.merge!(base_uri: base_uri, basic_auth: { username: username, password: password })
    end
  end
end


text:
package org.apache.log4j.rolling.helper;

import org.apache.log4j.ULogger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Compresses a file using Zip compression.
 *
 * @author Curt Arnold
 * @since 1.3
 */
public final class ZipCompressAction extends ActionBase {
  /**
   * Source file.
   */
  private final File source;

  /**
   * Destination file.
   */
  private final File destination;

  /**
   * If true, attempt to delete file on completion.
   */
  private final boolean deleteSource;

  /**
   * Logger to receive diagnostic messages.
   */
  private final ULogger logger;

  /**
   * Create new instance of GZCompressAction.
   *
   * @param source file to compress, may not be null.
   * @param destination compressed file, may not be null.
   * @param deleteSource if true, attempt to delete file on completion.  Failure to delete
   * does not cause an exception to be thrown or affect return value.
   * @param logger logger, may be null.
   */
  public ZipCompressAction(
    final File source, final File destination, final boolean deleteSource,
    final ULogger logger) {
    if (source == null) {
      throw new NullPointerException("source");
    }

    if (destination == null) {
      throw new NullPointerException("destination");
    }

    this.source = source;
    this.destination = destination;
    this.deleteSource = deleteSource;
    this.logger = logger;
  }

  /**
   * Compress.
   * @return true if successfully compressed.
   * @throws IOException on IO exception.
   */
  public boolean execute() throws IOException {
    return execute(source, destination, deleteSource, logger);
  }

  /**
   * Compress a file.
   *
   * @param source file to compress, may not be null.
   * @param destination compressed file, may not be null.
   * @param deleteSource if true, attempt to delete file on completion.  Failure to delete
   * does not cause an exception to be thrown or affect return value.
   * @param logger logger, may be null.
   * @return true if source file compressed.
   * @throws IOException on IO exception.
   */
  public static boolean execute(
    final File source, final File destination, final boolean deleteSource,
    final ULogger logger) throws IOException {
    if (source.exists()) {
      FileInputStream fis = new FileInputStream(source);
      FileOutputStream fos = new FileOutputStream(destination);
      ZipOutputStream zos = new ZipOutputStream(fos);

      ZipEntry zipEntry = new ZipEntry(source.getName());
      zos.putNextEntry(zipEntry);

      byte[] inbuf = new byte[8102];
      int n;

      while ((n = fis.read(inbuf)) != -1) {
        zos.write(inbuf, 0, n);
      }

      zos.close();
      fis.close();

      if (deleteSource) {
        if (!source.delete() && (logger != null)) {
          logger.info("Unable to delete {}.", source.toString());
        }
      }

      return true;
    }

    return false;
  }

    /**
     * Capture exception.
     *
     * @param ex exception.
     */
    protected void reportException(final Exception ex) {
        if (logger != null) {
            logger.info("Exception during compression of '" + source.toString() + "'.", ex);
        }
    }
}


text:
jsgifkeylogger
==============

a javascript keylogger included in a gif file
This is a PoC

The idea to inlcuding javascript in a .gif file came form Saumil Shah @therealsaumil
(site:  http://www.net-square.com )

This technique he named "**IMAJS**"

The asm file for this, came form  Ange Albertini @angealbertin ( site: http://code.google.com/p/corkami/ )

**only** for tests

more infos:

https://deepsec.net/docs/Slides/2012/DeepSec_2012_Saumil_Shah_-_Bad_Things_in_good_Packages.pdf

this is a basic PoC

no evasion nor bypass of JS Filters

For some more fun with obf. JS visit https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet


text:
require 'spec_helper'

describe Spree::Api::CitiesController, :type => :controller do
  render_views

  let!(:city) { create(:city) }
  let(:attributes) { Spree::Api::ApiHelpers.city_attributes }

  before do
    stub_authentication!
  end

  it 'gets all cities' do
    api_get :index

    expect(json_response['cities'].first).to include(*attributes)
    expect(json_response['cities'].first['name']).to eq(city.name)
  end

  it 'gets all the cities for a particular state' do
    api_get :index, :state_id => city.state.id

    expect(json_response['cities'].first).to include(*attributes)
    expect(json_response['cities'].first['name']).to eq(city.name)
  end

  context 'pagination' do

    before do
      allow(Spree::City).to receive(:accessible_by).and_return(@scope = double)
      allow(@scope).to receive_message_chain(:ransack, :result, :includes, :order).and_return(@scope)
    end

    it 'does not paginate cities results when asked not to do so' do
      expect(@scope).to_not receive(:page)
      expect(@scope).to_not receive(:per)
      api_get :index
    end

    it 'paginates when page parameter is passed through' do
      expect(@scope).to receive(:page).with(1).and_return(@scope)
      expect(@scope).to receive(:per).with(nil)
      api_get :index, :page => 1
    end

    it 'paginates when per_page parameter is passed through' do
      expect(@scope).to receive(:page).with(nil).and_return(@scope)
      expect(@scope).to receive(:per).with(25)
      api_get :index, :per_page => 25
    end
  end

  context 'with two cities' do
    before { create(:city, :name => 'Attalla') }

    it 'gets all cities for a state' do
      state = create(:state, name: 'Amazonas', abbr: 'AM')
      city.state = state
      city.save

      api_get :index, :state_id => state.id

      expect(json_response['cities'].first).to include(*attributes)
      expect(json_response['cities'].count).to eq 1
    end

    it 'can view all cities' do
      api_get :index

      expect(json_response['cities'].first).to include(*attributes)
    end

    it 'can query the results through a parameter' do
      api_get :index, :q => { :name_cont => 'Ash' }

      expect(json_response['cities'].first['name']).to eq('Ashville')
    end
  end

  it 'can view a city' do
    api_get :show, :id => city.id

    expect(json_response).to include(*attributes)
  end
end


text:
<?php

/**
 * DO NOT EDIT!
 * This file was automatically generated via bin/generate-validator-spec.php.
 */

namespace AmpProject\Validator\Spec\Tag;

use AmpProject\Extension;
use AmpProject\Format;
use AmpProject\Html\Attribute;
use AmpProject\Html\Tag as Element;
use AmpProject\Validator\Spec\AttributeList;
use AmpProject\Validator\Spec\Identifiable;
use AmpProject\Validator\Spec\SpecRule;
use AmpProject\Validator\Spec\Tag;

/**
 * Tag class AmpStoryBookendExtensionJsonScript.
 *
 * @package ampproject/amp-toolbox.
 *
 * @property-read string $tagName
 * @property-read string $specName
 * @property-read bool $unique
 * @property-read string $mandatoryParent
 * @property-read array<array> $attrs
 * @property-read array<string> $attrLists
 * @property-read array<string> $htmlFormat
 * @property-read array<string> $requiresExtension
 * @property-read bool $siblingsDisallowed
 * @property-read bool $mandatoryLastChild
 */
final class AmpStoryBookendExtensionJsonScript extends Tag implements Identifiable
{
    /**
     * ID of the tag.
     *
     * @var string
     */
    const ID = 'amp-story-bookend extension .json script';

    /**
     * Array of spec rules.
     *
     * @var array
     */
    const SPEC = [
        SpecRule::TAG_NAME => Element::SCRIPT,
        SpecRule::SPEC_NAME => 'amp-story-bookend extension .json script',
        SpecRule::UNIQUE => true,
        SpecRule::MANDATORY_PARENT => Extension::STORY_BOOKEND,
        SpecRule::ATTRS => [
            Attribute::TYPE => [
                SpecRule::MANDATORY => true,
                SpecRule::DISPATCH_KEY => 'NAME_VALUE_PARENT_DISPATCH',
                SpecRule::VALUE_CASEI => [
                    'application/json',
                ],
            ],
        ],
        SpecRule::ATTR_LISTS => [
            AttributeList\NonceAttr::ID,
        ],
        SpecRule::HTML_FORMAT => [
            Format::AMP,
        ],
        SpecRule::REQUIRES_EXTENSION => [
            Extension::STORY,
        ],
        SpecRule::SIBLINGS_DISALLOWED => true,
        SpecRule::MANDATORY_LAST_CHILD => true,
    ];
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  IAnimationTarget
  VSTGUI::Animation

  IBitmapCreator
  VSTGUI

  IColorChooserDelegate
  VSTGUI

  IContentProvider
  VSTGUI::Xml

  IController
  VSTGUI

  IDataBrowserDelegate
  VSTGUI

  IDataPackage
  VSTGUI

  IDependency
  VSTGUI

  IFilter
  VSTGUI::BitmapFilter

  IFocusDrawing
  VSTGUI

  IFontChooserDelegate
  VSTGUI

  IFontPainter
  VSTGUI

  IGenericStringListDataBrowserSourceSelectionChanged
  VSTGUI

  IHandler
  VSTGUI::Xml

  IKeyboardHook
  VSTGUI

  IMouseObserver
  VSTGUI

  IMultiBitmapControl
  VSTGUI

  InputStream
  VSTGUI

  InputStreamContentProvider
  VSTGUI::Xml

  InterpolationTimingFunction
  VSTGUI::Animation

  IPlatformFont
  VSTGUI

  IScrollbarDrawer
  VSTGUI

  ISplitViewController
  VSTGUI

  ISplitViewSeparatorDrawer
  VSTGUI

  Iterator
  VSTGUI::CViewContainer

  ITimingFunction
  VSTGUI::Animation

  ITouchEvent
  VSTGUI

  IUIDescription
  VSTGUI

  IViewAddedRemovedObserver
  VSTGUI

  IViewCreator
  VSTGUI

  IViewFactory
  VSTGUI

  IViewSwitchController
  VSTGUI

Searching...

No Matches


text:
package io.crate.sql.tree;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static java.util.Objects.requireNonNull;

public class Query extends Statement {

    private final QueryBody queryBody;
    private final List<SortItem> orderBy;
    private final Optional<Expression> limit;
    private final Optional<Expression> offset;

    public Query(QueryBody queryBody,
                 List<SortItem> orderBy,
                 Optional<Expression> limit,
                 Optional<Expression> offset) {
        this.queryBody = requireNonNull(queryBody, "queryBody is null");
        this.orderBy = orderBy;
        this.limit = limit;
        this.offset = offset;
    }

    public QueryBody getQueryBody() {
        return queryBody;
    }

    public List<SortItem> getOrderBy() {
        return orderBy;
    }

    public Optional<Expression> getLimit() {
        return limit;
    }

    public Optional<Expression> getOffset() {
        return offset;
    }

    @Override
    public <R, C> R accept(AstVisitor<R, C> visitor, C context) {
        return visitor.visitQuery(this, context);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Query query = (Query) o;
        return Objects.equals(queryBody, query.queryBody) &&
               Objects.equals(orderBy, query.orderBy) &&
               Objects.equals(limit, query.limit) &&
               Objects.equals(offset, query.offset);
    }

    @Override
    public int hashCode() {
        return Objects.hash(queryBody, orderBy, limit, offset);
    }

    @Override
    public String toString() {
        return "Query{" +
               "queryBody=" + queryBody +
               ", orderBy=" + orderBy +
               ", limit=" + limit +
               ", offset=" + offset +
               '}';
    }
}


text:
Count down to Friday at 17:00 or Monday at 08:00, whichever is closer to the user's local time.

### Setup / Installation

### Features / Ideas

* [ ] favicons
* [ ] about overlay
  * instructions (?pause)
  * preferences (timezone selection, custom work days/weekend, internationalization)
  * copyright
  * source code
* [ ] move `setInterval` to service worker
* [ ] tests
* [ ] linting (javascript and styles)
* [ ] don't get so close to white or other washed out colors
* [ ] three bouncing dots while loading
* [ ] add special handling for special dates
  * comic sans for april 1
* [ ] bundle with https://parceljs.org/
* [ ] minimize html/css/js
* [ ] optimize font handling
  * https://www.filamentgroup.com/lab/rocket-science.html
  * redo font faces: only `woff` and `woff2` are needed
  * `font-display`
  * unicode subsets
  * prefetching (link tag)
  * maybe font loading API (see talk notes in link above)


text:
package mltk.util;

import java.util.LinkedList;

/**
 * Class for generic queues.
 *
 * @author Yin Lou
 *
 * @param <T>
 */
public class Queue<T> {

	protected LinkedList<T> list;

	/**
	 * Constructor.
	 */
	public Queue() {
		list = new LinkedList<T>();
	}

	/**
	 * Inserts an item to the queue.
	 *
	 * @param item the item.
	 */
	public void enqueue(T item) {
		list.addLast(item);
	}

	/**
	 * Removes the first element in the queue.
	 *
	 * @return the first element in the queue.
	 */
	public T dequeue() {
		T item = list.getFirst();
		list.removeFirst();
		return item;
	}

	/**
	 * Returns true if the queue is empty.
	 *
	 * @return true if the queue is empty.
	 */
	public boolean isEmpty() {
		return list.size() == 0;
	}

}


text:
using System.Collections.Generic;
using IVeraControl.Model;
using UpnpModels.Model.UpnpDevice.Base;
using UpnpModels.Model.UpnpService;

namespace UpnpModels.Model.UpnpDevice
{
    //Specification: http://upnp.org/specs/ha/UPnP-ha-BinaryLight-v1-Device.pdf
    public class BinaryLight1 : UpnpDeviceBase, IUpnpDevice
    {
        public string DeviceUrn => "urn:schemas-upnp-org:device:BinaryLight:1";

        public string DeviceName => nameof(BinaryLight1);

        public BinaryLight1(IVeraController controller)
        {
            Services = new List<IUpnpService> { new SwitchPower1(controller, this) };
        }
    }
}


text:
namespace arc {

class ArcBridgeService;
class ArcInstanceThrottle;

// Receives boot phase notifications from ARC.
class ArcBootPhaseMonitorBridge
    : public ArcService,
      public InstanceHolder<mojom::BootPhaseMonitorInstance>::Observer,
      public mojom::BootPhaseMonitorHost {
 public:
  explicit ArcBootPhaseMonitorBridge(ArcBridgeService* bridge_service);
  ~ArcBootPhaseMonitorBridge() override;

  // InstanceHolder<mojom::BootPhaseMonitorInstance>::Observer
  void OnInstanceReady() override;
  void OnInstanceClosed() override;

  // mojom::BootPhaseMonitorHost
  void OnBootCompleted() override;

 private:
  mojo::Binding<mojom::BootPhaseMonitorHost> binding_;
  std::unique_ptr<ArcInstanceThrottle> throttle_;

  base::ThreadChecker thread_checker_;

  DISALLOW_COPY_AND_ASSIGN(ArcBootPhaseMonitorBridge);
};

}  // namespace arc

#endif  // CHROME_BROWSER_CHROMEOS_ARC_BOOT_PHASE_MONITOR_ARC_BOOT_PHASE_MONITOR_BRIDGE_H_


text:
<?xml-stylesheet href="css3-modsel-46.css" type="text/css"?>
<test>

This paragraph should be unstyled.

But this one should have a green background

And this one should also have a green background

  <address>This address is only here to fill some space between two paragraphs</address>

This paragraph should have a green background

</test>


text:
module Ubiquity
  module Controller
    VERSION = "0.0.1"
  end
end


text:
package com.google.errorprone.bugpatterns.testdata;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;

/**
 * Tests for self assignment
 *
 * @author eaftan@google.com (Eddie Aftandilian)
 */
public class SelfAssignmentPositiveCases2 {
  private int a;
  private Foo foo;

  // BUG: Diagnostic contains: private static final Object obj
  private static final Object obj = SelfAssignmentPositiveCases2.obj;
  // BUG: Diagnostic contains: private static final Object obj2
  private static final Object obj2 = checkNotNull(SelfAssignmentPositiveCases2.obj2);

  public void test6() {
    Foo foo = new Foo();
    foo.a = 2;
    // BUG: Diagnostic contains: remove this line
    foo.a = foo.a;
    // BUG: Diagnostic contains: checkNotNull(foo.a)
    foo.a = checkNotNull(foo.a);
    // BUG: Diagnostic contains: requireNonNull(foo.a)
    foo.a = requireNonNull(foo.a);
  }

  public void test7() {
    Foobar f = new Foobar();
    f.foo = new Foo();
    f.foo.a = 10;
    // BUG: Diagnostic contains: remove this line
    f.foo.a = f.foo.a;
    // BUG: Diagnostic contains: checkNotNull(f.foo.a)
    f.foo.a = checkNotNull(f.foo.a);
    // BUG: Diagnostic contains: requireNonNull(f.foo.a)
    f.foo.a = requireNonNull(f.foo.a);
  }

  public void test8() {
    foo = new Foo();
    // BUG: Diagnostic contains: remove this line
    this.foo.a = foo.a;
    // BUG: Diagnostic contains: checkNotNull(foo.a)
    this.foo.a = checkNotNull(foo.a);
    // BUG: Diagnostic contains: requireNonNull(foo.a)
    this.foo.a = requireNonNull(foo.a);
  }

  public void test9(Foo fao, Foo bar) {
    // BUG: Diagnostic contains: this.foo = fao
    this.foo = foo;
    // BUG: Diagnostic contains: this.foo = checkNotNull(fao)
    this.foo = checkNotNull(foo);
    // BUG: Diagnostic contains: this.foo = requireNonNull(fao)
    this.foo = requireNonNull(foo);
  }

  public void test10(Foo foo) {
    // BUG: Diagnostic contains: this.foo = foo
    foo = foo;
    // BUG: Diagnostic contains: this.foo = checkNotNull(foo)
    foo = checkNotNull(foo);
    // BUG: Diagnostic contains: this.foo = requireNonNull(foo)
    foo = requireNonNull(foo);
  }

  class Test11 {
    final Foo foo;

    Foo fao;

    Test11(Foo foo) {
      if (true) {
        // BUG: Diagnostic contains: this.fao = foo
        foo = foo;
      }
      this.foo = foo;
    }

    public void test11a(Foo foo) {
      // BUG: Diagnostic contains: this.fao = foo
      foo = foo;
    }
  }

  private static class Foo {
    int a;
  }

  private static class Bar {
    int a;
  }

  private static class Foobar {
    Foo foo;
    Bar bar;
  }
}


text:
![PetriNetInterfaceC picture](PetriNetInterfaceC.svg)

A petri net interface component of C-type

### Theory
This is a placeholder component for a petri net interface. It contains no equations and should normally only be used when exporting or connecting the model to external tools.


text:
package zame.game;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import net.rbgrn.android.glwallpaperservice.GLWallpaperService;
import zame.game.engine.GameMath;
import zame.game.providers.CachedTexturesProvider;

// http://stackoverflow.com/questions/6086040/get-number-of-home-screens-in-android
// http://stackoverflow.com/questions/5208203/android-live-wallpaper-rescaling

public class MyWallpaperService extends GLWallpaperService {
	public class WallpaperEngine extends GLEngine implements Renderer {
		protected zame.game.engine.Engine engine;

		public WallpaperEngine() {
			super();
			// TODO: handle prefs, other initialization

			if (CachedTexturesProvider.needToUpdateCache()) {
				CachedTexturesProvider.updateCache();
			}

			engine = new zame.game.engine.Engine(null);
			engine.game.savedGameParam = (engine.hasInstantSave() ? engine.instantName : "");
			engine.init();

			setRenderer(this);
			setRenderMode(RENDERMODE_CONTINUOUSLY);
		}

		@Override
		public void onResume() {
			super.onResume();

			if (engine != null) {
				engine.onResume();
			}
		}

		@Override
		public void onPause() {
			super.onPause();

			if (engine != null) {
				engine.onPause();
			}
		}

		@Override
		public void onDestroy() {
			super.onDestroy();

			if (engine != null) {
				engine.onPause();
				engine = null;
			}
		}

		@Override
		public void onSurfaceCreated(GL10 gl, EGLConfig config) {
			if (engine != null) {
				engine.onSurfaceCreated(gl);
			}
		}

		@Override
		public void onSurfaceChanged(GL10 gl, int width, int height) {
			if (engine != null) {
				engine.onSurfaceChanged(gl, width, height);
			}
		}

		@Override
		public void onDrawFrame(GL10 gl) {
			if (engine != null) {
				engine.onDrawFrame(gl);
			}
		}

		@Override
		public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) {
			super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);

			engine.xOffset = xOffset;
			engine.xOffsetEnabled = (xOffsetStep > GameMath.INFINITY);
		}
	}

	public MyWallpaperService() {
		super();
	}

	public Engine onCreateEngine() {
		return new WallpaperEngine();
	}
}


text:
package org.jolokia;

/**
 * Class holding the version of this agent and the protocol.
 *
 * @author roland
 * @since Jun 11, 2009
 */
public final class Version {

    private static final String VERSION = "1.3.7";

    // Major.Minor version of protocol
    private static final String PROTOCOL = "7.2";

    private Version() {}

    public static String getAgentVersion() {
        return VERSION;
    }

    public static String getProtocolVersion() {
        return PROTOCOL;
    }
}


text:
package weed_server

import (
	"fmt"
	"github.com/chrislusf/seaweedfs/weed/glog"
	"net/http"
	"strconv"
	"strings"

	"github.com/chrislusf/seaweedfs/weed/operation"
	"github.com/chrislusf/seaweedfs/weed/security"
	"github.com/chrislusf/seaweedfs/weed/stats"
	"github.com/chrislusf/seaweedfs/weed/storage/needle"
	"github.com/chrislusf/seaweedfs/weed/topology"
)

func (ms *MasterServer) lookupVolumeId(vids []string, collection string) (volumeLocations map[string]operation.LookupResult) {
	volumeLocations = make(map[string]operation.LookupResult)
	for _, vid := range vids {
		commaSep := strings.Index(vid, ",")
		if commaSep > 0 {
			vid = vid[0:commaSep]
		}
		if _, ok := volumeLocations[vid]; ok {
			continue
		}
		volumeLocations[vid] = ms.findVolumeLocation(collection, vid)
	}
	return
}

// If "fileId" is provided, this returns the fileId location and a JWT to update or delete the file.
// If "volumeId" is provided, this only returns the volumeId location
func (ms *MasterServer) dirLookupHandler(w http.ResponseWriter, r *http.Request) {
	vid := r.FormValue("volumeId")
	if vid != "" {
		// backward compatible
		commaSep := strings.Index(vid, ",")
		if commaSep > 0 {
			vid = vid[0:commaSep]
		}
	}
	fileId := r.FormValue("fileId")
	if fileId != "" {
		commaSep := strings.Index(fileId, ",")
		if commaSep > 0 {
			vid = fileId[0:commaSep]
		}
	}
	collection := r.FormValue("collection") // optional, but can be faster if too many collections
	location := ms.findVolumeLocation(collection, vid)
	httpStatus := http.StatusOK
	if location.Error != "" || location.Locations == nil {
		httpStatus = http.StatusNotFound
	} else {
		forRead := r.FormValue("read")
		isRead := forRead == "yes"
		ms.maybeAddJwtAuthorization(w, fileId, !isRead)
	}
	writeJsonQuiet(w, r, httpStatus, location)
}

// findVolumeLocation finds the volume location from master topo if it is leader,
// or from master client if not leader
func (ms *MasterServer) findVolumeLocation(collection, vid string) operation.LookupResult {
	var locations []operation.Location
	var err error
	if ms.Topo.IsLeader() {
		volumeId, newVolumeIdErr := needle.NewVolumeId(vid)
		if newVolumeIdErr != nil {
			err = fmt.Errorf("Unknown volume id %s", vid)
		} else {
			machines := ms.Topo.Lookup(collection, volumeId)
			for _, loc := range machines {
				locations = append(locations, operation.Location{Url: loc.Url(), PublicUrl: loc.PublicUrl})
			}
		}
	} else {
		machines, getVidLocationsErr := ms.MasterClient.GetVidLocations(vid)
		for _, loc := range machines {
			locations = append(locations, operation.Location{Url: loc.Url, PublicUrl: loc.PublicUrl})
		}
		err = getVidLocationsErr
	}
	if len(locations) == 0 && err == nil {
		err = fmt.Errorf("volume id %s not found", vid)
	}
	ret := operation.LookupResult{
		VolumeOrFileId: vid,
		Locations:      locations,
	}
	if err != nil {
		ret.Error = err.Error()
	}
	return ret
}

func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request) {
	stats.AssignRequest()
	requestedCount, e := strconv.ParseUint(r.FormValue("count"), 10, 64)
	if e != nil || requestedCount == 0 {
		requestedCount = 1
	}

	writableVolumeCount, e := strconv.Atoi(r.FormValue("writableVolumeCount"))
	if e != nil {
		writableVolumeCount = 0
	}

	option, err := ms.getVolumeGrowOption(r)
	if err != nil {
		writeJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()})
		return
	}

	vl := ms.Topo.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl, option.DiskType)

	if !vl.HasGrowRequest() && vl.ShouldGrowVolumes(option) {
		glog.V(0).Infof("dirAssign volume growth %v from %v", option.String(), r.RemoteAddr)
		if ms.Topo.AvailableSpaceFor(option) <= 0 {
			writeJsonQuiet(w, r, http.StatusNotFound, operation.AssignResult{Error: "No free volumes left for " + option.String()})
			return
		}
		errCh := make(chan error, 1)
		vl.AddGrowRequest()
		ms.vgCh <- &topology.VolumeGrowRequest{
			Option: option,
			Count:  writableVolumeCount,
			ErrCh:  errCh,
		}
		if err := <-errCh; err != nil {
			writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("cannot grow volume group! %v", err))
			return
		}
	}
	fid, count, dnList, err := ms.Topo.PickForWrite(requestedCount, option)
	if err == nil {
		ms.maybeAddJwtAuthorization(w, fid, true)
		dn := dnList.Head()
		writeJsonQuiet(w, r, http.StatusOK, operation.AssignResult{Fid: fid, Url: dn.Url(), PublicUrl: dn.PublicUrl, Count: count})
	} else {
		writeJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()})
	}
}

func (ms *MasterServer) maybeAddJwtAuthorization(w http.ResponseWriter, fileId string, isWrite bool) {
	if fileId == "" {
		return
	}
	var encodedJwt security.EncodedJwt
	if isWrite {
		encodedJwt = security.GenJwtForVolumeServer(ms.guard.SigningKey, ms.guard.ExpiresAfterSec, fileId)
	} else {
		encodedJwt = security.GenJwtForVolumeServer(ms.guard.ReadSigningKey, ms.guard.ReadExpiresAfterSec, fileId)
	}
	if encodedJwt == "" {
		return
	}

	w.Header().Set("Authorization", "BEARER "+string(encodedJwt))
}


text:
class Activity < ActiveRecord::Base
  # Associations
  belongs_to :project
  belongs_to :person
  validates :project, :presence => true, :allow_blank => false
  validates :person,  :presence => true, :allow_blank => false

  # Scopes
  scope :by_date, lambda {|value| where(:date => value)}
  scope :by_period, lambda {|value|
    if value.is_a? Array
      where(:date => (value[0]..value[1]))
    else
      where(:date => value)
    end
  }
  scope :by_project_id, lambda {|value|
    where(:project_id => value) if value.present?
  }

  # Sorting
  default_scope order("date DESC")

  # Duration
  validates :duration, :presence => true, :format => {:with => /[0-9]{1,2}([:.][0-9]{1,2})/}

  validates_date :date, :allow_nil => false, :allow_blank => false

  def duration=(value)
    if value.match(/:/)
      hours, minutes = value.split(':')
      write_attribute(:duration, hours.to_i + BigDecimal.new(minutes) / 60)
    else
      write_attribute(:duration, value)
    end
  end

  def to_s
    "%s: %0.2fh" % [project.name, duration]
  end

  # Work day
  belongs_to :work_day, :autosave => true
  after_save :update_work_day
  after_destroy :update_work_day

  private
  def update_work_day
    WorkDay.create_or_update(self.person, date)
  end
end


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Lame browser :P</title>
        <meta name="theme-color" content="{{ site.accent }}">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noindex">

        <link rel="shortcut icon" href="{{ site.icon }}">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons|Roboto:200,200i,300,300i,400,400i,500,500i|Roboto+Mono:300">
        <link rel="stylesheet" href="../src/feather/feather.min.css">

You have a lame browser.

If you landed on this page, it means you have a lame browser. :P

                        It looks like your browser supports JavaScript, but it doesn't use the latest technologies.
                        Let's run some tests.

Testing…

                        Keep your browser up to date in order to make use of the latest web technologies.

                        "Why aren't you using JavaScript?!" — MindfulMinun

                        Your browser isn't using JavaScript. Most modern browsers have that enabled,
                        you probably just turned it off. Do us all a favor and turn it back on.
                        Furthermore, don't forget to keep your browser up to date in order to make use of the latest web technologies.

                    Return to tchat


text:
from django.shortcuts import render

from blog.models import Post
from .models import Project

HEADING = """### Welcome! I'm Pramod Lakshmanan. Here are some of my recent projects."""

def projects(request):
    """
    1. Convert the markdown strings on the top of the page to html
    2. Render the response
    """
    heading_html = Post.md_to_html(HEADING)
    projects = Project.objects.filter(is_published=True).order_by('-created').prefetch_related('tags')
    for p in projects:
        p.tag_names = [tag.name for tag in p.tags.all()]
    return render(request, 'projects.html', {
        "heading": heading_html,
        "projects": projects
    })


text:
package org.uberfire.ext.widgets.common.client.colorpicker;

import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import org.uberfire.ext.widgets.common.client.colorpicker.canvas.Canvas;
import org.uberfire.ext.widgets.common.client.colorpicker.canvas.RenderingContext;

public class HuePicker extends Composite {
	private Canvas canvas;
	private int handleY = 90;
	private boolean mouseDown;

	public HuePicker() {
		canvas = new Canvas();
		canvas.setStylePrimaryName("subshell-HuePicker");
		canvas.setCanvasSize(26, 180);

		initWidget(canvas);

		canvas.addMouseDownHandler(new MouseDownHandler() {
			public void onMouseDown(MouseDownEvent event) {
				handleY = event.getRelativeY(canvas.getElement());
				drawGradient();
				fireHueChanged(getHue());

				mouseDown = true;
			}
		});
		canvas.addMouseMoveHandler(new MouseMoveHandler() {
			public void onMouseMove(MouseMoveEvent event) {
				if (mouseDown) {
					handleY = event.getRelativeY(canvas.getElement());
					drawGradient();
					fireHueChanged(getHue());
				}
			}
		});
		canvas.addMouseUpHandler(new MouseUpHandler() {
			public void onMouseUp(MouseUpEvent event) {
				mouseDown = false;
			}
		});
		canvas.addMouseOutHandler(new MouseOutHandler() {
			public void onMouseOut(MouseOutEvent event) {
				mouseDown = false;
			}
		});
	}

	@Override
	protected void onAttach() {
		super.onAttach();
		drawGradient();
	}

	private void drawGradient() {
		RenderingContext ctx = canvas.getContext();

		// draw gradient
		ctx.setFillStyle("#ffffff");
		ctx.fillRect(0, 0, 26, 180);
		for (int y = 0; y <= 179; y++) {
			String hex = ColorUtils.hsl2hex(y * 2, 100, 100);
			ctx.setFillStyle("#" + hex);
			ctx.fillRect(3, y, 20, 1);
		}

		// draw handle
		if (handleY >= 0) {
			ctx.setFillStyle("#000000");

			ctx.beginPath();
			ctx.moveTo(3, handleY);
			ctx.lineTo(0, handleY - 3);
			ctx.lineTo(0, handleY + 3);
			ctx.closePath();
			ctx.fill();

			ctx.moveTo(23, handleY);
			ctx.lineTo(26, handleY - 3);
			ctx.lineTo(26, handleY + 3);
			ctx.closePath();
			ctx.fill();
		}
	}

	public HandlerRegistration addHueChangedHandler(HueChangedHandler handler) {
		return addHandler(handler, HueChangedEvent.getType());
	}

	private void fireHueChanged(int hue) {
		fireEvent(new HueChangedEvent(hue));
	}

	public int getHue() {
		return handleY * 2;
	}

	public void setHue(int hue) {
		handleY = (int) Math.min(Math.max(Math.round(hue / 2d), 0d), 179d);
		drawGradient();
		fireHueChanged(hue);
	}
}


text:
    Stability: 3 - Stable

Use `require('tls')` to access this module.

The `tls` module uses OpenSSL to provide Transport Layer Security and/or
Secure Socket Layer: encrypted stream communication.

TLS/SSL is a public/private key infrastructure. Each client and each
server must have a private key. A private key is created like this:

    openssl genrsa -out ryans-key.pem 2048

All servers and some clients need to have a certificate. Certificates are public
keys signed by a Certificate Authority or self-signed. The first step to
getting a certificate is to create a "Certificate Signing Request" (CSR)
file. This is done with:

    openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem

To create a self-signed certificate with the CSR, do this:

    openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem

Alternatively you can send the CSR to a Certificate Authority for signing.

(TODO: docs on creating a CA, for now interested users should just look at
`test/fixtures/keys/Makefile` in the Node source code)

To create .pfx or .p12, do this:

    openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
        -certfile ca-cert.pem -out agent5.pfx

  - `in`:  certificate
  - `inkey`: private key
  - `certfile`: all CA certs concatenated in one file like
    `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem`

## Protocol support

Node.js is compiled with SSLv2 and SSLv3 protocol support by default, but these
protocols are **disabled**. They are considered insecure and could be easily
compromised as was shown by [CVE-2014-3566][]. However, in some situations, it
may cause problems with legacy clients/servers (such as Internet Explorer 6).
If you wish to enable SSLv2 or SSLv3, run node with the `--enable-ssl2` or
`--enable-ssl3` flag respectively.  In future versions of Node.js SSLv2 and
SSLv3 will not be compiled in by default.

There is a way to force node into using SSLv3 or SSLv2 only mode by explicitly
specifying `secureProtocol` to `'SSLv3_method'` or `'SSLv2_method'`.

The default protocol method Node.js uses is `SSLv23_method` which would be more
accurately named `AutoNegotiate_method`. This method will try and negotiate
from the highest level down to whatever the client supports.  To provide a
secure default, Node.js (since v0.10.33) explicitly disables the use of SSLv3
and SSLv2 by setting the `secureOptions` to be
`SSL_OP_NO_SSLv3|SSL_OP_NO_SSLv2` (again, unless you have passed
`--enable-ssl3`, or `--enable-ssl2`, or `SSLv3_method` as `secureProtocol`).

If you have set `secureOptions` to anything, we will not override your
options.

The ramifications of this behavior change:

 * If your application is behaving as a secure server, clients who are `SSLv3`
only will now not be able to appropriately negotiate a connection and will be
refused. In this case your server will emit a `clientError` event. The error
message will include `'wrong version number'`.
 * If your application is behaving as a secure client and communicating with a
server that doesn't support methods more secure than SSLv3 then your connection
won't be able to negotiate and will fail. In this case your client will emit a
an `error` event. The error message will include `'wrong version number'`.

## Client-initiated renegotiation attack mitigation

<!-- type=misc -->

The TLS protocol lets the client renegotiate certain aspects of the TLS session.
Unfortunately, session renegotiation requires a disproportional amount of
server-side resources, which makes it a potential vector for denial-of-service
attacks.

To mitigate this, renegotiations are limited to three times every 10 minutes. An
error is emitted on the [tls.TLSSocket][] instance when the threshold is
exceeded. The limits are configurable:

  - `tls.CLIENT_RENEG_LIMIT`: renegotiation limit, default is 3.

  - `tls.CLIENT_RENEG_WINDOW`: renegotiation window in seconds, default is
    10 minutes.

Don't change the defaults unless you know what you are doing.

To test your server, connect to it with `openssl s_client -connect address:port`
and tap `R<CR>` (that's the letter `R` followed by a carriage return) a few
times.

## NPN and SNI

<!-- type=misc -->

NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS
handshake extensions allowing you:

  * NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
  * SNI - to use one TLS server for multiple hostnames with different SSL
    certificates.

## Perfect Forward Secrecy

<!-- type=misc -->

The term "[Forward Secrecy]" or "Perfect Forward Secrecy" describes a feature of
key-agreement (i.e. key-exchange) methods. Practically it means that even if the
private key of a (your) server is compromised, communication can only be
decrypted by eavesdroppers if they manage to obtain the key-pair specifically
generated for each session.

This is achieved by randomly generating a key pair for key-agreement on every
handshake (in contrary to the same key for all sessions). Methods implementing
this technique, thus offering Perfect Forward Secrecy, are called "ephemeral".

Currently two methods are commonly used to achieve Perfect Forward Secrecy (note
the character "E" appended to the traditional abbreviations):

  * [DHE] - An ephemeral version of the Diffie Hellman key-agreement protocol.
  * [ECDHE] - An ephemeral version of the Elliptic Curve Diffie Hellman
    key-agreement protocol.

Ephemeral methods may have some performance drawbacks, because key generation
is expensive.

## tls.getCiphers()

Returns an array with the names of the supported SSL ciphers.

Example:

    var ciphers = tls.getCiphers();
    console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]

## tls.createServer(options[, secureConnectionListener])

Creates a new [tls.Server][].  The `connectionListener` argument is
automatically set as a listener for the [secureConnection][] event.  The
`options` object has these possibilities:

  - `pfx`: A string or `Buffer` containing the private key, certificate and
    CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with
    the `key`, `cert` and `ca` options.)

  - `key`: A string or `Buffer` containing the private key of the server in
    PEM format. (Could be an array of keys). (Required)

  - `passphrase`: A string of passphrase for the private key or pfx.

  - `cert`: A string or `Buffer` containing the certificate key of the server in
    PEM format. (Could be an array of certs). (Required)

  - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM
    format. If this is omitted several well known "root" CAs will be used,
    like VeriSign. These are used to authorize connections.

  - `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate
    Revocation List)

  - `ciphers`: A string describing the ciphers to use or exclude.

    To mitigate [BEAST attacks] it is recommended that you use this option in
    conjunction with the `honorCipherOrder` option described below to
    prioritize the non-CBC cipher.

    Defaults to
    `ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL`.
    Consult the [OpenSSL cipher list format documentation] for details
    on the format.

    `ECDHE-RSA-AES128-SHA256`, `DHE-RSA-AES128-SHA256` and
    `AES128-GCM-SHA256` are TLS v1.2 ciphers and used when node.js is
    linked against OpenSSL 1.0.1 or newer, such as the bundled version
    of OpenSSL.  Note that it is still possible for a TLS v1.2 client
    to negotiate a weaker cipher unless `honorCipherOrder` is enabled.

    `RC4` is used as a fallback for clients that speak on older version of
    the TLS protocol.  `RC4` has in recent years come under suspicion and
    should be considered compromised for anything that is truly sensitive.
    It is speculated that state-level actors possess the ability to break it.

    **NOTE**: Previous revisions of this section suggested `AES256-SHA` as an
    acceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore
    susceptible to [BEAST attacks]. Do *not* use it.

  - `ecdhCurve`: A string describing a named curve to use for ECDH key agreement
    or false to disable ECDH.

    Defaults to `prime256v1`. Consult [RFC 4492] for more details.

  - `dhparam`: DH parameter file to use for DHE key agreement. Use
    `openssl dhparam` command to create it. If the file is invalid to
    load, it is silently discarded.

  - `handshakeTimeout`: Abort the connection if the SSL/TLS handshake does not
    finish in this many milliseconds. The default is 120 seconds.

    A `'clientError'` is emitted on the `tls.Server` object whenever a handshake
    times out.

  - `honorCipherOrder` : When choosing a cipher, use the server's preferences
    instead of the client preferences.

    Although, this option is disabled by default, it is *recommended* that you
    use this option in conjunction with the `ciphers` option to mitigate
    BEAST attacks.

    Note: If SSLv2 is used, the server will send its list of preferences to the
    client, and the client chooses the cipher.  Support for SSLv2 is disabled
    unless node.js was configured with `./configure --with-sslv2`.

  - `requestCert`: If `true` the server will request a certificate from
    clients that connect and attempt to verify that certificate. Default:
    `false`.

  - `rejectUnauthorized`: If `true` the server will reject any connection
    which is not authorized with the list of supplied CAs. This option only
    has an effect if `requestCert` is `true`. Default: `false`.

  - `checkServerIdentity(servername, cert)`: Provide an override for checking
    server's hostname against the certificate. Should return an error if verification
    fails. Return `undefined` if passing.

  - `NPNProtocols`: An array or `Buffer` of possible NPN protocols. (Protocols
    should be ordered by their priority).

  - `SNICallback(servername, cb)`: A function that will be called if client
    supports SNI TLS extension. Two argument will be passed to it: `servername`,
    and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a
    SecureContext instance.
    (You can use `tls.createSecureContext(...)` to get proper
    SecureContext). If `SNICallback` wasn't provided - default callback with
    high-level API will be used (see below).

  - `sessionTimeout`: An integer specifying the seconds after which TLS
    session identifiers and TLS session tickets created by the server are
    timed out. See [SSL_CTX_set_timeout] for more details.

  - `ticketKeys`: A 48-byte `Buffer` instance consisting of 16-byte prefix,
    16-byte hmac key, 16-byte AES key. You could use it to accept tls session
    tickets on multiple instances of tls server.

    NOTE: Automatically shared between `cluster` module workers.

  - `sessionIdContext`: A string containing an opaque identifier for session
    resumption. If `requestCert` is `true`, the default is MD5 hash value
    generated from command-line. Otherwise, the default is not provided.

  - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force
    SSL version 3. The possible values depend on your installation of
    OpenSSL and are defined in the constant [SSL_METHODS][].

  - `secureOptions`: Set server options. For example, to disable the SSLv3
    protocol set the `SSL_OP_NO_SSLv3` flag. See [SSL_CTX_set_options]
    for all available options.

Here is a simple example echo server:

    var tls = require('tls');
    var fs = require('fs');

    var options = {
      key: fs.readFileSync('server-key.pem'),
      cert: fs.readFileSync('server-cert.pem'),

      // This is necessary only if using the client certificate authentication.
      requestCert: true,

      // This is necessary only if the client uses the self-signed certificate.
      ca: [ fs.readFileSync('client-cert.pem') ]
    };

    var server = tls.createServer(options, function(socket) {
      console.log('server connected',
                  socket.authorized ? 'authorized' : 'unauthorized');
      socket.write("welcome!\n");
      socket.setEncoding('utf8');
      socket.pipe(socket);
    });
    server.listen(8000, function() {
      console.log('server bound');
    });

Or

    var tls = require('tls');
    var fs = require('fs');

    var options = {
      pfx: fs.readFileSync('server.pfx'),

      // This is necessary only if using the client certificate authentication.
      requestCert: true,

    };

    var server = tls.createServer(options, function(socket) {
      console.log('server connected',
                  socket.authorized ? 'authorized' : 'unauthorized');
      socket.write("welcome!\n");
      socket.setEncoding('utf8');
      socket.pipe(socket);
    });
    server.listen(8000, function() {
      console.log('server bound');
    });
You can test this server by connecting to it with `openssl s_client`:

    openssl s_client -connect 127.0.0.1:8000

## tls.connect(options[, callback])
## tls.connect(port[, host][, options][, callback])

Creates a new client connection to the given `port` and `host` (old API) or
`options.port` and `options.host`. (If `host` is omitted, it defaults to
`localhost`.) `options` should be an object which specifies:

  - `host`: Host the client should connect to

  - `port`: Port the client should connect to

  - `socket`: Establish secure connection on a given socket rather than
    creating a new socket. If this option is specified, `host` and `port`
    are ignored.

  - `path`: Creates unix socket connection to path. If this option is
    specified, `host` and `port` are ignored.

  - `pfx`: A string or `Buffer` containing the private key, certificate and
    CA certs of the client in PFX or PKCS12 format.

  - `key`: A string or `Buffer` containing the private key of the client in
    PEM format. (Could be an array of keys).

  - `passphrase`: A string of passphrase for the private key or pfx.

  - `cert`: A string or `Buffer` containing the certificate key of the client in
    PEM format. (Could be an array of certs).

  - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM
    format. If this is omitted several well known "root" CAs will be used,
    like VeriSign. These are used to authorize connections.

  - `rejectUnauthorized`: If `true`, the server certificate is verified against
    the list of supplied CAs. An `'error'` event is emitted if verification
    fails; `err.code` contains the OpenSSL error code. Default: `true`.

  - `NPNProtocols`: An array of strings or `Buffer`s containing supported NPN
    protocols. `Buffer`s should have following format: `0x05hello0x05world`,
    where first byte is next protocol name's length. (Passing array should
    usually be much simpler: `['hello', 'world']`.)

  - `servername`: Servername for SNI (Server Name Indication) TLS extension.

  - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force
    SSL version 3. The possible values depend on your installation of
    OpenSSL and are defined in the constant [SSL_METHODS][].

  - `session`: A `Buffer` instance, containing TLS session.

The `callback` parameter will be added as a listener for the
['secureConnect'][] event.

`tls.connect()` returns a [tls.TLSSocket][] object.

Here is an example of a client of echo server as described previously:

    var tls = require('tls');
    var fs = require('fs');

    var options = {
      // These are necessary only if using the client certificate authentication
      key: fs.readFileSync('client-key.pem'),
      cert: fs.readFileSync('client-cert.pem'),

      // This is necessary only if the server uses the self-signed certificate
      ca: [ fs.readFileSync('server-cert.pem') ]
    };

    var socket = tls.connect(8000, options, function() {
      console.log('client connected',
                  socket.authorized ? 'authorized' : 'unauthorized');
      process.stdin.pipe(socket);
      process.stdin.resume();
    });
    socket.setEncoding('utf8');
    socket.on('data', function(data) {
      console.log(data);
    });
    socket.on('end', function() {
      server.close();
    });

Or

    var tls = require('tls');
    var fs = require('fs');

    var options = {
      pfx: fs.readFileSync('client.pfx')
    };

    var socket = tls.connect(8000, options, function() {
      console.log('client connected',
                  socket.authorized ? 'authorized' : 'unauthorized');
      process.stdin.pipe(socket);
      process.stdin.resume();
    });
    socket.setEncoding('utf8');
    socket.on('data', function(data) {
      console.log(data);
    });
    socket.on('end', function() {
      server.close();
    });

## Class: tls.TLSSocket

Wrapper for instance of [net.Socket][], replaces internal socket read/write
routines to perform transparent encryption/decryption of incoming/outgoing data.

## new tls.TLSSocket(socket, options)

Construct a new TLSSocket object from existing TCP socket.

`socket` is an instance of [net.Socket][]

`options` is an object that might contain following properties:

  - `secureContext`: An optional TLS context object from
     `tls.createSecureContext( ... )`

  - `isServer`: If true - TLS socket will be instantiated in server-mode

  - `server`: An optional [net.Server][] instance

  - `requestCert`: Optional, see [tls.createSecurePair][]

  - `rejectUnauthorized`: Optional, see [tls.createSecurePair][]

  - `NPNProtocols`: Optional, see [tls.createServer][]

  - `SNICallback`: Optional, see [tls.createServer][]

  - `session`: Optional, a `Buffer` instance, containing TLS session

  - `requestOCSP`: Optional, if `true` - OCSP status request extension would
    be added to client hello, and `OCSPResponse` event will be emitted on socket
    before establishing secure communication

## tls.createSecureContext(details)

Creates a credentials object, with the optional details being a
dictionary with keys:

* `pfx` : A string or buffer holding the PFX or PKCS12 encoded private
  key, certificate and CA certificates
* `key` : A string holding the PEM encoded private key
* `passphrase` : A string of passphrase for the private key or pfx
* `cert` : A string holding the PEM encoded certificate
* `ca` : Either a string or list of strings of PEM encoded CA
  certificates to trust.
* `crl` : Either a string or list of strings of PEM encoded CRLs
  (Certificate Revocation List)
* `ciphers`: A string describing the ciphers to use or exclude.
  Consult
  <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>
  for details on the format.
* `honorCipherOrder` : When choosing a cipher, use the server's preferences
  instead of the client preferences. For further details see `tls` module
  documentation.

If no 'ca' details are given, then node.js will use the default
publicly trusted list of CAs as given in
<http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt>.

## tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized])

Creates a new secure pair object with two streams, one of which reads/writes
encrypted data, and one reads/writes cleartext data.
Generally the encrypted one is piped to/from an incoming encrypted data stream,
and the cleartext one is used as a replacement for the initial encrypted stream.

 - `credentials`: A secure context object from tls.createSecureContext( ... )

 - `isServer`: A boolean indicating whether this tls connection should be
   opened as a server or a client.

 - `requestCert`: A boolean indicating whether a server should request a
   certificate from a connecting client. Only applies to server connections.

 - `rejectUnauthorized`: A boolean indicating whether a server should
   automatically reject clients with invalid certificates. Only applies to
   servers with `requestCert` enabled.

`tls.createSecurePair()` returns a SecurePair object with `cleartext` and
`encrypted` stream properties.

NOTE: `cleartext` has the same APIs as [tls.TLSSocket][]

## Class: SecurePair

Returned by tls.createSecurePair.

### Event: 'secure'

The event is emitted from the SecurePair once the pair has successfully
established a secure connection.

Similarly to the checking for the server 'secureConnection' event,
pair.cleartext.authorized should be checked to confirm whether the certificate
used properly authorized.

## Class: tls.Server

This class is a subclass of `net.Server` and has the same methods on it.
Instead of accepting just raw TCP connections, this accepts encrypted
connections using TLS or SSL.

### Event: 'secureConnection'

`function (tlsSocket) {}`

This event is emitted after a new connection has been successfully
handshaked. The argument is an instance of [tls.TLSSocket][]. It has all the
common stream methods and events.

`socket.authorized` is a boolean value which indicates if the
client has verified by one of the supplied certificate authorities for the
server. If `socket.authorized` is false, then
`socket.authorizationError` is set to describe how authorization
failed. Implied but worth mentioning: depending on the settings of the TLS
server, you unauthorized connections may be accepted.
`socket.npnProtocol` is a string containing selected NPN protocol.
`socket.servername` is a string containing servername requested with
SNI.

### Event: 'clientError'

`function (exception, tlsSocket) { }`

When a client connection emits an 'error' event before secure connection is
established - it will be forwarded here.

`tlsSocket` is the [tls.TLSSocket][] that the error originated from.

### Event: 'newSession'

`function (sessionId, sessionData, callback) { }`

Emitted on creation of TLS session. May be used to store sessions in external
storage. `callback` must be invoked eventually, otherwise no data will be
sent or received from secure connection.

NOTE: adding this event listener will have an effect only on connections
established after addition of event listener.

### Event: 'resumeSession'

`function (sessionId, callback) { }`

Emitted when client wants to resume previous TLS session. Event listener may
perform lookup in external storage using given `sessionId`, and invoke
`callback(null, sessionData)` once finished. If session can't be resumed
(i.e. doesn't exist in storage) one may call `callback(null, null)`. Calling
`callback(err)` will terminate incoming connection and destroy socket.

NOTE: adding this event listener will have an effect only on connections
established after addition of event listener.

### Event: 'OCSPRequest'

`function (certificate, issuer, callback) { }`

Emitted when the client sends a certificate status request. You could parse
server's current certificate to obtain OCSP url and certificate id, and after
obtaining OCSP response invoke `callback(null, resp)`, where `resp` is a
`Buffer` instance. Both `certificate` and `issuer` are a `Buffer`
DER-representations of the primary and issuer's certificates. They could be used
to obtain OCSP certificate id and OCSP endpoint url.

Alternatively, `callback(null, null)` could be called, meaning that there is no
OCSP response.

Calling `callback(err)` will result in a `socket.destroy(err)` call.

Typical flow:

1. Client connects to server and sends `OCSPRequest` to it (via status info
   extension in ClientHello.)
2. Server receives request and invokes `OCSPRequest` event listener if present
3. Server grabs OCSP url from either `certificate` or `issuer` and performs an
   [OCSP request] to the CA
4. Server receives `OCSPResponse` from CA and sends it back to client via
   `callback` argument
5. Client validates the response and either destroys socket or performs a
   handshake.

NOTE: `issuer` could be null, if the certificate is self-signed or if the issuer
is not in the root certificates list. (You could provide an issuer via `ca`
option.)

NOTE: adding this event listener will have an effect only on connections
established after addition of event listener.

NOTE: you may want to use some npm module like [asn1.js] to parse the
certificates.

### server.listen(port[, host][, callback])

Begin accepting connections on the specified `port` and `host`.  If the
`host` is omitted, the server will accept connections directed to any
IPv4 address (`INADDR_ANY`).

This function is asynchronous. The last parameter `callback` will be called
when the server has been bound.

See `net.Server` for more information.

### server.close()

Stops the server from accepting new connections. This function is
asynchronous, the server is finally closed when the server emits a `'close'`
event.

### server.address()

Returns the bound address, the address family name and port of the
server as reported by the operating system.  See [net.Server.address()][] for
more information.

### server.addContext(hostname, context)

Add secure context that will be used if client request's SNI hostname is
matching passed `hostname` (wildcards can be used). `context` can contain
`key`, `cert`, `ca` and/or any other properties from `tls.createSecureContext`
`options` argument.

### server.maxConnections

Set this property to reject connections when the server's connection count
gets high.

### server.connections

The number of concurrent connections on the server.

## Class: CryptoStream

    Stability: 0 - Deprecated. Use tls.TLSSocket instead.

This is an encrypted stream.

### cryptoStream.bytesWritten

A proxy to the underlying socket's bytesWritten accessor, this will return
the total bytes written to the socket, *including the TLS overhead*.

## Class: tls.TLSSocket

This is a wrapped version of [net.Socket][] that does transparent encryption
of written data and all required TLS negotiation.

This instance implements a duplex [Stream][] interfaces.  It has all the
common stream methods and events.

### Event: 'secureConnect'

This event is emitted after a new connection has been successfully handshaked.
The listener will be called no matter if the server's certificate was
authorized or not. It is up to the user to test `tlsSocket.authorized`
to see if the server certificate was signed by one of the specified CAs.
If `tlsSocket.authorized === false` then the error can be found in
`tlsSocket.authorizationError`. Also if NPN was used - you can check
`tlsSocket.npnProtocol` for negotiated protocol.

### Event: 'OCSPResponse'

`function (response) { }`

This event will be emitted if `requestOCSP` option was set. `response` is a
buffer object, containing server's OCSP response.

Traditionally, the `response` is a signed object from the server's CA that
contains information about server's certificate revocation status.

### tlsSocket.encrypted

Static boolean value, always `true`. May be used to distinguish TLS sockets
from regular ones.

### tlsSocket.authorized

A boolean that is `true` if the peer certificate was signed by one of the
specified CAs, otherwise `false`

### tlsSocket.authorizationError

The reason why the peer's certificate has not been verified. This property
becomes available only when `tlsSocket.authorized === false`.

### tlsSocket.getPeerCertificate([ detailed ])

Returns an object representing the peer's certificate. The returned object has
some properties corresponding to the field of the certificate. If `detailed`
argument is `true` - the full chain with `issuer` property will be returned,
if `false` - only the top certificate without `issuer` property.

Example:

    { subject:
       { C: 'UK',
         ST: 'Acknack Ltd',
         L: 'Rhys Jones',
         O: 'node.js',
         OU: 'Test TLS Certificate',
         CN: 'localhost' },
      issuerInfo:
       { C: 'UK',
         ST: 'Acknack Ltd',
         L: 'Rhys Jones',
         O: 'node.js',
         OU: 'Test TLS Certificate',
         CN: 'localhost' },
      issuer:
       { ... another certificate ... },
      raw: < RAW DER buffer >,
      valid_from: 'Nov 11 09:52:22 2009 GMT',
      valid_to: 'Nov  6 09:52:22 2029 GMT',
      fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF',
      serialNumber: 'B9B0D332A1AA5635' }

If the peer does not provide a certificate, it returns `null` or an empty
object.

### tlsSocket.getCipher()
Returns an object representing the cipher name and the SSL/TLS
protocol version of the current connection.

Example:
{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in
http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more
information.

### tlsSocket.renegotiate(options, callback)

Initiate TLS renegotiation process. The `options` may contain the following
fields: `rejectUnauthorized`, `requestCert` (See [tls.createServer][]
for details). `callback(err)` will be executed with `null` as `err`,
once the renegotiation is successfully completed.

NOTE: Can be used to request peer's certificate after the secure connection
has been established.

ANOTHER NOTE: When running as the server, socket will be destroyed
with an error after `handshakeTimeout` timeout.

### tlsSocket.setMaxSendFragment(size)

Set maximum TLS fragment size (default and maximum value is: `16384`, minimum
is: `512`). Returns `true` on success, `false` otherwise.

Smaller fragment size decreases buffering latency on the client: large
fragments are buffered by the TLS layer until the entire fragment is received
and its integrity is verified; large fragments can span multiple roundtrips,
and their processing can be delayed due to packet loss or reordering. However,
smaller fragments add extra TLS framing bytes and CPU overhead, which may
decrease overall server throughput.

### tlsSocket.getSession()

Return ASN.1 encoded TLS session or `undefined` if none was negotiated. Could
be used to speed up handshake establishment when reconnecting to the server.

### tlsSocket.getTLSTicket()

NOTE: Works only with client TLS sockets. Useful only for debugging, for
session reuse provide `session` option to `tls.connect`.

Return TLS session ticket or `undefined` if none was negotiated.

### tlsSocket.address()

Returns the bound address, the address family name and port of the
underlying socket as reported by the operating system. Returns an
object with three properties, e.g.
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`

### tlsSocket.remoteAddress

The string representation of the remote IP address. For example,
`'74.125.127.100'` or `'2001:4860:a005::68'`.

### tlsSocket.remoteFamily

The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.

### tlsSocket.remotePort

The numeric representation of the remote port. For example, `443`.

### tlsSocket.localAddress

The string representation of the local IP address.

### tlsSocket.localPort

The numeric representation of the local port.

[OpenSSL cipher list format documentation]: http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
[BEAST attacks]: http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html
[tls.createServer]: #tls_tls_createserver_options_secureconnectionlistener
[tls.createSecurePair]: #tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized
[tls.TLSSocket]: #tls_class_tls_tlssocket
[net.Server]: net.html#net_class_net_server
[net.Socket]: net.html#net_class_net_socket
[net.Server.address()]: net.html#net_server_address
['secureConnect']: #tls_event_secureconnect
[secureConnection]: #tls_event_secureconnection
[Stream]: stream.html#stream_stream
[SSL_METHODS]: http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS
[tls.Server]: #tls_class_tls_server
[SSL_CTX_set_timeout]: http://www.openssl.org/docs/ssl/SSL_CTX_set_timeout.html
[RFC 4492]: http://www.rfc-editor.org/rfc/rfc4492.txt
[Forward secrecy]: http://en.wikipedia.org/wiki/Perfect_forward_secrecy
[DHE]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
[ECDHE]: https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman
[asn1.js]: http://npmjs.org/package/asn1.js
[OCSP request]: http://en.wikipedia.org/wiki/OCSP_stapling
[SSL_CTX_set_options]: https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
[CVE-2014-3566]: https://access.redhat.com/articles/1232123


text:
const mongoose = require('mongoose');

const placeSchema = new mongoose.Schema({
  name: {type: String, require:true},
  latitude: {type:Number, require:true},
  longitude: {type:Number,require:true}
}, { timestamps: true });

const Place = mongoose.model('Place', placeSchema);

module.exports = Place;


text:
<?php

  namespace models\page;

  use core\model\ModelBaseImpl;
  use core\model\ModelConfig;
  use core\model\ModelConfigImpl;
  use core\vendor\Application;

  class IndexModel extends ModelBaseImpl {

    public function __construct(Application $app, ModelConfig $config = null) {
      parent::__construct($app, $config ?: new ModelConfigImpl('/page/index.twig', ['/'], ['get']));
    }

    public function loadLocalization() {
      $this->app->addLocalization('/page/index/');
    }

  }


text:
package org.apache.commons.io.filefilter;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.Serializable;

/**
 * This class turns a Java FileFilter or FilenameFilter into an IO FileFilter.
 *
 * @since 1.0
 * @version $Id$
 *
 * @see FileFilterUtils#asFileFilter(FileFilter)
 * @see FileFilterUtils#asFileFilter(FilenameFilter)
 */
public class DelegateFileFilter extends AbstractFileFilter implements Serializable {

    private static final long serialVersionUID = -8723373124984771318L;
    /** The Filename filter */
    private final FilenameFilter filenameFilter;
    /** The File filter */
    private final FileFilter fileFilter;

    /**
     * Constructs a delegate file filter around an existing FilenameFilter.
     *
     * @param filter  the filter to decorate
     */
    public DelegateFileFilter(final FilenameFilter filter) {
        if (filter == null) {
            throw new IllegalArgumentException("The FilenameFilter must not be null");
        }
        this.filenameFilter = filter;
        this.fileFilter = null;
    }

    /**
     * Constructs a delegate file filter around an existing FileFilter.
     *
     * @param filter  the filter to decorate
     */
    public DelegateFileFilter(final FileFilter filter) {
        if (filter == null) {
            throw new IllegalArgumentException("The FileFilter must not be null");
        }
        this.fileFilter = filter;
        this.filenameFilter = null;
    }

    /**
     * Checks the filter.
     *
     * @param file  the file to check
     * @return true if the filter matches
     */
    @Override
    public boolean accept(final File file) {
        if (fileFilter != null) {
            return fileFilter.accept(file);
        } else {
            return super.accept(file);
        }
    }

    /**
     * Checks the filter.
     *
     * @param dir  the directory
     * @param name  the filename in the directory
     * @return true if the filter matches
     */
    @Override
    public boolean accept(final File dir, final String name) {
        if (filenameFilter != null) {
            return filenameFilter.accept(dir, name);
        } else {
            return super.accept(dir, name);
        }
    }

    /**
     * Provide a String representation of this file filter.
     *
     * @return a String representation
     */
    @Override
    public String toString() {
        final String delegate = fileFilter != null ? fileFilter.toString() : filenameFilter.toString();
        return super.toString() + "(" + delegate + ")";
    }

}


text:
import os

from lucene import \
    Document, Field, IndexWriter, StandardAnalyzer, NumericField, \
    SimpleDateFormat, Version, SimpleFSDirectory, File, DateTools, DateField

# date culled from LuceneInAction.zip archive from Manning site
samplesModified = SimpleDateFormat('yyyy-MM-dd').parse('2004-12-02')

class TestDataDocumentHandler(object):

    def createIndex(cls, dataDir, indexDir, useCompound):

        indexDir = SimpleFSDirectory(File(indexDir))
        writer = IndexWriter(indexDir,
                             StandardAnalyzer(Version.LUCENE_CURRENT), True,
                             IndexWriter.MaxFieldLength.UNLIMITED)
        writer.setUseCompoundFile(useCompound)

        for dir, dirnames, filenames in os.walk(dataDir):
            for filename in filenames:
                if filename.endswith('.properties'):
                    cls.indexFile(writer, os.path.join(dir, filename), dataDir)

        writer.optimize()
        writer.close()

    def indexFile(cls, writer, path, baseDir):

        input = file(path)
        props = {}
        while True:
            line = input.readline().strip()
            if not line:
                break
            name, value = line.split('=', 1)
            props[name] = value.decode('unicode-escape')
        input.close()

        doc = Document()

        # category comes from relative path below the base directory
        category = os.path.dirname(path)[len(baseDir):]
        if os.path.sep != '/':
            category = category.replace(os.path.sep, '/')

        isbn = props['isbn']
        title = props['title']
        author = props['author']
        url = props['url']
        subject = props['subject']
        pubmonth = props['pubmonth']

        print title.encode('utf8')
        print author.encode('utf-8')
        print subject.encode('utf-8')
        print category.encode('utf-8')
        print "---------"

        doc.add(Field("isbn", isbn,
                      Field.Store.YES, Field.Index.NOT_ANALYZED))
        doc.add(Field("category", category,
                      Field.Store.YES, Field.Index.NOT_ANALYZED))
        doc.add(Field("title", title,
                      Field.Store.YES, Field.Index.ANALYZED,
                      Field.TermVector.WITH_POSITIONS_OFFSETS))
        doc.add(Field("title2", title.lower(),
                      Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS,
                      Field.TermVector.WITH_POSITIONS_OFFSETS))

        # split multiple authors into unique field instances
        authors = author.split(',')
        for a in authors:
            doc.add(Field("author", a,
                          Field.Store.YES, Field.Index.NOT_ANALYZED,
                          Field.TermVector.WITH_POSITIONS_OFFSETS))

        doc.add(Field("url", url,
                      Field.Store.YES,
                      Field.Index.NOT_ANALYZED_NO_NORMS))
        doc.add(Field("subject", subject,
                      Field.Store.NO, Field.Index.ANALYZED,
                      Field.TermVector.WITH_POSITIONS_OFFSETS))
        doc.add(NumericField("pubmonth",
                             Field.Store.YES,
                             True).setIntValue(int(pubmonth)))

        d = DateTools.stringToDate(pubmonth)
        d = int(d.getTime() / (1000 * 3600 * 24.0))
        doc.add(NumericField("pubmonthAsDay").setIntValue(d))

        doc.add(Field("contents", ' '.join([title, subject, author, category]),
                      Field.Store.NO, Field.Index.ANALYZED,
                      Field.TermVector.WITH_POSITIONS_OFFSETS))

        doc.add(Field("path", path,
                      Field.Store.YES, Field.Index.NOT_ANALYZED))
        doc.add(Field("modified", DateField.dateToString(samplesModified),
                      Field.Store.YES, Field.Index.NOT_ANALYZED))

        writer.addDocument(doc)

    createIndex = classmethod(createIndex)
    indexFile = classmethod(indexFile)


text:
---
id: 587d7fb3367417b2b2512bfc
title: Aggiungere una descrizione al tuo package.json
challengeType: 2
forumTopicId: 301522
dashedName: add-a-description-to-your-package-json
---

# --description--

La parte successiva di un buon file package.json è il campo `description`, che conterrà una breve ma informativa descrizione del progetto.

Se un giorno avessi intenzione di pubblicare un pacchetto su npm, questa è la stringa che dovrebbe vendere la tua idea all'utente quando decide se installare o meno il pacchetto. Tuttavia, questo non è l'unico caso di utilizzo per la descrizione: essa è un ottimo modo per riassumere ciò che un progetto fa. È altrettanto importante in qualsiasi progetto Node.js per aiutare altri sviluppatori, futuri manutentori o anche il futuro te stesso a comprendere il progetto velocemente.

Indipendentemente da ciò che prevedi per il vostro progetto, una descrizione è sicuramente consigliata. Ecco un esempio:

```json
"description": "A project that does something awesome",
```

# --instructions--

Aggiungi una `description` al file package.json del tuo progetto.

**Nota:** Ricordati di usare le virgolette doppie (") per i nomi di campo e le virgole (,) per separare i campi.

# --hints--

package.json dovrebbe avere una chiave "description" valida

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/package.json').then(
    (data) => {
      var packJson = JSON.parse(data);
      assert(packJson.description, '"description" is missing');
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

# --solutions--

```js
/**
  Backend challenges don't need solutions,
  because they would need to be tested against a full working project.
  Please check our contributing guidelines to learn more.
*/
```


text:
package collins.models.asset

import play.api.libs.json.JsObject
import play.api.libs.json.JsString
import play.api.libs.json.JsValue
import play.api.libs.json.Json

import collins.models.asset.conversions.AssetFormat

abstract class RemoteAssetProxy(jsonAsset: JsValue) extends RemoteAsset {

  private[this] val asset = Json.fromJson[AssetView](jsonAsset)
		  .getOrElse(throw new Exception("Unable to obtain asset from remote asset proxy"))

  def id = asset.id
  def tag = asset.tag
  def state = asset.state
  def status = asset.status
  def asset_type = asset.asset_type
  def created = asset.created
  def updated = asset.updated
  def deleted = asset.deleted

  def toJsValue() = {
    AssetFormat.writes(asset) ++ JsObject(Seq("LOCATION" -> JsString(hostTag)))
  }
}


text:
=pod

=head1 NAME

openssl-env - OpenSSL environment variables

=head1 DESCRIPTION

The OpenSSL libraries use environment variables to override the
compiled-in default paths for various data.
To avoid security risks, the environment is usually not consulted when
the executable is set-user-ID or set-group-ID.

=over 4

=item B<CTLOG_FILE>

Specifies the path to a certificate transparency log list.
See L<CTLOG_STORE_new(3)>.

=item B<OPENSSL>

Specifies the path to the B<openssl> executable. Used by
the B<rehash> script (see L<openssl-rehash(1)/Script Configuration>)
and by the B<CA.pl> script (see L<CA.pl(1)/NOTES>

=item B<OPENSSL_CONF>, B<OPENSSL_CONF_INCLUDE>

Specifies the path to a configuration file and the directory for
included files.
See L<config(5)>.

=item B<OPENSSL_CONFIG>

Specifies a configuration option and filename for the B<req> and B<ca>
commands invoked by the B<CA.pl> script.
See L<CA.pl(1)>.

=item B<OPENSSL_ENGINES>

Specifies the directory from which dynamic engines are loaded.
See L<openssl-engine(1)>.

=item B<OPENSSL_MALLOC_FD>, B<OPENSSL_MALLOC_FAILURES>

If built with debugging, this allows memory allocation to fail.
See L<OPENSSL_malloc(3)>.

=item B<OPENSSL_MODULES>

Specifies the directory from which cryptographic providers are loaded.
Equivalently, the generic B<-provider-path> command-line option may be used.

=item B<OPENSSL_WIN32_UTF8>

If set, then L<UI_OpenSSL(3)> returns UTF-8 encoded strings, rather than
ones encoded in the current code page, and
the L<openssl(1)> program also transcodes the command-line parameters
from the current code page to UTF-8.
This environment variable is only checked on Microsoft Windows platforms.

=item B<RANDFILE>

The state file for the random number generator.
This should not be needed in normal use.
See L<RAND_load_file(3)>.

=item B<SSL_CERT_DIR>, B<SSL_CERT_FILE>

Specify the default directory or file containing CA certificates.
See L<SSL_CTX_load_verify_locations(3)>.

=item B<TSGET>

Additional arguments for the L<tsget(1)> command.

=item B<OPENSSL_ia32cap>, B<OPENSSL_sparcv9cap>, B<OPENSSL_ppccap>, B<OPENSSL_armcap>, B<OPENSSL_s390xcap>

OpenSSL supports a number of different algorithm implementations for
various machines and, by default, it determines which to use based on the
processor capabilities and run time feature enquiry.  These environment
variables can be used to exert more control over this selection process.
See L<OPENSSL_ia32cap(3)>, L<OPENSSL_s390xcap(3)>.

=item B<NO_PROXY>, B<HTTPS_PROXY>, B<HTTP_PROXY>

Specify a proxy hostname.
See L<OSSL_HTTP_parse_url(3)>.

=back

=head1 COPYRIGHT

Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the Apache License 2.0 (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


text:
using namespace Cpf;
using namespace Adapters;
using namespace Metal;

//////////////////////////////////////////////////////////////////////////
Adapter::~Adapter()
{
}

bool Adapter::IsSoftware()
{
	return false;
}