text:
describe Api::V1::CurrentEntityController do
  controller do
    def self.model
      Stop
    end
    def url_for(params)
      "http://blah/offset=#{params[:offset]}"
    end
  end

  before(:each) do
    @glen_park = create(:stop, geometry: 'POINT(-122.433416 37.732525)', name: 'Glen Park')
    @bosworth_diamond = create(:stop, geometry: 'POINT(-122.434011 37.733595)', name: 'Bosworth + Diamond')
    @metro_embarcadero = create(:stop, geometry: 'POINT(-122.396431 37.793152)', name: 'Metro Embarcadero')
    @gilman_paul_3rd = create(:stop, geometry: 'POINT(-122.395644 37.722413)', name: 'Gilman + Paul + 3rd St.')
    @glen_park.update(tags: { wheelchair_accessible: 'yes' })
    @gilman_paul_3rd.update(tags: { wheelchair_accessible: 'no' })
  end

  context 'GET index' do
    context 'base' do
      it 'returns all entities' do
        get :index, total: true
        expect_json_types({ stops: :array })
        expect_json({
          stops: -> (stops) {
            expect(stops.length).to eq 4
          },
          meta: {
            total: 4
          }
        })
      end
    end

    context '?onestop_id' do
      it 'returns entities by onestop_id' do
        onestop_id = @glen_park.onestop_id
        get :index, onestop_id: onestop_id
        expect_json_types({ stops: :array })
        expect_json({
          stops: -> (stops) {
            expect(stops.length).to eq(1)
            expect(stops.first[:onestop_id]).to eq onestop_id
          }
        })
      end
    end

    context '?lat ?lon ?r' do
      it 'returns entities within a radius of a point' do
        get :index, lat: 37.732520, lon: -122.433415, r: 500
        expect_json({ stops: -> (stops) {
          expect(stops.map { |stop| stop[:onestop_id] }).to match_array([@glen_park, @bosworth_diamond].map(&:onestop_id))
        }})
      end
    end

    context '?bbox' do
      it 'returns entities inside a bbox' do
        get :index, bbox: '-122.4131,37.7136,-122.3789,37.8065'
        expect_json({ stops: -> (stops) {
          expect(stops.map { |stop| stop[:onestop_id] }).to match_array([@metro_embarcadero, @gilman_paul_3rd].map(&:onestop_id))
        }})
      end
    end

    context '?tag_key ?tag_value' do
      it 'returns entities with a given tag' do
        get :index, tag_key: 'wheelchair_accessible'
        expect_json({ stops: -> (stops) {
          expect(stops.map { |stop| stop[:onestop_id] }).to match_array([@glen_park.onestop_id, @gilman_paul_3rd.onestop_id])
        }})
      end

      it 'returns entities with a given tag value' do
        get :index, tag_key: 'wheelchair_accessible', tag_value: 'yes'
        expect_json({ stops: -> (stops) {
          expect(stops.map { |stop| stop[:onestop_id] }).to match_array([@glen_park.onestop_id])
        }})
      end
    end

    context '?imported_with_gtfs_id' do
      it 'returns entities with a given GTFS ID' do
        stop = Stop.first
        feed_version = create(:feed_version_example)
        feed_version.entities_imported_from_feed.create!(entity: stop, feed: feed_version.feed, gtfs_id: "test")
        get :index, imported_with_gtfs_id: 'test'
        expect_json({ stops: -> (stops) {
          expect(stops.first[:onestop_id]).to eq stop.onestop_id
          expect(stops.count).to eq 1
        }})
        get :index, imported_with_gtfs_id: 'true', gtfs_id: 'test'
        expect_json({ stops: -> (stops) {
          expect(stops.first[:onestop_id]).to eq stop.onestop_id
          expect(stops.count).to eq 1
        }})
        get :index, imported_with_gtfs_id: 'unknown'
        expect_json({ stops: -> (stops) {
          expect(stops.size).to eq 0
        }})
      end
    end
  end

  context '?format' do
    context 'geojson' do
      it 'should return GeoJSON' do
        stops = Stop.all.sort_by(&:id)
        get :index, format: :geojson
        expect_json({
          type: 'FeatureCollection',
          features: -> (features) {
            features.zip(stops) { |i,j|
              expect(i[:properties][:onestop_id]).to eq(j.onestop_id)
              expect(i[:geometry]).to eq(j.geometry)
            }
          }
        })
      end

      it '?bbox' do
        get :index, format: :geojson, bbox: '-122.4131,37.7136,-122.3789,37.8065'
        expect_json({
          type: 'FeatureCollection',
          features: -> (features) {
            expect(features.map { |feature| feature[:id] }).to match_array([@metro_embarcadero, @gilman_paul_3rd].map(&:onestop_id))
          }
        })
      end
    end

    context 'csv' do
      before(:each) do
        @sfmta = create(:operator, geometry: 'POINT(-122.395644 37.722413)', name: 'SFMTA')
        @metro_embarcadero.operators << @sfmta
      end

      it 'should return a CSV file for download' do
        get :index, format: :csv
        expect(response.headers['Content-Type']).to eq 'text/csv'
        expect(response.headers['Content-Disposition']).to eq 'attachment; filename=stops.csv'
      end

      it 'should include column headers and row values' do
        get :index, format: :csv, bbox: '-122.4131,37.7136,-122.3789,37.8065'
        expect(response.body.lines.count).to eq 3
        expect(response.body).to start_with('Onestop ID,Name,Operators serving stop (names),Operators serving stop (Onestop IDs),Latitude (centroid),Longitude (centroid)')
        expect(response.body).to include("#{@metro_embarcadero.onestop_id},#{@metro_embarcadero.name},#{@sfmta.name},#{@sfmta.onestop_id},#{@metro_embarcadero.geometry(as: :wkt).lat},#{@metro_embarcadero.geometry(as: :wkt).lon}")
      end
    end
  end

  context '?include ?exclude' do
    it 'includes issues' do
      stop = Stop.first
      Issue.create!(issue_type: 'stop_name').entities_with_issues.create!(entity: stop, entity_attribute: 'name')
      get :index, include: 'issues'
      expect_json({stops: -> (stops) {
        expect(stops.first[:issues].size).to eq 1
      }})
      get :index, embed_issues: 'true'
      expect_json({stops: -> (stops) {
        expect(stops.first[:issues].size).to eq 1
      }})
    end

    it 'excludes issues' do
      stop = Stop.first
      Issue.create!(issue_type: 'stop_name').entities_with_issues.create!(entity: stop, entity_attribute: 'name')
      get :index, exclude: 'issues'
      expect_json({stops: -> (stops) {
        expect(stops.first[:issues]).to be_nil
      }})
      get :index, embed_issues: 'false'
      expect_json({stops: -> (stops) {
        expect(stops.first[:issues]).to be_nil
      }})
    end

    it 'includes geometry' do
      get :index, include: 'geometry'
      expect_json({ stops: -> (stops) {
        expect(stops.first.has_key?(:geometry)).to be true
      }})
      get :index, include_geometry: "true"
      expect_json({ stops: -> (stops) {
        expect(stops.first.has_key?(:geometry)).to be true
      }})
      get :index, exclude_geometry: "false"
      expect_json({ stops: -> (stops) {
        expect(stops.first.has_key?(:geometry)).to be true
      }})
    end

    it 'excludes geometry' do
      get :index, exclude: 'geometry'
      expect_json({ stops: -> (stops) {
        expect(stops.first.has_key?(:geometry)).to be false
      }})
      get :index, exclude_geometry: "true"
      expect_json({ stops: -> (stops) {
        expect(stops.first.has_key?(:geometry)).to be false
      }})
      get :index, include_geometry: "false"
      expect_json({ stops: -> (stops) {
        expect(stops.first.has_key?(:geometry)).to be false
      }})
    end
  end

  describe 'GET show' do
    it 'returns a single entity' do
      get :show, id: @metro_embarcadero.onestop_id
      expect_json_types({
        onestop_id: :string,
        geometry: :object,
        name: :string,
        created_at: :date,
        updated_at: :date
      })
      expect_json({ onestop_id: -> (onestop_id) {
        expect(onestop_id).to eq @metro_embarcadero.onestop_id
      }})
    end

    it 'returns a 404 when not found' do
      get :show, id: 'ntd9015-2053'
      expect(response.status).to eq 404
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Section 1.4.4.6.2</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="sec_1-4-4-6-1.html">
<LINK REL=UP HREF="sec_1-4-4-6.html">
<LINK REL=NEXT HREF="sec_1-4-4-6-3.html">

1.4.4.6.2 The ``Compound Type Specifier Syntax'' Section of a Dictionary Entry

This information about a type describes the syntax of a compound type specifier for that type.

Whether or not the type is acceptable as an atomic type specifier is not represented here; see Section 1.4.4.6 (Dictionary Entries for Type Specifiers).

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
package leonardo2204.com.br.flowtests.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import leonardo2204.com.br.flowtests.R;
import leonardo2204.com.br.flowtests.model.Contact;
import leonardo2204.com.br.flowtests.presenter.EditDialogPresenter;

/**
 * Created by leonardo on 4/13/16.
 */
public class EditDialogView extends FrameLayout {

    @Inject
    protected EditDialogPresenter presenter;
    @Inject
    protected Contact contact;

    @Bind(R.id.name)
    EditText name;

    public EditDialogView(Context context) {
        super(context);
    }

    public EditDialogView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditDialogView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        setupUI();
    }

    private void setupUI() {
        ButterKnife.bind(this);
        name.setText(contact.getName());
    }

    @OnClick(R.id.cancel)
    public void onCancelClick(View v) {

    }

    @OnClick(R.id.save)
    public void onSave(View v) {

    }

}


text:
MediaMinionTimer = class MediaMinionTimer {
    constructor (action, minion) {
        this.type = 'timer';

        this.action = action;
        this.minion = minion;

        this.settings = combineSettings(action.settings, minion.settings);

        this.set = sets.findOne(action.set);

        this.shown = false;
        this.removed = false;

        this.last = 0;

        var t = this.settings.timer_time;

        if (this.settings.timer_type == 'countdown') {
            this.target = action.time + (t.hours * 3600000) + (t.minutes * 60000) + (t.seconds * 1000);
        }
        // TODO add startAt and endAt timers!

        this.canvas = document.createElement('canvas');
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;

        this.cx = this.canvas.getContext('2d');

        this.cx.font = `${this.settings.timers_font_weight} ${this.settings.timers_font_size}px ${this.settings.timers_font}`;
        this.cx.fillStyle = this.settings.timers_font_color;
        this.cx.strokeStyle = `{this.settings.timers_font_shadow}px ${this.settings.timers_font_shadow_color}`;

        this.cx.textAlign = this.settings.timers_text_align;
        if (this.settings.timers_text_align == 'left') this.x = 0;
        else if (this.settings.timers_text_align == 'center') this.x = window.innerWidth/2;
        else if (this.settings.timers_text_align == 'right') this.x = window.innerWidth;

        if (this.settings.timers_text_vertical_align == 'top') {
            this.cx.textBaseline = 'top';
            this.y = 0;
        } else if (this.settings.timers_text_vertical_align == 'center') {
            this.cx.textBaseline = 'middle';
            this.y = window.innerHeight / 2 - this.settings.timers_font_size / 2;
        } else if (this.settings.timers_text_vertical_align == 'bottom') {
            this.cx.textBaseline = 'bottom';
            this.y = window.innerHeight - this.settings.timers_font_size;
        }

        this.texture = null;
        this.materials = [];
        this.meshes = [];
        this.opacity = 0;
    }

    update () {
        // TODO make all this settings, hard-coding for now due to time contraints
        var i = 0;

        if (this.shown && time.since(this.last) > 1000) {
            this.last = time.now();

            this.cx.clearRect(0, 0, window.innerWidth, window.innerHeight);

            var t = (this.target - this.last) * 0.001;
            var text = secondsToTimeString(t);

            this.cx.fillText(text, this.x, this.y);
            this.cx.strokeText(text, this.x, this.y);
            if (this.texture) this.texture.needsUpdate = true;
        }

        if (this.shown) Meteor.setTimeout(this.update.bind(this), 100);
    }

    show (old) {
        if (old) {
            old.hide();
            old.remove();
        }

        this.shown = true;
        this.update();

        this.texture = new THREE.Texture(this.canvas);
        this.texture.minFilter = THREE.LinearFilter;
        this.texture.magFilter = THREE.LinearFilter;
        this.texture.needsUpdate = true;

        this.minion.create_blocks(this);

        this.minion.fades.push({
            start: 0, end: 1,
            length: parseFloat(this.settings.timers_fade) * 1000,
            time: this.action.time,
            callback: (v) => {
                this.opacity = v;
                for (var n in this.materials) {
                    this.materials[n].uniforms.opacity.value = v;
                }
            }
        });
    }

    hide () {
        this.shown = false;

        this.minion.fades.push({
            start: 1, end: 0,
            length: parseFloat(this.settings.timers_fade) * 1000,
            time: time.now(),
            callback: (v) => {
                for (var n in this.materials) {
                    this.opacity = v;
                    this.materials[n].uniforms.opacity.value = v;
                }

                if (v == 0) {
                    for (var i in this.meshes) {
                        this.minion.scene.remove(this.meshes[i]);
                    }

                    this.canremove = true;
                }
            }
        });
    }

    remove () {
        $(this.canvas).remove();
        this.removed = true;
    }
}


text:
package com.thoughtworks.go.server.transaction;

import com.thoughtworks.go.config.GoConfigDao;
import com.thoughtworks.go.domain.User;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.dao.DatabaseAccessHelper;
import com.thoughtworks.go.server.dao.UserDao;
import com.thoughtworks.go.server.database.DatabaseStrategy;
import com.thoughtworks.go.util.GoConfigFileHelper;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:WEB-INF/applicationContext-global.xml",
        "classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
        "classpath:testPropertyConfigurer.xml",
        "classpath:WEB-INF/spring-all-servlet.xml",
})
public class GoCDSqlSessionDaoSupportTest {
    @Autowired private GoConfigDao goConfigDao;
    @Autowired private GoCache goCache;
    @Autowired private DatabaseAccessHelper dbHelper;
    @Autowired private TransactionTemplate transactionTemplate;
    @Autowired private SqlSessionFactory sqlMapClient;
    @Autowired private UserDao userDao;
    @Autowired private SystemEnvironment systemEnvironment;
    @Autowired private DatabaseStrategy databaseStrategy;

    private GoConfigFileHelper configHelper = new GoConfigFileHelper();
    private SqlMapClientDaoSupport daoSupport;
    private TransactionCacheAssertionUtil assertionUtil;

    @Before
    public void setUp() throws Exception {
        assertionUtil = new TransactionCacheAssertionUtil(goCache, transactionTemplate);
        configHelper.usingCruiseConfigDao(goConfigDao);
        configHelper.onSetUp();
        dbHelper.onSetUp();
        goCache.clear();
        daoSupport = new SqlMapClientDaoSupport(goCache, sqlMapClient, systemEnvironment, databaseStrategy) {

        };
    }

    @After
    public void tearDown() throws Exception {
        dbHelper.onTearDown();
        configHelper.onTearDown();
    }

    @Test
    public void shouldOptOutOfCacheServing_forInsert() {
        assertionUtil.assertCacheBehaviourInTxn(new TransactionCacheAssertionUtil.DoInTxn() {
            public void invoke() {
                userDao.saveOrUpdate(new User("loser", "Massive Loser", "boozer@loser.com"));
            }
        });
        assertThat(userDao.findUser("loser").getEmail(), is("boozer@loser.com"));
    }

    @Test
    public void shouldNotOptOutOfCacheServing_whenQueryingObjects() {
        final User loser = new User("loser");
        userDao.saveOrUpdate(loser);
        final User[] loadedUser = new User[1];

        assertThat(assertionUtil.doInTxnWithCachePut(new TransactionCacheAssertionUtil.DoInTxn() {
            public void invoke() {
                loadedUser[0] = userDao.findUser(loser.getName());
            }
        }), is("boozer"));

        assertThat(loadedUser[0].getName(), is("loser"));
    }

    @Test
    public void shouldNotOptOutOfCacheServing_whenQueryingList() {
        final User loser = new User("loser");
        userDao.saveOrUpdate(loser);

        final User[] loadedUser = new User[1];

        assertThat(assertionUtil.doInTxnWithCachePut(new TransactionCacheAssertionUtil.DoInTxn() {
            public void invoke() {
                loadedUser[0] = userDao.allUsers().get(0);
            }
        }), is("boozer"));

        assertThat(loadedUser[0].getName(), is("loser"));
    }

}


text:
local luaj = {}

local callJavaStaticMethod = LuaJavaBridge.callStaticMethod

local function checkArguments(args, sig)
    if type(args) ~= "table" then args = {} end
    if sig then return args, sig end

    sig = {"("}
    for i, v in ipairs(args) do
        local t = type(v)
        if t == "number" then
            sig[#sig + 1] = "F"
        elseif t == "boolean" then
            sig[#sig + 1] = "Z"
        elseif t == "function" then
            sig[#sig + 1] = "I"
        else
            sig[#sig + 1] = "Ljava/lang/String;"
        end
    end
    sig[#sig + 1] = ")V"

    return args, table.concat(sig)
end

function luaj.callStaticMethod(className, methodName, args, sig)
    local args, sig = checkArguments(args, sig)
    --echoInfo("luaj.callStaticMethod(\"%s\",\n\t\"%s\",\n\targs,\n\t\"%s\"", className, methodName, sig)
    return callJavaStaticMethod(className, methodName, args, sig)
end

return luaj


text:
from __future__ import unicode_literals

def get_admin_urls():
    from django.conf.urls import include, url
    from django.contrib import admin
    from django.conf import settings
    return [url(r'^%s' % settings.ADMIN_URL, include(admin.site.urls))]


text:
/**
 * @fileoverview Base class for comment events.
 */
'use strict';

/**
 * Base class for comment events.
 * @class
 */
goog.module('Blockly.Events.CommentBase');

const Xml = goog.require('Blockly.Xml');
const eventUtils = goog.require('Blockly.Events.utils');
const utilsXml = goog.require('Blockly.utils.xml');
const {Abstract: AbstractEvent} = goog.require('Blockly.Events.Abstract');
/* eslint-disable-next-line no-unused-vars */
const {CommentCreate} = goog.requireType('Blockly.Events.CommentCreate');
/* eslint-disable-next-line no-unused-vars */
const {CommentDelete} = goog.requireType('Blockly.Events.CommentDelete');
/* eslint-disable-next-line no-unused-vars */
const {WorkspaceComment} = goog.requireType('Blockly.WorkspaceComment');

/**
 * Abstract class for a comment event.
 * @extends {AbstractEvent}
 * @alias Blockly.Events.CommentBase
 */
class CommentBase extends AbstractEvent {
  /**
   * @param {!WorkspaceComment=} opt_comment The comment this event
   *     corresponds to.  Undefined for a blank event.
   */
  constructor(opt_comment) {
    super();
    /**
     * Whether or not an event is blank.
     * @type {boolean}
     */
    this.isBlank = typeof opt_comment === 'undefined';

    /**
     * The ID of the comment this event pertains to.
     * @type {string}
     */
    this.commentId = this.isBlank ? '' : opt_comment.id;

    /**
     * The workspace identifier for this event.
     * @type {string}
     */
    this.workspaceId = this.isBlank ? '' : opt_comment.workspace.id;

    /**
     * The event group id for the group this event belongs to. Groups define
     * events that should be treated as an single action from the user's
     * perspective, and should be undone together.
     * @type {string}
     */
    this.group = eventUtils.getGroup();

    /**
     * Sets whether the event should be added to the undo stack.
     * @type {boolean}
     */
    this.recordUndo = eventUtils.getRecordUndo();
  }

  /**
   * Encode the event as JSON.
   * @return {!Object} JSON representation.
   */
  toJson() {
    const json = super.toJson();
    if (this.commentId) {
      json['commentId'] = this.commentId;
    }
    return json;
  }

  /**
   * Decode the JSON event.
   * @param {!Object} json JSON representation.
   */
  fromJson(json) {
    super.fromJson(json);
    this.commentId = json['commentId'];
  }

  /**
   * Helper function for Comment[Create|Delete]
   * @param {!CommentCreate|!CommentDelete} event
   *     The event to run.
   * @param {boolean} create if True then Create, if False then Delete
   */
  static CommentCreateDeleteHelper(event, create) {
    const workspace = event.getEventWorkspace_();
    if (create) {
      const xmlElement = utilsXml.createElement('xml');
      xmlElement.appendChild(event.xml);
      Xml.domToWorkspace(xmlElement, workspace);
    } else {
      const comment = workspace.getCommentById(event.commentId);
      if (comment) {
        comment.dispose();
      } else {
        // Only complain about root-level block.
        console.warn(
            'Can\'t uncreate non-existent comment: ' + event.commentId);
      }
    }
  }
}

exports.CommentBase = CommentBase;


text: from .webs import URLS


text:
<?php

  namespace osCommerce\OM\Core\Site\Admin\Application\ServerInfo;

  class ServerInfo extends \osCommerce\OM\Core\ApplicationModelAbstract { }
?>


text:
from AbstractPowerCalculator import AbstractPowerCalculator
from LinearInterpolationPowerCalculator import interp

'''
Tacx Blue Motion power calculator. Uses fixed lever position 4.
'''
class TacxBlueMotionPowerCalculator(AbstractPowerCalculator):
    def __init__(self):
        super(TacxBlueMotionPowerCalculator, self).__init__()
        self.wheel_circumference = 2.122  # default value - can be overridden in config.py

    # Data from the diagram of Tacx Blue Motion 4/10:
    # http://www.powercurvesensor.com/cycling-trainer-power-curves/
    # speed values
    xp = [0.0, 5.0, 10.0, 15.0, 20.0, 25.0,
          30.0, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0]
    # power values
    yp = [0.0, 33.0, 65.0, 100.0, 135.0, 175.0,
          217.0, 260.0, 308.0, 364.0, 424.0, 488.0, 560.0]

    def power_from_speed(self, revs_per_sec):
        kms_per_rev = self.wheel_circumference / 1000.0
        speed = revs_per_sec * 3600 * kms_per_rev
        power = int(interp(self.xp, self.yp, speed))
        return power

    def set_wheel_circumference(self, circumference):
        self.wheel_circumference = circumference


text:
package org.apache.storm.trident.operation;

import java.util.Map;
import java.util.Set;
import org.apache.storm.generated.SharedMemory;

/**
 * This interface is implemented by various Trident classes in order to gather and propogate resources that have been set on them.
 *
 * @see ResourceDeclarer
 */
public interface ITridentResource {
    /**
     * Get resource.
     * @return a name of resource name -> amount of that resource. *Return should never be null!*
     */
    Map<String, Number> getResources();

    /**
     * Get shared memory.
     * @return the shared memory region requests
     */
    Set<SharedMemory> getSharedMemory();
}


text:
import warnings
import json

from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.contrib.sites.models import Site
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib import messages

try:
    from django.utils.encoding import force_text
except ImportError:
    from django.utils.encoding import force_unicode as force_text

from ..utils import (import_attribute, get_user_model,
                     generate_unique_username,
                     resolve_url)

from . import app_settings

class DefaultAccountAdapter(object):

    def stash_verified_email(self, request, email):
        request.session['account_verified_email'] = email

    def unstash_verified_email(self, request):
        ret = request.session.get('account_verified_email')
        request.session['account_verified_email'] = None
        return ret

    def is_email_verified(self, request, email):
        """
        Checks whether or not the email address is already verified
        beyond allauth scope, for example, by having accepted an
        invitation before signing up.
        """
        ret = False
        verified_email = request.session.get('account_verified_email')
        if verified_email:
            ret = verified_email.lower() == email.lower()
        return ret

    def format_email_subject(self, subject):
        prefix = app_settings.EMAIL_SUBJECT_PREFIX
        if prefix is None:
            site = Site.objects.get_current()
            prefix = u"[{name}] ".format(name=site.name)
        return prefix + force_text(subject)

    def render_mail(self, template_prefix, email, context):
        """
        Renders an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "account/email/email_confirmation"
        """
        subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject)

        bodies = {}
        for ext in ['html', 'txt']:
            try:
                template_name = '{0}_message.{1}'.format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name,
                                               context).strip()
            except TemplateDoesNotExist:
                if ext == 'txt' and not bodies:
                    # We need at least one body
                    raise
        if 'txt' in bodies:
            msg = EmailMultiAlternatives(subject,
                                         bodies['txt'],
                                         settings.DEFAULT_FROM_EMAIL,
                                         [email])
            if 'html' in bodies:
                msg.attach_alternative(bodies['html'], 'text/html')
        else:
            msg = EmailMessage(subject,
                               bodies['html'],
                               settings.DEFAULT_FROM_EMAIL,
                               [email])
            msg.content_subtype = 'html'  # Main content is now text/html
        return msg

    def send_mail(self, template_prefix, email, context):
        msg = self.render_mail(template_prefix, email, context)
        msg.send()

    def get_login_redirect_url(self, request):
        """
        Returns the default URL to redirect to after logging in.  Note
        that URLs passed explicitly (e.g. by passing along a `next`
        GET parameter) take precedence over the value returned here.
        """
    #    assert request.user.is_authenticated()
        url = getattr(settings, "LOGIN_REDIRECT_URLNAME", None)
        if url:
            warnings.warn("LOGIN_REDIRECT_URLNAME is deprecated, simply"
                          " use LOGIN_REDIRECT_URL with a URL name",
                          DeprecationWarning)
        else:
            url = settings.LOGIN_REDIRECT_URL
        return resolve_url(url)

    def get_logout_redirect_url(self, request):
        """
        Returns the URL to redriect to after the user logs out. Note that
        this method is also invoked if you attempt to log out while no users
        is logged in. Therefore, request.user is not guaranteed to be an
        authenticated user.
        """
        return resolve_url(app_settings.LOGOUT_REDIRECT_URL)

    def get_email_confirmation_redirect_url(self, request):
        """
        The URL to return to after successful e-mail confirmation.
        """
        if request.user.is_authenticated():
            if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:
                return  \
                    app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
            else:
                return self.get_login_redirect_url(request)
        else:
            return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL

    def is_open_for_signup(self, request):
        """
        Checks whether or not the site is open for signups.

        Next to simply returning True/False you can also intervene the
        regular flow by raising an ImmediateHttpResponse
        """
        return True

    def new_user(self, request):
        """
        Instantiates a new User instance.
        """
        user = get_user_model()()
        return user

    def populate_username(self, request, user):
        """
        Fills in a valid username, if required and missing.  If the
        username is already present it is assumed to be valid
        (unique).
        """
        from .utils import user_username, user_email, user_field
        first_name = user_field(user, 'first_name')
        last_name = user_field(user, 'last_name')
        email = user_email(user)
        username = user_username(user)
        if app_settings.USER_MODEL_USERNAME_FIELD:
            user_username(user,
                          username
                          or generate_unique_username([first_name,
                                                       last_name,
                                                       email,
                                                       'user']))

    def save_user(self, request, user, form, commit=True):
        """
        Saves a new `User` instance using information provided in the
        signup form.
        """
        from .utils import user_username, user_email, user_field

        data = form.cleaned_data
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        username = data.get('username')
        user_email(user, email)
        user_username(user, username)
        user_field(user, 'first_name', first_name or '')
        user_field(user, 'last_name', last_name or '')
        if 'password1' in data:
            user.set_password(data["password1"])
        else:
            user.set_unusable_password()
        self.populate_username(request, user)
        if commit:
            # Ability not to commit makes it easier to derive from
            # this adapter by adding
            user.save()
        return user

    def clean_username(self, username):
        """
        Validates the username. You can hook into this if you want to
        (dynamically) restrict what usernames can be chosen.
        """
        from django.contrib.auth.forms import UserCreationForm
        USERNAME_REGEX = UserCreationForm().fields['username'].regex
        if not USERNAME_REGEX.match(username):
            raise forms.ValidationError(_("Usernames can only contain "
                                          "letters, digits and @/./+/-/_."))

        # TODO: Add regexp support to USERNAME_BLACKLIST
        if username in app_settings.USERNAME_BLACKLIST:
            raise forms.ValidationError(_("Username can not be used. "
                                          "Please use other username."))
        username_field = app_settings.USER_MODEL_USERNAME_FIELD
        assert username_field
        user_model = get_user_model()
        try:
            query = {username_field + '__iexact': username}
            user_model.objects.get(**query)
        except user_model.DoesNotExist:
            return username
        raise forms.ValidationError(_("This username is already taken. Please "
                                      "choose another."))

    def clean_email(self, email):
        """
        Validates an email value. You can hook into this if you want to
        (dynamically) restrict what email addresses can be chosen.
        """
        return email

    def add_message(self, request, level, message_template,
                    message_context={}, extra_tags=''):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            try:
                message = render_to_string(message_template,
                                           message_context).strip()
                if message:
                    messages.add_message(request, level, message,
                                         extra_tags=extra_tags)
            except TemplateDoesNotExist:
                pass

    def ajax_response(self, request, response, redirect_to=None, form=None):
        data = {}
        if redirect_to:
            status = 200
            data['location'] = redirect_to
        if form:
            if form.is_valid():
                status = 200
            else:
                status = 400
                data['form_errors'] = form._errors
            if hasattr(response, 'render'):
                response.render()
            data['html'] = response.content.decode('utf8')
        return HttpResponse(json.dumps(data),
                            status=status,
                            content_type='application/json')

    def login(self, request, user):
        from django.contrib.auth import login
        # HACK: This is not nice. The proper Django way is to use an
        # authentication backend
        if not hasattr(user, 'backend'):
            user.backend \
                = "allauth.account.auth_backends.AuthenticationBackend"
        login(request, user)

def get_adapter():
    return import_attribute(app_settings.ADAPTER)()


text:
package org.wso2.andes.server.management;

import org.wso2.andes.AMQException;

import javax.management.JMException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

/**
 * This should be implemented by all Managable objects.
 */
public interface ManagedObject
{
    static final String DOMAIN = "org.wso2.andes";

    /**
     * @return the name that uniquely identifies this object instance. It must be
     * unique only among objects of this type at this level in the hierarchy so
     * the uniqueness should not be too difficult to ensure.
     */
    String getObjectInstanceName();

    String getType();

    Class<?> getManagementInterface();

    ManagedObject getParentObject();

    void register() throws AMQException, JMException;

    void unregister() throws AMQException;

    /**
     * Returns the ObjectName required for the mbeanserver registration.
     * @return ObjectName
     * @throws MalformedObjectNameException
     */
    ObjectName getObjectName() throws MalformedObjectNameException;
}


text:
Bowser
======

A WebRTC browser for iOS developed in the open. Bowser is built on top of [OpenWebRTC](https://github.com/EricssonResearch/openwebrtc).

![Bowser logo](http://static.squarespace.com/static/53f1eedee4b0439bf8d480c5/t/53f25022e4b0cca46a383183/1408389154850/?format=500w "Bowser logo")

## App Store
Bowser is not only Open Source, it is also available as a [free download](https://itunes.apple.com/app/bowser/id560478358?mt=8) on the Apple App Store. When improvements have been made to Bowser or OpenWebRTC new versions for the App Store are published by Ericsson Research.

[![Bowser video](http://img.youtube.com/vi/mR_-2trCjzE/0.jpg)](http://www.youtube.com/watch?v=mR_-2trCjzE)

## Developing for Bowser
Tips and other resources can be found on the wiki page [Developing for Bowser](https://github.com/EricssonResearch/bowser/wiki/Developing-for-Bowser).

## Extension of UIWebView
Bowser is based on the official `UIWebView` provided by the platform and the [WebRTC](http://www.w3.org/2011/04/webrtc/) API's are implemented with JavaScript that is injected into web pages as they load, the injected JavaScript code is using remote procedure calls to control the [OpenWebRTC](https://github.com/EricssonResearch/openwebrtc) backend.

The [plan](https://github.com/EricssonResearch/bowser/issues/1) is to move to the `WKWebView`, introduced in iOS 8, as soon as possible.

## Video rendering
Mobile Safari on iPhone displays `<video>` elements only in fullscreen. This severely limits the UI of your apps, especially when designing video communication apps using WebRTC. Bowser goes beyond that and allows you to fully customise and manipulate `<video>` elements using CSS and JavaScript.

## Building
To build Bowser you need a completed build of [OpenWebRTC](https://github.com/EricssonResearch/openwebrtc), Xcode and the iOS SDK. The build itself is pretty simple as we have set up the header/library search paths to expect that you cloned Bowser alongside OpenWebRTC. As long as you have:
```
/path/to/bowser
/path/to/openwebrtc
```
...then you shouldn't have any problems with just opening the Xcode project and building.

## Debugging WebRTC scripts
As Bowser is using the official `UIWebView` that is provided by the iOS platform you can use [Apple's Web Developer Tools](https://developer.apple.com/safari/tools/) to debug your WebRTC scripts. It is also possible to use Safari on OS X to debug Bowser. The details are described in this [blog post](http://www.openwebrtc.org/blog/2014/10/31/webrtc-in-safari-using-openwebrtc).

## Background
Bowser was originally developed by Ericsson Research and released in October of 2012, for both iOS and Android devices. Back then Bowser was the world's first WebRTC-enabled browser for mobile devices. Bowser was later removed from the Apple App Store and Google Play but was resurrected and released as Open Source together with OpenWebRTC.

## License
Bowser is released under BSD-2 clause. See LICENSE for details.


text:
<?php

namespace PHPExiftool\Driver\Tag\XMPCrs;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class LensManualDistortionAmount extends AbstractTag
{

    protected $Id = 'LensManualDistortionAmount';

    protected $Name = 'LensManualDistortionAmount';

    protected $FullName = 'XMP::crs';

    protected $GroupName = 'XMP-crs';

    protected $g0 = 'XMP';

    protected $g1 = 'XMP-crs';

    protected $g2 = 'Image';

    protected $Type = 'integer';

    protected $Writable = true;

    protected $Description = 'Lens Manual Distortion Amount';
}


text:
Spree Scan And Go
==============

Find orders, shipments and users with you barcode scanner.
This extension is usefull when you use a barcode scanner with you Spree shop.
If you print a barcode to your printable orders or packing slips, you can easily scan this barcode to view the order or shipment in your Spree admin.

For user without a barcode scanner: it's also pretty handy to just find stuff very fast from every admin screen. The scan and go bar will be on the bottom of every screen.

Created for Spree 2-1-stable (2.1.4)

Installation
------------

Add spree_scan_and_go to your Gemfile:

```ruby
gem 'spree_scan_and_go', github: 'reinaris/spree_scan_and_go'
```

Bundle your dependencies and run the installation generator:

```shell
bundle
bundle exec rails g spree_scan_and_go:install
```


text:
using System;
using System.Linq;
using Google.Apis.Drive.v2.Data;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Oblqo.Google
{
    public class GoogleFile : DriveFile
    {
        public const int PropertyMaxLength = 124 / 2;

        internal bool hasChildren;

        public GoogleFile(GoogleDrive drive, File file)
            : base(drive)
        {
            this.File = file;
        }

        public File File { get; }

        public override string Id => File.Id;

        public override bool IsImage => File.MimeType.StartsWith("image/");

        public override bool IsFolder => File.MimeType == GoogleMimeTypes.Folder;

        public override string Name => File.Title;

        public override bool HasChildren => hasChildren;

        public override long Size => File.FileSize.GetValueOrDefault();

        public override DateTime ModifiedDate => File.ModifiedDate.GetValueOrDefault();

        public override DateTime CreatedDate => File.CreatedDate.GetValueOrDefault();

        public override int OriginalImageWidth
        {
            get
            {
                if (File.Properties == null)
                    return ImageWidth;
                var property = File.Properties.FirstOrDefault(x => x.Key == "OriginalImageWidth");
                return property == null ? ImageWidth : int.Parse(property.Value);
            }
            set
            {
                File.Properties.Add(new Property() { Key = "OriginalImageWidth", Value = value.ToString() });
            }
        }

        public override int OriginalImageHeight
        {
            get
            {
                if (File.Properties == null)
                    return ImageHeight;
                var property = File.Properties.FirstOrDefault(x => x.Key == "OriginalImageHeight");
                return property == null ? ImageHeight : int.Parse(property.Value);
            }
            set
            {
                if (File.Properties == null)
                {
                    File.Properties = new List<Property>();
                }
                File.Properties.Add(new Property() { Key = "OriginalImageHeight", Value = value.ToString() });
            }
        }

        public override long OriginalSize
        {
            get
            {
                if (File.Properties == null)
                    return Size;
                var property = File.Properties.FirstOrDefault(x => x.Key == "OriginalSize");
                return property == null ? Size : long.Parse(property.Value);
            }
            set
            {
                File.Properties.Add(new Property() { Key = "OriginalSize", Value = value.ToString() });
            }
        }

        public override int ImageWidth => File.ImageMediaMetadata?.Width != null ? File.ImageMediaMetadata.Width.Value : 0;

        public override int ImageHeight => File.ImageMediaMetadata?.Height != null ? File.ImageMediaMetadata.Height.Value : 0;

        public override bool IsRoot => Id == GoogleDrive.RootId;

        public override string MimeType => File.MimeType;

        public override System.Xml.Linq.XElement ToXml()
        {
            var ret = base.ToXml();
            ret.SetAttributeValue("fileId", File.Id);
            return ret;
        }

        public static int GetNumericValue(char c)
        {
            return c - '0';
        }

        private string PropertyValue(string key)
        {
            return File.Properties == null ? null : (from prop in File.Properties where prop.Key == key select prop.Value).FirstOrDefault();
        }

        public override string GetAttribute(string name)
        {
            if (File.Properties == null)
            {
                return null;
            }

            var ret = PropertyValue(name);
            if (ret != null)
            {
                return ret;
            }

            // gl-1.id-{1}
            var fileIdKeyLen = string.Format("{0}-{1}", name, 0).Length;
            var startsWith = string.Format("{0}-{1}", name, "");
            var parts = new string[9];

            foreach (var prop in File.Properties)
            {
                if (prop.Key.Length == fileIdKeyLen
                    && prop.Key.StartsWith(startsWith)
                    && char.IsDigit(prop.Key.Last()))
                {
                    parts[GetNumericValue(prop.Key.Last())] = prop.Value;
                }
            }
            return string.Join("", parts);
        }

        public override async Task SetAttributeAsync(string name, string value, CancellationToken token)
        {

            // Initializing properties.
            var props = new List<Property>();

            // Field
            var keyLen = string.Format(Drive.StorageFileIdFormat, Drive.Storage.Kind, 0).Length;
            var valueLen = PropertyMaxLength - keyLen;
            if (value.Length <= valueLen)
            {
                props.Add(new Property { Key = name, Value = value, Visibility = "PRIVATE" });
            }
            else
            {
                var storageFileIdParts = Common.SplitBy(value, valueLen);
                if (storageFileIdParts.Length > 9) throw new Exception("Storage file ID is too long");
                props.AddRange(storageFileIdParts.Select((t, i) => new Property {Key = name + "-" + i, Value = t, Visibility = "PRIVATE"}));
            }

            var service = await((GoogleDrive)Drive).GetServiceAsync(token);
            await service.Files.Update(new File { Properties = props }, File.Id).ExecuteAsync(token);
            await Task.Delay(1000, token);
        }

        public override async Task WriteAsync(byte[] bytes, CancellationToken token)
        {
            var stream = new System.IO.MemoryStream(bytes, false);
            var service = await ((GoogleDrive)Drive).GetServiceAsync(token);
            await service.Files.Update(File, File.Id, stream, File.MimeType).UploadAsync(token);
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Handb. Allgem. mykol. (Stuttgart) 160 (1851)

#### Original name
Thelephora radiosa Fr., 1818

### Remarks
null


text:
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { IndexLink, NavLink } from 'react-router';
import AboutComponent from '../../components/About';

export default class About extends Component {
  render() {
    const { todos, actions, children } = this.props;

    return (
      <AboutComponent />
    );
  }
}


text:
namespace geometry {
namespace spatial {

namespace {
using Vec3 = Eigen::Vector3d;
// Moller-Trumbore
Intersection intersect_triangle(const Vec3 &orig,
                                const Vec3 &dir,
                                const Vec3 &vert0,
                                const Vec3 &vert1,
                                const Vec3 &vert2) {
  // SUB(edge1, vert1, vert0);
  const Vec3 edge1 = vert1 - vert0;
  // SUB(edge2, vert2, vert0);
  const Vec3 edge2 = vert2 - vert0;

  // CROSS(pvec, dir, edge2);
  const Vec3 pvec = dir.cross(edge2);

  // det = DOT(edge1, pvec);
  const double det = edge1.dot(pvec);

  constexpr double EPS = 1e-6;
  if (det > -EPS && det < EPS) {
    return Intersection::no_intersection();
  }
  const double inv_det = 1.0 / det;
  // SUB(tvec, orig, vert0);
  const Vec3 tvec = orig - vert0;

  // *u = DOT(tvec, pvec) * inv_det;
  const double u = tvec.dot(pvec) * inv_det;
  if (u < 0.0 || u > 1.0) {
    return Intersection::no_intersection();
  }
  // CROSS(qvec, tvec, edge1);
  const Vec3 qvec = tvec.cross(edge1);
  // *v = DOT(dir, qvec) * inv_det;
  const double v = dir.dot(qvec) * inv_det;
  if (v < 0.0 || u + v > 1.0) {
    return Intersection::no_intersection();
  }

  // *t = DOT(edge2, qvec) * inv_det;
  const double t = edge2.dot(qvec) * inv_det;
  Intersection intersection;
  intersection.distance = t;
  intersection.intersected = t > 0.0;
  return intersection;
}
}  // namespace

class TriangleVolume final : public Volume {
 public:
  TriangleVolume(const std::array<Vec3, 3> &vertices) : vertices_(vertices) {
  }
  Intersection intersect(const Ray &ray) const override {
    return intersect_triangle(
        ray.origin, ray.direction, vertices_[0], vertices_[1], vertices_[2]);
  }
  Sphere bounding_sphere() const override {
    return {};
  }

  BoundingBox<3> bounding_box() const override {
    BoundingBox<3> box;
    for (const auto &vert : vertices_) {
      box.expand(vert);
    }
    return box;
  }

  bool does_intersect(const Ray &ray) const override {
    return {};
  }

 private:
  std::array<Vec3, 3> vertices_;
};
}  // namespace spatial
}


text:
package hudson.plugins.cobertura;

import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractItem;
import hudson.model.AbstractProject;
import hudson.plugins.cobertura.renderers.SourceCodePainter;
import hudson.plugins.cobertura.renderers.SourceEncoding;
import hudson.plugins.cobertura.targets.CoverageMetric;
import hudson.plugins.cobertura.targets.CoverageTarget;
import hudson.plugins.cobertura.targets.CoverageResult;
import hudson.remoting.VirtualChannel;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;

import java.io.File;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.ConvertUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * Cobertura {@link Publisher}.
 *
 * @author Stephen Connolly
 */
public class CoberturaPublisher extends Recorder {

	private final String coberturaReportFile;

	private final boolean onlyStable;

	private final boolean failUnhealthy;

	private final boolean failUnstable;

	private final boolean autoUpdateHealth;

	private final boolean autoUpdateStability;

	private final boolean zoomCoverageChart;

	private final boolean copyHealth;

	private final String neighbourJobName;

	private final int maxNumberOfBuilds;

	private boolean failNoReports = true;

	private CoverageTarget healthyTarget;

	private CoverageTarget unhealthyTarget;

	private CoverageTarget failingTarget;

	public static final CoberturaReportFilenameFilter COBERTURA_FILENAME_FILTER = new CoberturaReportFilenameFilter();

	private static final Logger logger = Logger
			.getLogger(CoberturaPublisher.class.getName());

	private final SourceEncoding sourceEncoding;

	/**
	 * @param coberturaReportFile
	 *            the report directory
	 * @stapler-constructor
	 */
	@DataBoundConstructor
	public CoberturaPublisher(String coberturaReportFile, boolean onlyStable,
			boolean failUnhealthy, boolean copyHealth, boolean failUnstable,
			boolean autoUpdateHealth, boolean autoUpdateStability,
			boolean zoomCoverageChart, boolean failNoReports,
			SourceEncoding sourceEncoding, int maxNumberOfBuilds,
			String neighbourJobName) {
		this.coberturaReportFile = coberturaReportFile;
		this.onlyStable = onlyStable;
		this.failUnhealthy = failUnhealthy;
		this.copyHealth = copyHealth;
		this.neighbourJobName = neighbourJobName;
		this.failUnstable = failUnstable;
		this.autoUpdateHealth = autoUpdateHealth;
		this.autoUpdateStability = autoUpdateStability;
		this.zoomCoverageChart = zoomCoverageChart;
		this.failNoReports = failNoReports;
		this.sourceEncoding = sourceEncoding;
		this.maxNumberOfBuilds = maxNumberOfBuilds;
		this.healthyTarget = new CoverageTarget();
		this.unhealthyTarget = new CoverageTarget();
		this.failingTarget = new CoverageTarget();
	}

	/**
	 * Getter for property 'targets'.
	 *
	 * @return Value for property 'targets'.
	 */
	public List<CoberturaPublisherTarget> getTargets() {
		Map<CoverageMetric, CoberturaPublisherTarget> targets = new TreeMap<CoverageMetric, CoberturaPublisherTarget>();
		float checker;
		for (CoverageMetric metric : healthyTarget.getTargets()) {
			CoberturaPublisherTarget target = targets.get(metric);
			if (target == null) {
				target = new CoberturaPublisherTarget();
				target.setMetric(metric);
			}
			checker = (float) healthyTarget.getTarget(metric) / 100000f;
			if (checker <= 0.001f) {
				checker = (float) (Math.round(checker * 100000f));
			}
			target.setHealthy(checker);
			targets.put(metric, target);
		}
		for (CoverageMetric metric : unhealthyTarget.getTargets()) {
			CoberturaPublisherTarget target = targets.get(metric);
			if (target == null) {
				target = new CoberturaPublisherTarget();
				target.setMetric(metric);
			}
			checker = (float) unhealthyTarget.getTarget(metric) / 100000f;
			if (checker <= 0.001f) {
				checker = (float) (Math.round(checker * 100000f));
			}
			target.setUnhealthy(checker);
			targets.put(metric, target);
		}
		for (CoverageMetric metric : failingTarget.getTargets()) {
			CoberturaPublisherTarget target = targets.get(metric);
			if (target == null) {
				target = new CoberturaPublisherTarget();
				target.setMetric(metric);
			}
			checker = (float) failingTarget.getTarget(metric) / 100000f;
			if (checker <= 0.001f) {
				checker = (float) (Math.round(checker * 100000f));
			}
			target.setUnstable(checker);
			targets.put(metric, target);
		}
		List<CoberturaPublisherTarget> result = new ArrayList<CoberturaPublisherTarget>(
				targets.values());
		return result;
	}

	/**
	 * Setter for property 'targets'.
	 *
	 * @param targets
	 *            Value to set for property 'targets'.
	 */
	private void setTargets(List<CoberturaPublisherTarget> targets) {
		// healthyTarget.clear();
		// unhealthyTarget.clear();
		// failingTarget.clear();
		float rounded;
		for (CoberturaPublisherTarget target : targets) {
			if (target.getHealthy() != null) {
				rounded = (Math.round((float) 100f * target.getHealthy()));
				rounded = roundDecimalFloat(rounded);
				healthyTarget.setTarget(target.getMetric(),
						(int) ((float) 100000f * rounded));
			}
			if (target.getUnhealthy() != null) {
				rounded = (Math.round((float) 100f * target.getUnhealthy()));
				rounded = roundDecimalFloat(rounded);
				unhealthyTarget.setTarget(target.getMetric(),
						(int) ((float) 100000f * rounded));
			}
			if (target.getUnstable() != null) {
				rounded = (Math.round((float) 100f * target.getUnstable()));
				rounded = roundDecimalFloat(rounded);
				failingTarget.setTarget(target.getMetric(),
						(int) ((float) 100000f * rounded));
			}
		}
	}

	/**
	 * Getter for property 'coberturaReportFile'.
	 *
	 * @return Value for property 'coberturaReportFile'.
	 */
	public String getCoberturaReportFile() {
		return coberturaReportFile;
	}

	/**
	 * Which type of build should be considered.
	 *
	 * @return the onlyStable
	 */
	public boolean getOnlyStable() {
		return onlyStable;
	}

	public int getMaxNumberOfBuilds() {
		return maxNumberOfBuilds;
	}

	/**
	 * Getter for property 'failUnhealthy'.
	 *
	 * @return Value for property 'failUnhealthy'.
	 */
	public boolean getFailUnhealthy() {
		return failUnhealthy;
	}

	public boolean getCopyHealth() {
		return copyHealth;
	}

	public String getNeighbourJobName() {
		return neighbourJobName;
	}

	/**
	 * Getter for property 'failUnstable'.
	 *
	 * @return Value for property 'failUnstable'.
	 */
	public boolean getFailUnstable() {
		return failUnstable;
	}

	/**
	 * Getter for property 'autoUpdateHealth'.
	 *
	 * @return Value for property 'autoUpdateHealth'.
	 */
	public boolean getAutoUpdateHealth() {
		return autoUpdateHealth;
	}

	/**
	 * Getter for property 'autoUpdateStability'.
	 *
	 * @return Value for property 'autoUpdateStability'.
	 */
	public boolean getAutoUpdateStability() {
		return autoUpdateStability;
	}

	public boolean getZoomCoverageChart() {
		return zoomCoverageChart;
	}

	public boolean isFailNoReports() {
		return failNoReports;
	}

	/**
	 * Getter for property 'healthyTarget'.
	 *
	 * @return Value for property 'healthyTarget'.
	 */
	public CoverageTarget getHealthyTarget() {
		return healthyTarget;
	}

	/**
	 * Setter for property 'healthyTarget'.
	 *
	 * @param healthyTarget
	 *            Value to set for property 'healthyTarget'.
	 */
	public void setHealthyTarget(CoverageTarget healthyTarget) {
		this.healthyTarget = healthyTarget;
	}

	/**
	 * Getter for property 'unhealthyTarget'.
	 *
	 * @return Value for property 'unhealthyTarget'.
	 */
	public CoverageTarget getUnhealthyTarget() {
		return unhealthyTarget;
	}

	/**
	 * Setter for property 'unhealthyTarget'.
	 *
	 * @param unhealthyTarget
	 *            Value to set for property 'unhealthyTarget'.
	 */
	public void setUnhealthyTarget(CoverageTarget unhealthyTarget) {
		this.unhealthyTarget = unhealthyTarget;
	}

	/**
	 * Getter for property 'failingTarget'.
	 *
	 * @return Value for property 'failingTarget'.
	 */
	public CoverageTarget getFailingTarget() {
		return failingTarget;
	}

	/**
	 * Setter for property 'failingTarget'.
	 *
	 * @param failingTarget
	 *            Value to set for property 'failingTarget'.
	 */
	public void setFailingTarget(CoverageTarget failingTarget) {
		this.failingTarget = failingTarget;
	}

	/**
	 * Gets the directory where the Cobertura Report is stored for the given
	 * project.
	 */
	/* package */
	static File getCoberturaReportDir(AbstractItem project) {
		return new File(project.getRootDir(), "cobertura");
	}

	/**
	 * Gets the directory where the Cobertura Report is stored for the given
	 * project.
	 */
	/* package */
	static File[] getCoberturaReports(AbstractBuild<?, ?> build) {
		return build.getRootDir().listFiles(COBERTURA_FILENAME_FILTER);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
			BuildListener listener) throws InterruptedException, IOException {
		listener.getLogger().println(
				"[Cobertura] Publishing Cobertura coverage report...");
		final FilePath[] moduleRoots = build.getModuleRoots();
		final boolean multipleModuleRoots = moduleRoots != null
				&& moduleRoots.length > 1;
		final FilePath moduleRoot = multipleModuleRoots ? build.getWorkspace()
				: build.getModuleRoot();
		final File buildCoberturaDir = build.getRootDir();
		FilePath buildTarget = new FilePath(buildCoberturaDir);

		FilePath[] reports = new FilePath[0];
		try {
			reports = moduleRoot.act(new ParseReportCallable(
					coberturaReportFile));

			// if the build has failed, then there's not
			// much point in reporting an error
			if (build.getResult().isWorseOrEqualTo(Result.FAILURE)
					&& reports.length == 0) {
				return true;
			}

		} catch (IOException e) {
			Util.displayIOException(e, listener);
			e.printStackTrace(listener
					.fatalError("Unable to find coverage results"));
			build.setResult(Result.FAILURE);
		}

		if (reports.length == 0) {
			String msg = "[Cobertura] No coverage results were found using the pattern '"
					+ coberturaReportFile
					+ "' relative to '"
					+ moduleRoot.getRemote()
					+ "'."
					+ "  Did you enter a pattern relative to the correct directory?"
					+ "  Did you generate the XML report(s) for Cobertura?";
			listener.getLogger().println(msg);
			if (failNoReports) {
				build.setResult(Result.FAILURE);
			} else {
				listener.getLogger().println(
						"[Cobertura] Skipped cobertura reports.");
			}
			return true;
		}

		for (int i = 0; i < reports.length; i++) {
			final FilePath targetPath = new FilePath(buildTarget, "coverage"
					+ (i == 0 ? "" : i) + ".xml");
			try {
				reports[i].copyTo(targetPath);
			} catch (IOException e) {
				Util.displayIOException(e, listener);
				e.printStackTrace(listener
						.fatalError("Unable to copy coverage from "
								+ reports[i] + " to " + buildTarget));
				build.setResult(Result.FAILURE);
			}
		}

		listener.getLogger()
				.println("Publishing Cobertura coverage results...");
		Set<String> sourcePaths = new HashSet<String>();
		CoverageResult result = null;
		for (File coberturaXmlReport : getCoberturaReports(build)) {
			try {
				result = CoberturaCoverageParser.parse(coberturaXmlReport,
						result, sourcePaths);
			} catch (IOException e) {
				Util.displayIOException(e, listener);
				e.printStackTrace(listener.fatalError("Unable to parse "
						+ coberturaXmlReport));
				build.setResult(Result.FAILURE);
			}
		}
		if (result != null) {
			listener.getLogger().println("Cobertura coverage report found.");
			result.setOwner(build);
			final FilePath paintedSourcesPath = new FilePath(new File(build
					.getProject().getRootDir(), "cobertura"));
			paintedSourcesPath.mkdirs();
			SourceCodePainter painter = new SourceCodePainter(
					paintedSourcesPath, sourcePaths,
					result.getPaintedSources(), listener, getSourceEncoding());

			moduleRoot.act(painter);
			final CoberturaBuildAction action = CoberturaBuildAction.load(
					build, result, healthyTarget, unhealthyTarget,
					getOnlyStable(), getFailUnhealthy(), getCopyHealth(),
					getFailUnstable(), getAutoUpdateHealth(),
					getAutoUpdateStability(), getNeighbourJobName());

			build.getActions().add(action);
			Set<CoverageMetric> failingMetrics = failingTarget
					.getFailingMetrics(result);
			if (!failingMetrics.isEmpty()) {
				listener.getLogger()
						.println(
								"Code coverage enforcement failed for the following metrics:");
				float oldStabilityPercent;
				float setStabilityPercent;
				for (CoverageMetric metric : failingMetrics) {
					oldStabilityPercent = failingTarget.getObservedPercent(
							result, metric);
					setStabilityPercent = failingTarget.getSetPercent(result,
							metric);
					listener.getLogger()
							.println(
									"    "
											+ metric.getName()
											+ "'s stability is "
											+ roundDecimalFloat(oldStabilityPercent * 100f)
											+ " and set mininum stability is "
											+ roundDecimalFloat(setStabilityPercent * 100f)
											+ ".");
				}
				if (!getFailUnstable()) {
					listener.getLogger().println("Setting Build to unstable.");
					build.setResult(Result.UNSTABLE);
				} else {
					listener.getLogger().println(
							"Failing build due to unstability.");
					build.setResult(Result.FAILURE);
				}
			}
			if (getFailUnhealthy()) {
				Set<CoverageMetric> unhealthyMetrics = unhealthyTarget
						.getFailingMetrics(result);
				if (!unhealthyMetrics.isEmpty()) {
					listener.getLogger().println(
							"Unhealthy for the following metrics:");
					float oldHealthyPercent;
					float setHealthyPercent;
					for (CoverageMetric metric : unhealthyMetrics) {
						oldHealthyPercent = unhealthyTarget.getObservedPercent(
								result, metric);
						setHealthyPercent = unhealthyTarget.getSetPercent(
								result, metric);
						listener.getLogger()
								.println(
										"    "
												+ metric.getName()
												+ "'s health is "
												+ roundDecimalFloat(oldHealthyPercent * 100f)
												+ " and set minimum health is "
												+ roundDecimalFloat(setHealthyPercent * 100f)
												+ ".");
					}
					listener.getLogger().println(
							"Failing build because it is unhealthy.");
					build.setResult(Result.FAILURE);
				}
			}
			if (build.getResult() == Result.SUCCESS) {
				if (getCopyHealth()) {
					String path = buildCoberturaDir.toString().substring(0,
							buildCoberturaDir.toString().indexOf("jobs"))
							+ "jobs/" + getNeighbourJobName() + "/config.xml";
					setMainJobPercentages(path, result,
							listener);
				} else {
					if (getAutoUpdateHealth()) {
						setNewPercentages(result, true, listener);
					}

					if (getAutoUpdateStability()) {
						setNewPercentages(result, false, listener);
					}
				}
			}
		} else {
			listener.getLogger().println(
					"No coverage results were successfully parsed.  Did you generate "
							+ "the XML report(s) for Cobertura?");
			build.setResult(Result.FAILURE);
		}

		return true;
	}

	/**
	 * Changes unhealthy or unstable percentage fields for ratcheting.
	 */
	private void setNewPercentages(CoverageResult result, boolean select,
			BuildListener listener) {
		Set<CoverageMetric> healthyMetrics = healthyTarget
				.getAllMetrics(result);
		float newPercent;
		float oldPercent;
		// copyJobTarget.
		if (!healthyMetrics.isEmpty()) {
			for (CoverageMetric metric : healthyMetrics) {
				newPercent = healthyTarget.getObservedPercent(result, metric);
				newPercent = (float) (Math.round(newPercent * 100f));
				if (select) {
					oldPercent = unhealthyTarget.getSetPercent(result, metric);
					oldPercent = (float) (Math.round(oldPercent * 100f));
				} else {
					oldPercent = failingTarget.getSetPercent(result, metric);
					oldPercent = (float) (Math.round(oldPercent * 100f));
				}
				if (newPercent > oldPercent) {
					if (select) {
						unhealthyTarget.setTarget(metric,
								(int) (newPercent * 1000f));
						listener.getLogger().println(
								"    " + metric.getName()
										+ "'s new health minimum is: "
										+ roundDecimalFloat(newPercent));
					} else {
						failingTarget.setTarget(metric,
								(int) (newPercent * 1000f));
						listener.getLogger().println(
								"    " + metric.getName()
										+ "'s new stability minimum is: "
										+ roundDecimalFloat(newPercent));
					}
				}
			}
		}
	}

	/**
	 * Updates the unhealthy or unstable percentage fields for another job
	 *
	 */
	private void setMainJobPercentages(String neighbourJobPath,
			CoverageResult result, BuildListener listener) {
		Set<CoverageMetric> healthyMetrics = healthyTarget
				.getAllMetrics(result);
		Map<String, Integer> mainJobUnhealthyMetrics = getMainJobMetrics(
				"unhealthyTarget", listener, neighbourJobPath);
		if (mainJobUnhealthyMetrics == null) {
			return;
		}
		Map<String, Integer> mainJobFailingMetrics = getMainJobMetrics(
				"failingTarget", listener, neighbourJobPath);
		if (mainJobFailingMetrics == null) {
			return;
		}
		float newPercent;
		// copyJobTarget.
		if (!healthyMetrics.isEmpty()) {
			for (CoverageMetric metric : healthyMetrics) {
				newPercent = healthyTarget.getObservedPercent(result, metric);
				newPercent = (float) (Math.round(newPercent * 100f));
				Integer healthMetricsValue = mainJobUnhealthyMetrics.get(metric
						.toString());
				Integer stabilityMetricsValue = mainJobFailingMetrics
						.get(metric.toString());
				unhealthyTarget.setTarget(metric,
						(int) (healthMetricsValue == null ? 0
								: (healthMetricsValue * 1f)));
				failingTarget.setTarget(metric,
						(int) (stabilityMetricsValue == null ? 0
								: (stabilityMetricsValue * 1f)));
			}
		}
	}

	public Map<String, Integer> getMainJobMetrics(String metricsNodeName,
			BuildListener listener, String neighbourJobPath) {
		Map<String, Integer> jobMetrics = new HashMap<String, Integer>();
		File fXmlFile = new File(neighbourJobPath);
		if (!fXmlFile.exists()) {
			listener.getLogger()
					.println(
							"Job Name : "
									+ getNeighbourJobName()
									+ " !! No such job exists to copy health metrics values.");
			listener.getLogger().println("Health Metrics are not updated !!");

			return null;
		}
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

		try {
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();
			Element node = (Element) doc.getElementsByTagName(metricsNodeName)
					.item(0);
			NodeList nlist = node.getElementsByTagName("entry");
			for (int temp = 0; temp < nlist.getLength(); temp++) {
				Node nNode = nlist.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {

					Element eElement = (Element) nNode;
					jobMetrics
							.put(eElement
									.getElementsByTagName(
											"hudson.plugins.cobertura.targets.CoverageMetric")
									.item(0).getTextContent(),
									Integer.parseInt(eElement
											.getElementsByTagName("int")
											.item(0).getTextContent()));
				}
			}

		} catch (SAXException e) {
			// Util.displayIOException(e, listener);
			e.printStackTrace(listener
					.fatalError("Unable to parse main job file"));

		} catch (IOException e1) {
			Util.displayIOException(e1, listener);
			e1.printStackTrace(listener
					.fatalError("Unable to parse main job file"));
			// build.setResult(Result.FAILURE);

		} catch (ParserConfigurationException e2) {
			e2.printStackTrace(listener
					.fatalError("Unable to parse main job file"));
		}
		return jobMetrics;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Action getProjectAction(AbstractProject<?, ?> project) {
		return new CoberturaProjectAction(project, getOnlyStable());
	}

	/**
	 * {@inheritDoc}
	 */
	public BuildStepMonitor getRequiredMonitorService() {
		return BuildStepMonitor.BUILD;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public BuildStepDescriptor<Publisher> getDescriptor() {
		// see Descriptor javadoc for more about what a descriptor is.
		return DESCRIPTOR;
	}

	public SourceEncoding getSourceEncoding() {
		return sourceEncoding;
	}

	/**
	 * Descriptor should be singleton.
	 */
	@Extension
	public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();

	public static class ParseReportCallable implements
			FilePath.FileCallable<FilePath[]> {

		private static final long serialVersionUID = 1L;

		private final String reportFilePath;

		public ParseReportCallable(String reportFilePath) {
			this.reportFilePath = reportFilePath;
		}

		public FilePath[] invoke(File f, VirtualChannel channel)
				throws IOException, InterruptedException {
			FilePath[] r = new FilePath(f).list(reportFilePath);

			XMLInputFactory factory = XMLInputFactory.newInstance();
			factory.setProperty("javax.xml.stream.supportDTD", false);

			for (FilePath filePath : r) {
				InputStream is = null;
				XMLEventReader reader = null;
				try {
					is = filePath.read();
					reader = factory.createXMLEventReader(is);
					while (reader.hasNext()) {
						XMLEvent event = reader.nextEvent();
						if (event.isStartElement()) {
							StartElement start = (StartElement) event;
							if (start.getName().getLocalPart()
									.equals("coverage")) {
								// This is a cobertura coverage report file
								break;
							} else {
								throw new IOException(
										filePath
												+ " is not a cobertura coverage report, please check your report pattern");
							}
						}
					}
				} catch (XMLStreamException e) {
					throw new IOException(
							filePath
									+ " is not an XML file, please check your report pattern");
				} finally {
					try {
						if (reader != null) {
							try {
								reader.close();
							} catch (XMLStreamException ex) {
								//
							}
						}
					} finally {
						IOUtils.closeQuietly(is);
					}
				}

			}
			return r;
		}
	}

	/**
	 * Descriptor for {@link CoberturaPublisher}. Used as a singleton. The class
	 * is marked as public so that it can be accessed from views.
	 * <p/>
	 * <p/>
	 * See <tt>views/hudson/plugins/cobertura/CoberturaPublisher/*.jelly</tt>
	 * for the actual HTML fragment for the configuration screen.
	 */
	public static final class DescriptorImpl extends
			BuildStepDescriptor<Publisher> {

		CoverageMetric[] metrics = { CoverageMetric.PACKAGES,
				CoverageMetric.FILES, CoverageMetric.CLASSES,
				CoverageMetric.METHOD, CoverageMetric.LINE,
				CoverageMetric.CONDITIONAL, };

		/**
		 * Constructs a new DescriptorImpl.
		 */
		DescriptorImpl() {
			super(CoberturaPublisher.class);
		}

		/**
		 * This human readable name is used in the configuration screen.
		 */
		public String getDisplayName() {
			return Messages.CoberturaPublisher_displayName();
		}

		/**
		 * Getter for property 'metrics'.
		 *
		 * @return Value for property 'metrics'.
		 */
		public List<CoverageMetric> getMetrics() {
			return Arrays.asList(metrics);
		}

		/**
		 * Getter for property 'defaultTargets'.
		 *
		 * @return Value for property 'defaultTargets'.
		 */
		public List<CoberturaPublisherTarget> getDefaultTargets() {
			List<CoberturaPublisherTarget> result = new ArrayList<CoberturaPublisherTarget>();
			result.add(new CoberturaPublisherTarget(CoverageMetric.METHOD, 80f,
					null, null));
			result.add(new CoberturaPublisherTarget(CoverageMetric.LINE, 80f,
					null, null));
			result.add(new CoberturaPublisherTarget(CoverageMetric.CONDITIONAL,
					70f, null, null));
			return result;
		}

		public List<CoberturaPublisherTarget> getTargets(
				CoberturaPublisher instance) {
			if (instance == null) {
				return getDefaultTargets();
			}
			return instance.getTargets();
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public boolean configure(StaplerRequest req, JSONObject formData)
				throws FormException {
			req.bindParameters(this, "cobertura.");
			save();
			return super.configure(req, formData);
		}

		/**
		 * Creates a new instance of {@link CoberturaPublisher} from a submitted
		 * form.
		 */
		@Override
		public CoberturaPublisher newInstance(StaplerRequest req,
				JSONObject formData) throws FormException {
			CoberturaPublisher instance = req.bindJSON(
					CoberturaPublisher.class, formData);
			ConvertUtils.register(CoberturaPublisherTarget.CONVERTER,
					CoverageMetric.class);
			logger.info(req.toString());

			List<CoberturaPublisherTarget> targets = req.bindParametersToList(
					CoberturaPublisherTarget.class, "cobertura.target.");
			System.out.println();
			instance.setTargets(targets);
			return instance;
		}

		@SuppressWarnings("unchecked")
		@Override
		public boolean isApplicable(Class<? extends AbstractProject> jobType) {
			return true;
		}
	}

	private static class CoberturaReportFilenameFilter implements
			FilenameFilter {

		/**
		 * {@inheritDoc}
		 */
		public boolean accept(File dir, String name) {
			// TODO take this out of an anonymous inner class, create a
			// singleton and use a Regex to match the name
			return name.startsWith("coverage") && name.endsWith(".xml");
		}
	}

	public float roundDecimalFloat(Float input) {
		float rounded = (float) Math.round(input);
		rounded = rounded / 100f;
		return rounded;
	}
}


text:
#include <peafowl/peafowl.h>
#include <pcap.h>
#include <net/ethernet.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
#include <assert.h>

int main(int argc, char** argv){

  if(argc != 2){
    fprintf(stderr, "Usage: %s pcap_file\n", argv[0]);
    return -1;
  }
  char* pcap_filename=argv[1];
  char errbuf[PCAP_ERRBUF_SIZE];

  pfwl_state_t* state = pfwl_init();
  pcap_t *handle = pcap_open_offline(pcap_filename, errbuf);

  if(handle == NULL){
    fprintf(stderr, "Couldn't open device %s: %s\n", pcap_filename, errbuf);
    return (2);
  }

  const u_char* packet;
  struct pcap_pkthdr header;

  // Server Name field
  pfwl_field_add_L7(state, PFWL_FIELDS_L7_DNS_NAME_SRV);
  // IP address of Server Name field
  /* pfwl_protocol_field_add(state, PFWL_FIELDS_DNS_NS_IP_1); */
  // Authoritative Server Name field
  /* pfwl_protocol_field_add(state, PFWL_FIELDS_DNS_AUTH_SRV); */
  pfwl_protocol_l2_t dlt = pfwl_convert_pcap_dlt(pcap_datalink(handle));

  while((packet = pcap_next(handle, &header)) != NULL){
    pfwl_dissection_info_t r;
    if(pfwl_dissect_from_L2(state, packet, header.caplen, time(NULL), dlt, &r) >= PFWL_STATUS_OK){
      pfwl_string_t field;
      if(r.l7.protocol == PFWL_PROTO_L7_DNS &&
         !pfwl_field_string_get(r.l7.protocol_fields, PFWL_FIELDS_L7_DNS_NAME_SRV, &field)){
        printf("Name Server detected: %.*s\n", (int) field.length, field.value);
      }
      if(r.l7.protocol == PFWL_PROTO_L7_DNS &&
         !pfwl_field_string_get(r.l7.protocol_fields, PFWL_FIELDS_L7_DNS_NS_IP_1, &field)){
        printf("IP address of Name Server: %.*s\n", (int) field.length, field.value);
      }
      if(r.l7.protocol == PFWL_PROTO_L7_DNS &&
         !pfwl_field_string_get(r.l7.protocol_fields, PFWL_FIELDS_L7_DNS_AUTH_SRV, &field)){
        printf("Authoritative Server detected: %.*s\n", (int) field.length, field.value);
      }
    }
  }
  return 0;
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.iotake.suller</groupId>
    <artifactId>iotake-suller</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>iotake-sullerj</artifactId>
  <packaging>jar</packaging>

  <name>iotake SullerJ</name>
  <description>SullerJ is an extension to SolrJ with richer bindings.</description>

  <build>
    <plugins>
      <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.4</version>
          <executions>
              <execution>
                  <goals>
                      <goal>test-jar</goal>
                  </goals>
              </execution>
          </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!-- intradependencies -->
    <!-- true dependencies -->
    <dependency>
      <groupId>org.apache.solr</groupId>
      <artifactId>solr-solrj</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>
    <!-- test dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymockclassextension</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.solr</groupId>
      <artifactId>solr-test-framework</artifactId>
    </dependency>
  </dependencies>
</project>


text:
package org.apache.orc.bench;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.orc.TypeDescription;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;

public class Utilities {

  public static TypeDescription loadSchema(String name) throws IOException {
    InputStream in = Utilities.class.getClassLoader().getResourceAsStream(name);
    byte[] buffer= new byte[1 * 1024];
    int len = in.read(buffer);
    StringBuilder string = new StringBuilder();
    while (len > 0) {
      for(int i=0; i < len; ++i) {
        // strip out
        if (buffer[i] != '\n' && buffer[i] != ' ') {
          string.append((char) buffer[i]);
        }
      }
      len = in.read(buffer);
    }
    return TypeDescription.fromString(string.toString());
  }

  public static org.apache.orc.CompressionKind getCodec(CompressionKind compression) {
    switch (compression) {
      case NONE:
        return org.apache.orc.CompressionKind.NONE;
      case ZLIB:
        return org.apache.orc.CompressionKind.ZLIB;
      case SNAPPY:
        return org.apache.orc.CompressionKind.SNAPPY;
      default:
        throw new IllegalArgumentException("Unknown compression " + compression);
    }
  }

  public static Iterable<String> sliceArray(final String[] array,
                                            final int start) {
    return new Iterable<String>() {
      String[] values = array;
      int posn = start;

      @Override
      public Iterator<String> iterator() {
        return new Iterator<String>() {
          @Override
          public boolean hasNext() {
            return posn < values.length;
          }

          @Override
          public String next() {
            if (posn >= values.length) {
              throw new NoSuchElementException("Index off end of array." +
                  " index = " + posn + " length = " + values.length);
            } else {
              return values[posn++];
            }
          }

          @Override
          public void remove() {
            throw new UnsupportedOperationException("No remove");
          }
        };
      }
    };
  }

  public static Properties convertSchemaToHiveConfig(TypeDescription schema) {
    Properties result = new Properties();
    if (schema.getCategory() != TypeDescription.Category.STRUCT) {
      throw new IllegalArgumentException("Hive requires struct root types" +
          " instead of " + schema);
    }
    StringBuilder columns = new StringBuilder();
    StringBuilder types = new StringBuilder();
    List<String> columnNames = schema.getFieldNames();
    List<TypeDescription> columnTypes = schema.getChildren();
    for(int c=0; c < columnNames.size(); ++c) {
      if (c != 0) {
        columns.append(",");
        types.append(",");
      }
      columns.append(columnNames.get(c));
      types.append(columnTypes.get(c));
    }
    result.setProperty(serdeConstants.LIST_COLUMNS, columns.toString());
    result.setProperty(serdeConstants.LIST_COLUMN_TYPES, types.toString());
    return result;
  }

  public static Path getVariant(Path root,
                                String data,
                                String format,
                                String compress) {
    return new Path(root, "generated/" + data + "/" + format + "." + compress);
  }
}


text:
import originalExtend from 'extend';

import createEnigmaError from './error';
import errorCodes from './error-codes';

const extend = originalExtend.bind(null, true);
const JSONPatch = {};
const { isArray } = Array;
function isObject(v) { return v != null && !Array.isArray(v) && typeof v === 'object'; }
function isUndef(v) { return typeof v === 'undefined'; }
function isFunction(v) { return typeof v === 'function'; }

/**
* Generate an exact duplicate (with no references) of a specific value.
*
* @private
* @param {Object} The value to duplicate
* @returns {Object} a unique, duplicated value
*/
function generateValue(val) {
  if (val) {
    return extend({}, { val }).val;
  }
  return val;
}

/**
* An additional type checker used to determine if the property is of internal
* use or not a type that can be translated into JSON (like functions).
*
* @private
* @param {Object} obj The object which has the property to check
* @param {String} The property name to check
* @returns {Boolean} Whether the property is deemed special or not
*/
function isSpecialProperty(obj, key) {
  return isFunction(obj[key])
    || key.substring(0, 2) === '$$'
    || key.substring(0, 1) === '_';
}

/**
* Finds the parent object from a JSON-Pointer ("/foo/bar/baz" = "bar" is "baz" parent),
* also creates the object structure needed.
*
* @private
* @param {Object} data The root object to traverse through
* @param {String} The JSON-Pointer string to use when traversing
* @returns {Object} The parent object
*/
function getParent(data, str) {
  const seperator = '/';
  const parts = str.substring(1).split(seperator).slice(0, -1);
  let numPart;

  parts.forEach((part, i) => {
    if (i === parts.length) {
      return;
    }
    numPart = +part;
    const newPart = !isNaN(numPart) ? [] : {};
    data[numPart || part] = isUndef(data[numPart || part])
      ? newPart
      : data[part];
    data = data[numPart || part];
  });

  return data;
}

/**
* Cleans an object of all its properties, unless they're deemed special or
* cannot be removed by configuration.
*
* @private
* @param {Object} obj The object to clean
*/
function emptyObject(obj) {
  Object.keys(obj).forEach((key) => {
    const config = Object.getOwnPropertyDescriptor(obj, key);

    if (config.configurable && !isSpecialProperty(obj, key)) {
      delete obj[key];
    }
  });
}

/**
* Compare an object with another, could be object, array, number, string, bool.
* @private
* @param {Object} a The first object to compare
* @param {Object} a The second object to compare
* @returns {Boolean} Whether the objects are identical
*/
function compare(a, b) {
  let isIdentical = true;

  if (isObject(a) && isObject(b)) {
    if (Object.keys(a).length !== Object.keys(b).length) {
      return false;
    }
    Object.keys(a).forEach((key) => {
      if (!compare(a[key], b[key])) {
        isIdentical = false;
      }
    });
    return isIdentical;
  }
  if (isArray(a) && isArray(b)) {
    if (a.length !== b.length) {
      return false;
    }
    for (let i = 0, l = a.length; i < l; i += 1) {
      if (!compare(a[i], b[i])) {
        return false;
      }
    }
    return true;
  }
  return a === b;
}

/**
* Generates patches by comparing two arrays.
*
* @private
* @param {Array} oldA The old (original) array, which will be patched
* @param {Array} newA The new array, which will be used to compare against
* @returns {Array} An array of patches (if any)
*/
function patchArray(original, newA, basePath) {
  let patches = [];
  const oldA = original.slice();
  let tmpIdx = -1;

  function findIndex(a, id, idx) {
    if (a[idx] && isUndef(a[idx].qInfo)) {
      return null;
    }
    if (a[idx] && a[idx].qInfo.qId === id) {
      // shortcut if identical
      return idx;
    }
    for (let ii = 0, ll = a.length; ii < ll; ii += 1) {
      if (a[ii] && a[ii].qInfo.qId === id) {
        return ii;
      }
    }
    return -1;
  }

  if (compare(newA, oldA)) {
    // array is unchanged
    return patches;
  }

  if (!isUndef(newA[0]) && isUndef(newA[0].qInfo)) {
    // we cannot create patches without unique identifiers, replace array...
    patches.push({
      op: 'replace',
      path: basePath,
      value: newA,
    });
    return patches;
  }

  for (let i = oldA.length - 1; i >= 0; i -= 1) {
    tmpIdx = findIndex(newA, oldA[i].qInfo && oldA[i].qInfo.qId, i);
    if (tmpIdx === -1) {
      patches.push({
        op: 'remove',
        path: `${basePath}/${i}`,
      });
      oldA.splice(i, 1);
    } else {
      patches = patches.concat(JSONPatch.generate(oldA[i], newA[tmpIdx], `${basePath}/${i}`));
    }
  }

  for (let i = 0, l = newA.length; i < l; i += 1) {
    tmpIdx = findIndex(oldA, newA[i].qInfo && newA[i].qInfo.qId);
    if (tmpIdx === -1) {
      patches.push({
        op: 'add',
        path: `${basePath}/${i}`,
        value: newA[i],
      });
      oldA.splice(i, 0, newA[i]);
    } else if (tmpIdx !== i) {
      patches.push({
        op: 'move',
        path: `${basePath}/${i}`,
        from: `${basePath}/${tmpIdx}`,
      });
      oldA.splice(i, 0, oldA.splice(tmpIdx, 1)[0]);
    }
  }
  return patches;
}

/**
* Generate an array of JSON-Patch:es following the JSON-Patch Specification Draft.
*
* See [specification draft](http://tools.ietf.org/html/draft-ietf-appsawg-json-patch-10)
*
* Does NOT currently generate patches for arrays (will replace them)
* @private
* @param {Object} original The object to patch to
* @param {Object} newData The object to patch from
* @param {String} [basePath] The base path to use when generating the paths for
*                            the patches (normally not used)
* @returns {Array} An array of patches
*/
JSONPatch.generate = function generate(original, newData, basePath) {
  basePath = basePath || '';
  let patches = [];

  Object.keys(newData).forEach((key) => {
    const val = generateValue(newData[key]);
    const oldVal = original[key];
    const tmpPath = `${basePath}/${key}`;

    if (compare(val, oldVal) || isSpecialProperty(newData, key)) {
      return;
    }
    if (isUndef(oldVal)) {
      // property does not previously exist
      patches.push({
        op: 'add',
        path: tmpPath,
        value: val,
      });
    } else if (isObject(val) && isObject(oldVal)) {
      // we need to generate sub-patches for this, since it already exist
      patches = patches.concat(JSONPatch.generate(oldVal, val, tmpPath));
    } else if (isArray(val) && isArray(oldVal)) {
      patches = patches.concat(patchArray(oldVal, val, tmpPath));
    } else {
      // it's a simple property (bool, string, number)
      patches.push({
        op: 'replace',
        path: `${basePath}/${key}`,
        value: val,
      });
    }
  });

  Object.keys(original).forEach((key) => {
    if (isUndef(newData[key]) && !isSpecialProperty(original, key)) {
      // this property does not exist anymore
      patches.push({
        op: 'remove',
        path: `${basePath}/${key}`,
      });
    }
  });

  return patches;
};

/**
* Apply a list of patches to an object.
* @private
* @param {Object} original The object to patch
* @param {Array} patches The list of patches to apply
*/
JSONPatch.apply = function apply(original, patches) {
  patches.forEach((patch) => {
    let parent = getParent(original, patch.path);
    let key = patch.path.split('/').splice(-1)[0];
    let target = key && isNaN(+key) ? parent[key] : parent[+key] || parent;
    const from = patch.from ? patch.from.split('/').splice(-1)[0] : null;

    if (patch.path === '/') {
      parent = null;
      target = original;
    }

    if (patch.op === 'add' || patch.op === 'replace') {
      if (isArray(parent)) {
        // trust indexes from patches, so don't replace the index if it's an add
        if (key === '-') {
          key = parent.length;
        }
        parent.splice(+key, patch.op === 'add' ? 0 : 1, patch.value);
      } else if (isArray(target) && isArray(patch.value)) {
        // keep array reference if possible...
        target.length = 0;

        const chunkSize = 1000;
        for (let i = 0; i < patch.value.length; i += chunkSize) {
          const chunk = patch.value.slice(i, i + chunkSize);
          target.push(...chunk);
        }
      } else if (isObject(target) && isObject(patch.value)) {
        // keep object reference if possible...
        emptyObject(target);
        extend(target, patch.value);
      } else if (!parent) {
        throw createEnigmaError(errorCodes.PATCH_HAS_NO_PARENT, 'Patchee is not an object we can patch');
      } else {
        // simple value
        parent[key] = patch.value;
      }
    } else if (patch.op === 'move') {
      const oldParent = getParent(original, patch.from);
      if (isArray(parent)) {
        parent.splice(+key, 0, oldParent.splice(+from, 1)[0]);
      } else {
        parent[key] = oldParent[from];
        delete oldParent[from];
      }
    } else if (patch.op === 'remove') {
      if (isArray(parent)) {
        parent.splice(+key, 1);
      } else {
        delete parent[key];
      }
    }
  });
};

/**
* Deep clone an object.
* @private
* @param {Object} obj The object to clone
* @returns {Object} A new object identical to the `obj`
*/
JSONPatch.clone = function clone(obj) {
  return extend({}, obj);
};

/**
* Creates a JSON-patch.
* @private
* @param {String} op The operation of the patch. Available values: "add", "remove", "move"
* @param {Object} [val] The value to set the `path` to. If `op` is `move`, `val`
*                       is the "from JSON-path" path
* @param {String} path The JSON-path for the property to change (e.g. "/qHyperCubeDef/columnOrder")
* @returns {Object} A patch following the JSON-patch specification
*/
JSONPatch.createPatch = function createPatch(op, val, path) {
  const patch = {
    op: op.toLowerCase(),
    path,
  };
  if (patch.op === 'move') {
    patch.from = val;
  } else if (typeof val !== 'undefined') {
    patch.value = val;
  }
  return patch;
};

/**
* Apply the differences of two objects (keeping references if possible).
* Identical to running `JSONPatch.apply(original, JSONPatch.generate(original, newData));`
* @private
* @param {Object} original The object to update/patch
* @param {Object} newData the object to diff against
*
* @example
* var obj1 = { foo: [1,2,3], bar: { baz: true, qux: 1 } };
* var obj2 = { foo: [4,5,6], bar: { baz: false } };
* JSONPatch.updateObject(obj1, obj2);
* // => { foo: [4,5,6], bar: { baz: false } };
*/
JSONPatch.updateObject = function updateObject(original, newData) {
  if (!Object.keys(original).length) {
    extend(original, newData);
    return;
  }
  JSONPatch.apply(original, JSONPatch.generate(original, newData));
};

export default JSONPatch;


text:
let { Cc, Ci, Cr } = require("chrome");
let system = require("sdk/system");
let systemEvents = require("sdk/system/events");
let windowUtils = require("sdk/window/utils");
let Request = require("sdk/request").Request;
let timers = require("sdk/timers");
let properties = require("packages/properties");
let urlHelper = require("packages/urlHelper");

var asyncHistory = Cc["@mozilla.org/browser/history;1"]
                  .getService(Ci.mozIAsyncHistory);

exports.enable = (enable) => {
  return doEnable(enable);
};

/**
 * Whether the redirecter should be enabled or not.
 *
 * @private
 * @param {boolean} aEnable
 */
function doEnable(aEnable) {
  if (aEnable) {
    systemEvents.on("http-on-modify-request", requestListener);
  } else {
    systemEvents.off("http-on-modify-request", requestListener);
  }
}

/**
 * Returns a number if the resource is the initial document.
 * Eg. index.html
 *
 * @private
 * @param {object} aHttpChannel
 * @returns {number}
 */
function isChannelInitialDocument(aHttpChannel) {
  return aHttpChannel.loadFlags & aHttpChannel.LOAD_INITIAL_DOCUMENT_URI;
}

/**
 * @private
 * @param {object} aRequest
 * @returns {object}
 */
function getWindowForRequest(aRequest){
  if (aRequest instanceof Ci.nsIRequest) {
    try {
      if (aRequest.notificationCallbacks) {
        return aRequest.notificationCallbacks
              .getInterface(Ci.nsILoadContext).associatedWindow;
      }
    } catch(e) {
    }
    try {
      if (aRequest.loadGroup && aRequest.loadGroup.notificationCallbacks) {
        return aRequest.loadGroup.notificationCallbacks
              .getInterface(Ci.nsILoadContext).associatedWindow;
      }
    } catch(e) {
    }
  }
  return null;
}

/**
 * @private
 * @param {object} request
 * @param {string} url
 */
function redirectRequest(request, url) {
  let browserWindow = windowUtils.getMostRecentBrowserWindow();
  if (system.platform == "android") {
    browserWindow.BrowserApp.loadURI(url);
  } else {
    let gBrowser = browserWindow.gBrowser;
    let domWin = getWindowForRequest(request);
    let browser = gBrowser.getBrowserForDocument(domWin.top.document);
    browser.loadURI(url);
  }
}

/**
 * Called for each request.
 *
 * @private
 * @param {Event} aEvent
 */
function requestListener(aEvent) {
  let request = aEvent.subject;
  let channel = request.QueryInterface(Ci.nsIHttpChannel);
  let url = request.URI.spec;

  // Do not modify requests to gfycat.
  if (url.contains(properties.gfycat.domain)) {
    return;
  }

  // Make sure flagged gifs falls through (see data/scripts/resImageViewerMod).
  if (url.contains("gccfxDoRequest=1")) {
    return;
  }

  let isInitialDocument = isChannelInitialDocument(channel);
  let isImageFileExtension = urlHelper.isImageFileExtension(url);

  // Redirect direct gif requests.
  if (isInitialDocument && isImageFileExtension) {
    console.log("Is direct request");

    // Cancel the request.
    channel.cancel(Cr.NS_BINDING_ABORTED);

    // Check if content type is gif/image and redirect.

    let isGifFileExtensionCallback = () => {
      // Since the request is aborted, make sure the url is updated in the browser history.
      // Automatically marks the url as visited etc.
      let videoPage = properties.addon.chromePageUrl + url;

      asyncHistory.updatePlaces({
        title: "Redirected by gfycat companion, " + url,
        uri: request.URI,
        visits: [{
          transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
          visitDate: (Date.now()) * 1000
        }]
      });

      redirectRequest(request, videoPage);
    };

    let isNotGifFileExtensionCallback = () => {
      // Disable the listener before redirect so the listener does not loop.
      doEnable(false);
      redirectRequest(request, url);
      timers.setTimeout(() => {
        console.log("Enable");
        doEnable(true);
      }, 300);
    };

    // Check if image is a gif by doing a head request.
    console.log("Check content type");
    urlHelper.asyncIsContentTypeGif(url, isGifFileExtensionCallback, isNotGifFileExtensionCallback);
  }
}


text:
The `SPObject` class contains methods related to common attributes of SharePoint objects.

## Subclasses
- [SPAccessToken](docs/SPAccessToken.md)
- [SPFormDigest](docs/SPFormDigest.md)
- [SPList](docs/SPList.md)
- [SPItem](docs/SPItem.md)
- [SPFolder](docs/SPFolder.md)
- [SPFile](docs/SPFile.md)
- [SPUser](docs/SPUser.md)

## Extra
Get an extra property of a `SPAccessToken`, `SPFormDigest`, `SPList`, `SPItem`, `SPFolder`, `SPFile` or `SPUser` object.

```php
    echo $object->getExtra('Foo'); // Bar
```


text:
package com.jtanks.model;

import java.awt.Color;

import com.jtanks.util.Point;

public interface BasicEntity {
    Color getColor();
    Point getPosition();
    double getSize();
    boolean isDestroyed();
}