text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2016 Mobvoi Inc.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<resources>

    <!-- Dialog padding for round display -->
    <dimen name="alert_dialog_round_padding">0dip</dimen>
    <dimen name="alert_dialog_round_padding_bottom">5dp</dimen>
    <dimen name="alert_dialog_round_button_padding_horizontal_full">10dp</dimen>
    <dimen name="alert_dialog_round_button_padding_horizontal_pair">38dp</dimen>
    <dimen name="alert_dialog_button_translate_vertical">30dp</dimen>
    <dimen name="alert_dialog_button_translate_horizontal">28dp</dimen>
    <dimen name="alert_dialog_message_padding_horizontal">20dp</dimen>
    <dimen name="alert_dialog_skip_button_height">48dp</dimen>
    <dimen name="alert_dialog_skip_button_padding">8dp</dimen>
    <dimen name="alert_dialog_skip_text_space_relative">6dp</dimen>

    <!-- TimePicker -->
    <dimen name="tic_timepicker_time_label_size">60sp</dimen>
    <dimen name="tic_timepicker_extra_time_label_margin">-30dp</dimen>
    <dimen name="tic_timepicker_ampm_label_size">16sp</dimen>
    <dimen name="tic_timepicker_ampm_horizontal_padding">12dp</dimen>
    <dimen name="tic_timepicker_ampm_vertical_padding">16dp</dimen>
    <dimen name="tic_timepicker_pm_top_padding">3dp</dimen>
    <dimen name="tic_timepicker_separator_padding">4dp</dimen>
    <dimen name="tic_timepicker_header_height">96dp</dimen>
    <dimen name="tic_timepicker_minimum_margin_sides">48dp</dimen>
    <dimen name="tic_timepicker_minimum_margin_top_bottom">24dp</dimen>
    <dimen name="tic_timepicker_radial_picker_dimen">270dp</dimen>

    <!-- Buttons -->
    <dimen name="tic_compound_button_drawable_size">36dp</dimen>
    <dimen name="tic_compound_button_drawable_size_small">24dp</dimen>
    <dimen name="tic_round_button_size_large">68dp</dimen>
    <dimen name="tic_round_button_size_normal">56dp</dimen>
    <dimen name="tic_round_button_size_mini">40dp</dimen>
    <dimen name="tic_round_button_src_padding_large">17dp</dimen>
    <dimen name="tic_round_button_src_padding_normal">14dp</dimen>
    <dimen name="tic_round_button_src_padding_mini">10dp</dimen>
    <dimen name="tic_primary_button_width">132dp</dimen>
    <dimen name="tic_primary_button_height">56dp</dimen>

    <dimen name="tic_menu_item_margin_horizontal_small">1dp</dimen>
    <dimen name="tic_menu_item_margin_horizontal_large">3dp</dimen>
    <dimen name="tic_menu_item_content_margin_small">6dp</dimen>
    <dimen name="tic_menu_item_content_margin_large">8dp</dimen>
    <dimen name="tic_menu_item_icon_padding_1">21dp</dimen>
    <dimen name="tic_menu_item_icon_padding_2">@dimen/tic_round_button_src_padding_large</dimen>
    <dimen name="tic_menu_item_icon_padding_3">@dimen/tic_round_button_src_padding_normal</dimen>
    <dimen name="tic_menu_item_icon_size_1">84dp</dimen>
    <dimen name="tic_menu_item_icon_size_2">@dimen/tic_round_button_size_large</dimen>
    <dimen name="tic_menu_item_icon_size_3">@dimen/tic_round_button_size_normal</dimen>
    <dimen name="tic_menu_item_title_size_1">@dimen/tic_text_size_medium_1</dimen>
    <dimen name="tic_menu_item_title_size_2">@dimen/tic_text_size_medium_2</dimen>
    <dimen name="tic_menu_item_title_size_3">@dimen/tic_text_size_small_1</dimen>

    <!--NumberPickerDialog -->
    <dimen name="number_picker_dialog_unit_text_margin_left">8dp</dimen>
</resources>


text:
hadoopUser=$(./load-config.sh hadoop-user)
hadoopMaster=$(./load-config.sh hadoop-master)
hdfsSaveDir=$(./load-config.sh hadoop-hdfssavedir)
sparkUser=$(./load-config.sh spark-user)
sparkMaster=$(./load-config.sh spark-master)
sparkSlaves=$(./load-config.sh spark-slaves)

redpajama_set_name: RedPajamaGithub


text:
package codeblocks;

import renderable.RenderableBlock;
import workspace.Workspace;
import workspace.WorkspaceEvent;
import codeblockutil.SoundManager;
import codeblockutil.Sound;

/**
 * A class that stores information about a potential block connection.
 *
 * Each BlockLink instance stores the Block IDs of the "plug" and "socket"
 * and two block connectors, one from each, with a possible connection.
 *
 * In block linking, a "plug" can be either a before or plug connector,
 * while a "socket" can either be a after or socket connector.  Plugs can only
 * connect to other socket connectors, while before connectors can connect to
 * after and command socket connectors.
 */
public class BlockLink {

	private static Sound clickSound;

	private Long plugBlockID;
	private Long socketBlockID;
	private Long lastPlugBlockID;
	private BlockConnector plug;
	private BlockConnector socket;

	//information regarding the last BlockLink instance
	private static Long lastPlugID;
	private static Long lastSocketID;
	private static BlockConnector lastPlug;
	private static BlockConnector lastSocket;
	private static BlockLink lastLink;

	/**
	 * Private constructor to (somewhat) limit object creation
	 * @param block1
	 * @param block2
	 * @param socket1
	 * @param socket2
	 */
	private BlockLink(Block block1, Block block2, BlockConnector socket1, BlockConnector socket2) {
		boolean isPlug1 = (block1.hasPlug() && block1.getPlug() == socket1) ||
		(block1.hasBeforeConnector() && block1.getBeforeConnector() == socket1);
		boolean isPlug2 = (block2.hasPlug() && block2.getPlug() == socket2) ||
		(block2.hasBeforeConnector() && block2.getBeforeConnector() == socket2);
		if (!(isPlug1 ^ isPlug2)) {
			// bad news... there should be only one plug
			assert(false);
		} else if (isPlug1){
			plug = socket1;
			socket = socket2;
			plugBlockID = block1.getBlockID();
			socketBlockID = block2.getBlockID();
		} else {
			plug = socket2;
			socket = socket1;
			plugBlockID = block2.getBlockID();
			socketBlockID = block1.getBlockID();
		}
		lastPlugID = plugBlockID;
		lastSocketID = socketBlockID;
		lastPlug = plug;
		lastSocket = socket;
		lastPlugBlockID = Block.NULL;
	}

	static{
		//load the sound for connecting blocks, but only once
		try{
			clickSound = SoundManager.loadSound("/codeblocks/click.wav");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Error initializing sounds.  Continuing...");
		}
	}

	/**
	 *
	 * @return the BlockConnector representing the plug side of the link
	 */
	public BlockConnector getPlug() {
		return plug;
	}

	/**
	 *
	 * @return the BlockConnector representing the socket side of the link
	 */
	public BlockConnector getSocket() {
		return socket;
	}

	/**
	 *
	 * @return the Block ID of the Block containing the plug side of the link
	 */
	public Long getPlugBlockID() {
		return plugBlockID;
	}

	/**
	 *
	 * @return the Block ID of the Block containing the socket side of the link
	 */
	public Long getSocketBlockID() {
		return socketBlockID;
	}

	public Long getLastBlockID() {
		return lastPlugBlockID;
	}

	/**
	 * This method actually connects the two blocks stored in this BlockLink object.
	 *
	 */
	public void connect() {

		/* Make sure to disconnect any connections that are going to be overwritten
		 * by this new connection.  For example, if inserting a block between two
		 * others, make sure to break that original link.*/
		if (socket.hasBlock()) {
			// save the ID of the block previously attached to (in) this
			// socket.  This is used by insertion rules to re-link the replaced
			// block to the newly-inserted block.
			lastPlugBlockID = socket.getBlockID();

			// break the link between the socket block and the block in that socket
			Block plugBlock = Block.getBlock(lastPlugBlockID);
			BlockConnector plugBlockPlug = BlockLinkChecker.getPlugEquivalent(plugBlock);
			if (plugBlockPlug != null && plugBlockPlug.hasBlock()) {
				Block socketBlock = Block.getBlock(plugBlockPlug.getBlockID());
				BlockLink link = BlockLink.getBlockLink(plugBlock, socketBlock, plugBlockPlug, socket);
				link.disconnect();
				//don't tell the block about the disconnect like we would normally do, because
				// we don't actually want it to have a chance to remove any expandable sockets
				// since the inserted block will be filling whatever socket was vacated by this
				// broken link.
				//NOTIFY WORKSPACE LISTENERS OF DISCONNECTION (not sure if this is great because the connection is immediately replaced)
				Workspace.getInstance().notifyListeners(new WorkspaceEvent(RenderableBlock.getRenderableBlock(socketBlock.getBlockID()).getParentWidget(), link, WorkspaceEvent.BLOCKS_DISCONNECTED));
			}
		}
		if (plug.hasBlock()) {
			// in the case of insertion, breaking the link above will mean that
			// the plug shouldn't be connected by the time we reach here.  This
			// exception will only be thrown if the plug is connected even
			// after any insertion-esq links were broken above
			throw new RuntimeException("trying to link a plug that's already connected somewhere.");
		}

		// actually form the connection
		plug.setConnectorBlockID(socketBlockID);
		socket.setConnectorBlockID(plugBlockID);

		//notify renderable block of connection so it can redraw with stretching
		RenderableBlock socketRB = RenderableBlock.getRenderableBlock(socketBlockID);
		socketRB.blockConnected(socket, plugBlockID);

		if(clickSound != null){
			//System.out.println("playing click sound");
			clickSound.play();
		}
	}

	public void disconnect() {
		plug.setConnectorBlockID(Block.NULL);
		socket.setConnectorBlockID(Block.NULL);
	}

	/**
	 * Factory method for creating BlockLink objects
	 * @param block1 one of the Block objects in the potential link
	 * @param block2 the other Block object
	 * @param socket1 the BlockConnector from block1
	 * @param socket2 the BlockConnector from block2
	 * @return a BlockLink object storing the potential link between block1 and block2
	 */
	public static BlockLink getBlockLink(Block block1, Block block2, BlockConnector socket1, BlockConnector socket2) {
		// If these arguments are the same as the last call to getBlockLink, return the old object instead of creating a new one
		if (!((block1.getBlockID().equals(lastPlugID) && block2.getBlockID().equals(lastSocketID) &&
				socket1.equals(lastPlug) && socket2.equals(lastSocket)) ||
				(block2.getBlockID().equals(lastPlugID) && block1.getBlockID().equals(lastSocketID) &&
						socket2.equals(lastPlug) && socket1.equals(lastSocket)))) {
			lastLink = new BlockLink(block1, block2, socket1, socket2);
		}
		return lastLink;
	}

	public String toString() {
		return "BlockLink(Plug: " + plugBlockID + ", Socket: " + socketBlockID + ")";
	}
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createCachedDescriptors = createCachedDescriptors;
exports.createUncachedDescriptors = createUncachedDescriptors;
exports.createDescriptor = createDescriptor;

var _files = require("./files");

var _item = require("./item");

var _caching = require("./caching");

function isEqualDescriptor(a, b) {
  return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved);
}

function createCachedDescriptors(dirname, options, alias) {
  const {
    plugins,
    presets,
    passPerPreset
  } = options;
  return {
    options,
    plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => [],
    presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => []
  };
}

function createUncachedDescriptors(dirname, options, alias) {
  let plugins;
  let presets;
  return {
    options,
    plugins: () => {
      if (!plugins) {
        plugins = createPluginDescriptors(options.plugins || [], dirname, alias);
      }

      return plugins;
    },
    presets: () => {
      if (!presets) {
        presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset);
      }

      return presets;
    }
  };
}

const PRESET_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPresetDescriptors = (0, _caching.makeWeakCache)((items, cache) => {
  const dirname = cache.using(dir => dir);
  return (0, _caching.makeStrongCache)(alias => (0, _caching.makeStrongCache)(passPerPreset => createPresetDescriptors(items, dirname, alias, passPerPreset).map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc))));
});
const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPluginDescriptors = (0, _caching.makeWeakCache)((items, cache) => {
  const dirname = cache.using(dir => dir);
  return (0, _caching.makeStrongCache)(alias => createPluginDescriptors(items, dirname, alias).map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)));
});
const DEFAULT_OPTIONS = {};

function loadCachedDescriptor(cache, desc) {
  const {
    value,
    options = DEFAULT_OPTIONS
  } = desc;
  if (options === false) return desc;
  let cacheByOptions = cache.get(value);

  if (!cacheByOptions) {
    cacheByOptions = new WeakMap();
    cache.set(value, cacheByOptions);
  }

  let possibilities = cacheByOptions.get(options);

  if (!possibilities) {
    possibilities = [];
    cacheByOptions.set(options, possibilities);
  }

  if (possibilities.indexOf(desc) === -1) {
    const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc));

    if (matches.length > 0) {
      return matches[0];
    }

    possibilities.push(desc);
  }

  return desc;
}

function createPresetDescriptors(items, dirname, alias, passPerPreset) {
  return createDescriptors("preset", items, dirname, alias, passPerPreset);
}

function createPluginDescriptors(items, dirname, alias) {
  return createDescriptors("plugin", items, dirname, alias);
}

function createDescriptors(type, items, dirname, alias, ownPass) {
  const descriptors = items.map((item, index) => createDescriptor(item, dirname, {
    type,
    alias: `${alias}$${index}`,
    ownPass: !!ownPass
  }));
  assertNoDuplicates(descriptors);
  return descriptors;
}

function createDescriptor(pair, dirname, {
  type,
  alias,
  ownPass
}) {
  const desc = (0, _item.getItemDescriptor)(pair);

  if (desc) {
    return desc;
  }

  let name;
  let options;
  let value = pair;

  if (Array.isArray(value)) {
    if (value.length === 3) {
      [value, options, name] = value;
    } else {
      [value, options] = value;
    }
  }

  let file = undefined;
  let filepath = null;

  if (typeof value === "string") {
    if (typeof type !== "string") {
      throw new Error("To resolve a string-based item, the type of item must be given");
    }

    const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset;
    const request = value;
    ({
      filepath,
      value
    } = resolver(value, dirname));
    file = {
      request,
      resolved: filepath
    };
  }

  if (!value) {
    throw new Error(`Unexpected falsy value: ${String(value)}`);
  }

  if (typeof value === "object" && value.__esModule) {
    if (value.default) {
      value = value.default;
    } else {
      throw new Error("Must export a default export when using ES6 modules.");
    }
  }

  if (typeof value !== "object" && typeof value !== "function") {
    throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`);
  }

  if (filepath !== null && typeof value === "object" && value) {
    throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`);
  }

  return {
    name,
    alias: filepath || alias,
    value,
    options,
    dirname,
    ownPass,
    file
  };
}

function assertNoDuplicates(items) {
  const map = new Map();

  for (const item of items) {
    if (typeof item.value !== "function") continue;
    let nameMap = map.get(item.value);

    if (!nameMap) {
      nameMap = new Set();
      map.set(item.value, nameMap);
    }

    if (nameMap.has(item.name)) {
      const conflicts = items.filter(i => i.value === item.value);
      throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, `  plugins: [`, `    ['some-plugin', {}],`, `    ['some-plugin', {}, 'some unique name'],`, `  ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n"));
    }

    nameMap.add(item.name);
  }
}


text:
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2015 Olga Diamanti <olga.diam@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.

#ifndef IGL_PARALLEL_TRANSPORT_ANGLE
#define IGL_PARALLEL_TRANSPORT_ANGLE
#include "igl_inline.h"

#include <Eigen/Core>
#include <vector>

namespace igl {
  // Given the per-face local bases computed via igl::local_basis, this function
  // computes the angle between the two reference frames across each edge.
  // Any two vectors across the edge whose 2D representation only differs by
  // this angle are considered to be parallel.

  // Inputs:
  //   V               #V by 3 list of mesh vertex coordinates
  //   F               #F by 3 list of mesh faces (must be triangles)
  //   FN              #F by 3 list of face normals
  //   E2F             #E by 2 list of the edge-to-face relation (e.g. computed
  //                   via igl::edge_topology)
  //   F2E             #F by 3 list of the face-to-edge relation (e.g. computed
  //                   via igl::edge_topology)
  // Output:
  //   K               #E by 1 list of the parallel transport angles (zero
  //                   for all boundary edges)
  //
template <typename DerivedV, typename DerivedF, typename DerivedK>
IGL_INLINE void parallel_transport_angles(
const Eigen::PlainObjectBase<DerivedV>&V,
const Eigen::PlainObjectBase<DerivedF>&F,
const Eigen::PlainObjectBase<DerivedV>&FN,
const Eigen::MatrixXi &E2F,
const Eigen::MatrixXi &F2E,
Eigen::PlainObjectBase<DerivedK>&K);

};

#ifndef IGL_STATIC_LIBRARY
#include "parallel_transport_angles.cpp"
#endif

#endif /* defined(IGL_PARALLEL_TRANSPORT_ANGLE) */


text:
<!DOCTYPE html>
<meta charset=utf-8>
<meta name=viewport content="width=device-width, initial-scale=1">
<title>reproCSS</title>

reproCSS

A CSS reprocessor using <style> tags

Can you imagine if you could interpolate JS inside CSS with the ${} syntax, and also control when and how frequently that CSS reprocessed with a process="" attribute on the <style> tag:

<style process="none"></style>
<style process="once"></style>
<style process="auto"></style>
<style process="touchstart mousedown"></style>

If you are using reproCSS with custom events, you may also optionally use a selector attribute specify a list of one or more CSS selectors you would like to add event listeners for. If no selector attribute is found all custom events will be applied to window.

<style process="click" selector="#any, .css, [selector]"></style>

You can add the CSS you want reprocss.js to apply to your HTML in <style> tags with the following values on the process attribute:

none means no reprocessing

once means process immediately and never again

auto runs every resize, input, and click event on window

any space-separated list of JS events you wish to listen for

How to use reproCSS

Github

To view reproCSS on Github visit: github.com/tomhodgins/reprocss

You can include the reprocss.js JavaScript plugin in your HTML:

<script src="reprocss.js"></script>

npm

If you are using reproCSS on NPM you can include it in your JS modules with a line like this:

const reprocss = require('reprocss')

How to write reproCSSed CSS

To evaluate JavaScript inside the CSS as it's being reprocessed by reprocss.js you can use the ${} interpolation syntax. The following <style> tag would always ensure the <div> in this example was half of the window's height:

<style process="auto">
  div {
    height: calc(${innerHeight}px / 2);
  }
</style>

When the browser is 1000px tall the ${innerHeight} in our CSS will be output as 500, leading to the following output:

<style process="auto">
  div {
    height: calc(500px / 2);
  }
</style>

Currently this plugin only supports <style> tags, but it may be possible to support CSS loaded via <link> with a similar technique.

Examples

Interpolating JS-supplied values in CSS content:;

<div>Hello</div>

<script>
  var user = 'Username'
</script>

<style process="once">
  div:after {
    content: ' ${user}';
  }
</style>

Element Queries via a JS Selector Resolver

<div id="demo">
  <p>Hello</p>
</div>

<style process="resize">
  ${demo.offsetWidth > 400 && "#demo"} {
    background: lime;
  }
  ${demo.offsetWidth > 400 && "#demo"} p {
    color: red;
  }
</style>

JS interpolation in CSS

<textarea id="demo"></textarea>

<style process="input">
  #demo {
    background: hsl(${demo.value.length}, 50%, 50%)
  }
</style>

Demos

Element Queries with reproCSS

Min/Max Font Size

Attribute Values as Numbers

Regex Search on Attribute Value

Cursor Tracking

Scalable Iframe

View reproCSS demos on CodePen

Mixins

Writing mixins for reproCSS is easy, any JavaScript function that outputs code that can be used in CSS can be called from anywhere in the stylesheet reproCSS is processing using JS interpolation with ${}.

An example of a common mixin template might look like this:

function mixin(selector, rule) {

  // Find tags in document matching selector
  var tag = document.querySelectorAll(selector)

  // Begin with an empty style
  var style = ''

  // Begin counting matching tags at 0
  var count = 0

  // For each tag matching our selector
  for (var i=0; i<tag.length; i++) {

    // Create an identifier based on the selector used
    var attr = selector.replace(/\W+/g, '')

    // Mark tag with a custom attribute containing identifier and count
    tag[i].setAttribute('data-mixin-' + attr, count)

    // Add a copy of the CSS rule to the style using a selector for this tag's unique attribute
    style += '\n[data-mixin-' + attr + '="' + count + '"] {\n'
             + '  ' + rule + '\n'
             + '}\n'

    // Increment the tag counter by +1
    count++

  }

  // Return all generated styles as CSS text
  return style

}

If you were going to create a mixin starting from the template above the first thing you'd want to do is change the function name (currently mixin()) to something unique, as well as update the mentions of mixin inside the mixin logic where it's used to name the elements the mixin is styling, data-mixin-.

Once you have changed the name of the function, you can pass a CSS selector or a list of CSS selectors into to the plugin, along with CSS properties and values as a string to be processed and added to new rules. This basic template can be extended in many ways to support different things. Here are some examples of reproCSS mixins and helper functions:

Aspect Ratio Mixin

This mixin lets you to define an aspect ratio for elements.

syntax

aspectRatio('iframe', 16/9)

output

/* iframe { aspect-ratio: 1.77; } */
[data-aspect-ratio-unique=0] {
  height: 503px;
}

demo

Aspect Ratio Mixin Demo

XPath Select Mixin

This mixin lets you use XPath as a selector for CSS rules.

syntax

xpath('//*', `
  border: 1px solid red;
`)

outpue

/*

//* {
  border: 1px solid red;
}

*/
[data-xpath-unique=0] {
  border: 1px solid red;
}

demo

XPath Selector Mixin Demo

Auto Expand Mixin

This mixin lets you choose between auto-expanding an element's width and height to match its scrollWidth or scrollHeight. Available keywords are width,, height, and both.

syntax

autoExpand('textarea', 'height')

output

/* textarea { height: auto-expand; } */

demo

Auto Expand Mixin Demo

Container Queries Mixin

This mixin lets you define a 'container' using a CSS selector, run a JavaScript test against matching tags that match the container's selector, and to apply a CSS rule to that container or its children.

syntax

container('div', 'this.offsetWidth > 500', 'span', 'background: lime;')

output

/* div(this.offsetWidth > 500) span */
[data-container-unique="0"] {
  background: lime;
}

demo

Container Queries Mixin Demo

Scoped Eval() Mixin

This mixin lets you define a CSS selector list, and to output CSS rules with JS interpolation from the context of each element in the document matching the selector.

syntax

scoped('div', `
  margin: 1em;
  background: lime;
  height: eval(this.offsetWidth / (16/9))px;
`)

output

/* Scope: div */
[data-scoped-unique="0"] {
  margin: 1em;
  background: lime;
  height: 144.5625px;
}

demo

Scoped Eval() Mixin Demo

Parent Selector Mixin

This mixin lets you define a CSS selector list and apply a CSS rule to the parent node of any matching tags in your document.

syntax

parent('li', 'border: 1px solid red;')

output

/* li:parent */
[data-parent-unique="0"] {
  border: 1px solid red;
}

demo

Parent Selector Mixin Demo

Prev Selector Mixin

This mixin lets you define a CSS selector list and apply a CSS rule to the previous sibling node of any matching tags in your document.

syntax

prev('li:nth-of-type(2)', 'background: lime;')

output

/* li:prev */
[data-prev-unique="0"] {
  background: lime;
}

demo

Prev Selector Mixin Demo

Closest Selector Mixin

This mixin lets CSS authors apply styles to the nearest element matching a CSS selector to another element matching a given CSS selector. You can use this to find the nearest matching ancestor.

syntax

closest('#start', '.target', `border-color: lime`)

output

/* #start:closest(.target) */
[data-closest-unique="0"] {
  border-color: lime
}

demo

Closest Selector Mixin Demo

Ancestor Selector Mixin

This mixin lets CSS authors apply styles to all ancestor elements matching a CSS selector to another element matching a given CSS selector. You can use this to style all matching ancestors.

syntax

ancestor('#start', '.target', `border-color: lime`)

output

/* #start:ancestor(.target) */
[data-ancestor-unique="0"] {
  border-color: lime;
}

demo

Ancestor Selector Mixin Demo

Elder Selector Mixin

This mixin lets CSS authors apply styles to all elder siblings of elements matching a CSS selector.

syntax

elder('.target', 'background: lime;')

output

[data-elder-unique="0"] {
  background: lime;
}

demo

Elder Selector Mixin Demo

Made with ♥ by @innovati


text:
package rice.pastry;

/**
 * An interface to any object capable of generating nodeIds.
 *
 * @version $Id: NodeIdFactory.java 3613 2007-02-15 14:45:14Z jstewart $
 *
 * @author Andrew Ladd
 */

public interface NodeIdFactory {
    /**
     * Generates a nodeId.
     *
     * @return a new node id.
     */

    public Id generateNodeId();
}


text:
<config xmlns="urn:org:jgroups"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:org:jgroups http://www.jgroups.org/schema/jgroups-5.2.xsd">
   <!-- This file has been adpoted from https://github.com/infinispan/infinispan/blob/master/core/src/main/resources/default-configs/default-jgroups-udp.xml -->
   <!-- jgroups.udp.address is deprecated and will be removed, see ISPN-11867 -->
   <UDP bind_addr="${jgroups.bind.address,jgroups.udp.address:127.0.0.1}"
        bind_port="${jgroups.bind.port,jgroups.udp.port:0}"
        mcast_addr="${jgroups.udp.mcast_addr,jgroups.mcast_addr:228.6.7.8}"
        mcast_port="${jgroups.udp.mcast_port,jgroups.mcast_port:46655}"
        tos="0"
        ucast_send_buf_size="1m"
        mcast_send_buf_size="1m"
        ucast_recv_buf_size="20m"
        mcast_recv_buf_size="25m"
        ip_ttl="${jgroups.ip_ttl:2}"
        thread_naming_pattern="pl"
        diag.enabled="${jgroups.diag.enabled:false}"
        bundler_type="transfer-queue"
        bundler.max_size="${jgroups.bundler.max_size:64000}"

        thread_pool.min_threads="${jgroups.thread_pool.min_threads:0}"
        thread_pool.max_threads="${jgroups.thread_pool.max_threads:200}"
        thread_pool.keep_alive_time="60000"

        thread_pool.thread_dumps_threshold="${jgroups.thread_dumps_threshold:10000}"
   />
   <RED/>
   <PING num_discovery_runs="3"/>
   <MERGE3 min_interval="10000"
           max_interval="30000"
   />
   <FD_SOCK2 offset="${jgroups.fd.port-offset:50000}"/>
   <FD_ALL3/>
   <VERIFY_SUSPECT timeout="1000"/>
   <pbcast.NAKACK2 xmit_interval="100"
                   xmit_table_num_rows="50"
                   xmit_table_msgs_per_row="1024"
                   xmit_table_max_compaction_time="30000"
                   resend_last_seqno="true"
   />
   <UNICAST3 xmit_interval="100"
             xmit_table_num_rows="50"
             xmit_table_msgs_per_row="1024"
             xmit_table_max_compaction_time="30000"
   />
   <pbcast.STABLE desired_avg_gossip="5000"
                  max_bytes="1M"
   />
   <pbcast.GMS print_local_addr="false"
               join_timeout="${jgroups.join_timeout:500}"
   />
   <UFC max_credits="${jgroups.max_credits:4m}"
        min_threshold="0.40"
   />
   <MFC max_credits="${jgroups.max_credits:4m}"
        min_threshold="0.40"
   />
   <FRAG4 frag_size="${jgroups.frag_size:60000}"/>
</config>


text:
[![Gem Version](https://badge.fury.io/rb/json-schema.svg)](https://badge.fury.io/rb/json-schema)
[![Travis](https://travis-ci.org/ruby-json-schema/json-schema.svg?branch=master)](https://travis-ci.org/ruby-json-schema/json-schema)
[![Code Climate](https://codeclimate.com/github/ruby-json-schema/json-schema/badges/gpa.svg)](https://codeclimate.com/github/ruby-json-schema/json-schema)

Ruby JSON Schema Validator
==========================

This library is intended to provide Ruby with an interface for validating JSON
objects against a JSON schema conforming to [JSON Schema Draft
4](http://tools.ietf.org/html/draft-zyp-json-schema-04). Legacy support for
[JSON Schema Draft 3](http://tools.ietf.org/html/draft-zyp-json-schema-03),
[JSON Schema Draft 2](http://tools.ietf.org/html/draft-zyp-json-schema-02), and
[JSON Schema Draft 1](http://tools.ietf.org/html/draft-zyp-json-schema-01) is
also included.

Additional Resources
--------------------

- [Google Groups](https://groups.google.com/forum/#!forum/ruby-json-schema)
- #ruby-json-schema on chat.freenode.net

Version 2.0.0 Upgrade Notes
---------------------------

Please be aware that the upgrade to version 2.0.0 will use Draft-04 **by
default**, so schemas that do not declare a validator using the `$schema`
keyword will use Draft-04 now instead of Draft-03. This is the reason for the
major version upgrade.

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

From rubygems.org:

```sh
gem install json-schema
```

From the git repo:

```sh
$ gem build json-schema.gemspec
$ gem install json-schema-2.5.2.gem
```

Validation
-----

Three base validation methods exist:

1. `validate`: returns a boolean on whether a validation attempt passes
2. `validate!`: throws a `JSON::Schema::ValidationError` with an appropriate message/trace on where the validation failed
3. `fully_validate`: builds an array of validation errors return when validation is complete

All methods take two arguments, which can be either a JSON string, a file
containing JSON, or a Ruby object representing JSON data. The first argument to
these methods is always the schema, the second is always the data to validate.
An optional third options argument is also accepted; available options are used
in the examples below.

By default, the validator uses the [JSON Schema Draft
4](http://tools.ietf.org/html/draft-zyp-json-schema-04) specification for
validation; however, the user is free to specify additional specifications or
extend existing ones. Legacy support for Draft 1, Draft 2, and Draft 3 is
included by either passing an optional `:version` parameter to the `validate`
method (set either as `:draft1` or `draft2`), or by declaring the `$schema`
attribute in the schema and referencing the appropriate specification URI. Note
that the `$schema` attribute takes precedence over the `:version` option during
parsing and validation.

For further information on json schema itself refer to Understanding
JSON Schema.

Basic Usage
--------------

```ruby
require "json-schema"

schema = {
  "type" => "object",
  "required" => ["a"],
  "properties" => {
    "a" => {"type" => "integer"}
  }
}

#
# validate ruby objects against a ruby schema
#

# => true
JSON::Validator.validate(schema, { "a" => 5 })
# => false
JSON::Validator.validate(schema, {})

#
# validate a json string against a json schema file
#

require "json"
File.write("schema.json", JSON.dump(schema))

# => true
JSON::Validator.validate('schema.json', '{ "a": 5 }')

#
# raise an error when validation fails
#

# => "The property '#/a' of type String did not match the following type: integer"
begin
  JSON::Validator.validate!(schema, { "a" => "taco" })
rescue JSON::Schema::ValidationError => e
  e.message
end

#
# return an array of error messages when validation fails
#

# => ["The property '#/a' of type String did not match the following type: integer in schema 18a1ffbb-4681-5b00-bd15-2c76aee4b28f"]
JSON::Validator.fully_validate(schema, { "a" => "taco" })
```

Advanced Options
-----------------

```ruby
require "json-schema"

schema = {
  "type"=>"object",
  "required" => ["a"],
  "properties" => {
    "a" => {
      "type" => "integer",
      "default" => 42
    },
    "b" => {
      "type" => "object",
      "properties" => {
        "x" => {
          "type" => "integer"
        }
      }
    }
  }
}

#
# with the `:list` option, a list can be validated against a schema that represents the individual objects
#

# => true
JSON::Validator.validate(schema, [{"a" => 1}, {"a" => 2}, {"a" => 3}], :list => true)
# => false
JSON::Validator.validate(schema, [{"a" => 1}, {"a" => 2}, {"a" => 3}])

#
# with the `:errors_as_objects` option, `#fully_validate` returns errors as hashes instead of strings
#

# => [{:schema=>#<Addressable::URI:0x3ffa69cbeed8 URI:18a1ffbb-4681-5b00-bd15-2c76aee4b28f>, :fragment=>"#/a", :message=>"The property '#/a' of type String did not match the following type: integer in schema 18a1ffbb-4681-5b00-bd15-2c76aee4b28f", :failed_attribute=>"TypeV4"}]
JSON::Validator.fully_validate(schema, { "a" => "taco" }, :errors_as_objects => true)

#
# with the `:strict` option, all properties are condisidered to have `"required": true` and all objects `"additionalProperties": false`
#

# => true
JSON::Validator.validate(schema, { "a" => 1, "b" => { "x" => 2 } }, :strict => true)
# => false
JSON::Validator.validate(schema, { "a" => 1, "b" => { "x" => 2 }, "c" => 3 }, :strict => true)
# => false
JSON::Validator.validate(schema, { "a" => 1 }, :strict => true)

#
# with the `:fragment` option, only a fragment of the schema is used for validation
#

# => true
JSON::Validator.validate(schema, { "x" => 1 }, :fragment => "#/properties/b")
# => false
JSON::Validator.validate(schema, { "x" => 1 })

#
# with the `:validate_schema` option, the schema is validated (against the json schema spec) before the json is validated (against the specified schema)
#

# => true
JSON::Validator.validate(schema, { "a" => 1 }, :validate_schema => true)
# => false
JSON::Validator.validate({ "required" => true }, { "a" => 1 }, :validate_schema => true)

#
# with the `:insert_defaults` option, any undefined values in the json that have a default in the schema are replaced with the default before validation
#

# => true
JSON::Validator.validate(schema, {}, :insert_defaults => true)
# => false
JSON::Validator.validate(schema, {})

#
# with the `:version` option, schemas conforming to older drafts of the json schema spec can be used
#

v2_schema = {
  "type" => "object",
  "properties" => {
    "a" => {
      "type" => "integer"
    }
  }
}

# => false
JSON::Validator.validate(v2_schema, {}, :version => :draft2)
# => true
JSON::Validator.validate(v2_schema, {})

#
# with the `:parse_data` option set to false, the json must be a parsed ruby object (not a json text, a uri or a file path)
#

# => true
JSON::Validator.validate(schema, { "a" => 1 }, :parse_data => false)
# => false
JSON::Validator.validate(schema, '{ "a": 1 }', :parse_data => false)

#
# with the `:json` option, the json must be an unparsed json text (not a hash, a uri or a file path)
#

# => true
JSON::Validator.validate(schema, '{ "a": 1 }', :json => true)
# => "no implicit conversion of Hash into String"
begin
  JSON::Validator.validate(schema, { "a" => 1 }, :json => true)
rescue TypeError => e
  e.message
end

#
# with the `:uri` option, the json must be a uri or file path (not a hash or a json text)
#

File.write("data.json", '{ "a": 1 }')

# => true
JSON::Validator.validate(schema, "data.json", :uri => true)
# => "Can't convert Hash into String."
begin
  JSON::Validator.validate(schema, { "a"  => 1 }, :uri => true)
rescue TypeError => e
  e.message
end

#
# with the `:clear_cache` option set to true, the internal cache of schemas is
# cleared after validation (otherwise schemas are cached for efficiency)
#

File.write("schema.json", v2_schema.to_json)

# => true
JSON::Validator.validate("schema.json", {})

File.write("schema.json", schema.to_json)

# => true
JSON::Validator.validate("schema.json", {}, :clear_cache => true)

# => false
JSON::Validator.validate("schema.json", {})
```

Extending Schemas
-----------------

For this example, we are going to extend the [JSON Schema Draft
3](http://tools.ietf.org/html/draft-zyp-json-schema-03) specification by adding
a 'bitwise-and' property for validation.

```ruby
require "json-schema"

class BitwiseAndAttribute < JSON::Schema::Attribute
  def self.validate(current_schema, data, fragments, processor, validator, options = {})
    if data.is_a?(Integer) && data & current_schema.schema['bitwise-and'].to_i == 0
      message = "The property '#{build_fragment(fragments)}' did not evaluate  to true when bitwise-AND'd with  #{current_schema.schema['bitwise-or']}"
      validation_error(processor, message, fragments, current_schema, self, options[:record_errors])
    end
  end
end

class ExtendedSchema < JSON::Schema::Draft3
  def initialize
    super
    @attributes["bitwise-and"] = BitwiseAndAttribute
    @uri = JSON::Util::URI.parse("http://test.com/test.json")
    @names = ["http://test.com/test.json"]
  end

  JSON::Validator.register_validator(self.new)
end

schema = {
  "$schema" => "http://test.com/test.json",
  "properties" => {
    "a" => {
      "bitwise-and" => 1
    },
    "b" => {
      "type" => "string"
    }
  }
}

data = {
  "a" => 0
}

data = {"a" => 1, "b" => "taco"}
JSON::Validator.validate(schema,data) # => true
data = {"a" => 1, "b" => 5}
JSON::Validator.validate(schema,data) # => false
data = {"a" => 0, "b" => "taco"}
JSON::Validator.validate(schema,data) # => false
```

Custom format validation
------------------------

The JSON schema standard allows custom formats in schema definitions which
should be ignored by validators that do not support them. JSON::Schema allows
registering procs as custom format validators which receive the value to be
checked as parameter and must raise a `JSON::Schema::CustomFormatError` to
indicate a format violation. The error message will be prepended by the property
name, e.g. [The property '#a']()

```ruby
require "json-schema"

format_proc = -> value {
  raise JSON::Schema::CustomFormatError.new("must be 42") unless value == "42"
}

# register the proc for format 'the-answer' for draft4 schema
JSON::Validator.register_format_validator("the-answer", format_proc, ["draft4"])

# omitting the version parameter uses ["draft1", "draft2", "draft3", "draft4"] as default
JSON::Validator.register_format_validator("the-answer", format_proc)

# deregistering the custom validator
# (also ["draft1", "draft2", "draft3", "draft4"] as default version)
JSON::Validator.deregister_format_validator('the-answer', ["draft4"])

# shortcut to restore the default formats for validators (same default as before)
JSON::Validator.restore_default_formats(["draft4"])

# with the validator registered as above, the following results in
# ["The property '#a' must be 42"] as returned errors
schema = {
  "$schema" => "http://json-schema.org/draft-04/schema#",
  "properties" => {
    "a" => {
      "type" => "string",
      "format" => "the-answer",
    }
  }
}
errors = JSON::Validator.fully_validate(schema, {"a" => "23"})
```

Validating a JSON Schema
------------------------

To validate that a JSON Schema conforms to the JSON Schema standard,
you need to validate your schema against the metaschema for the appropriate
JSON Schema Draft. All of the normal validation methods can be used
for this. First retrieve the appropriate metaschema from the internal
cache (using `JSON::Validator.validator_for_name()` or
`JSON::Validator.validator_for_uri()`) and then simply validate your
schema against it.

```ruby
require "json-schema"

schema = {
  "type" => "object",
  "properties" => {
    "a" => {"type" => "integer"}
  }
}

metaschema = JSON::Validator.validator_for_name("draft4").metaschema
# => true
JSON::Validator.validate(metaschema, schema)
```

Controlling Remote Schema Reading
---------------------------------

In some cases, you may wish to prevent the JSON Schema library from making HTTP
calls or reading local files in order to resolve `$ref` schemas. If you fully
control all schemas which should be used by validation, this could be
accomplished by registering all referenced schemas with the validator in
advance:

```ruby
schema = JSON::Schema.new(some_schema_definition, Addressable::URI.parse('http://example.com/my-schema'))
JSON::Validator.add_schema(schema)
```

If more extensive control is necessary, the `JSON::Schema::Reader` instance used
can be configured in a few ways:

```ruby
# Change the default schema reader used
JSON::Validator.schema_reader = JSON::Schema::Reader.new(:accept_uri => true, :accept_file => false)

# For this validation call, use a reader which only accepts URIs from my-website.com
schema_reader = JSON::Schema::Reader.new(
  :accept_uri => proc { |uri| uri.host == 'my-website.com' }
)
JSON::Validator.validate(some_schema, some_object, :schema_reader => schema_reader)
```

The `JSON::Schema::Reader` interface requires only an object which responds to
`read(string)` and returns a `JSON::Schema` instance. See the [API
documentation](http://www.rubydoc.info/github/ruby-json-schema/json-schema/master/JSON/Schema/Reader)
for more information.

JSON Backends
-------------

The JSON Schema library currently supports the `json` and `yajl-ruby` backend
JSON parsers. If either of these libraries are installed, they will be
automatically loaded and used to parse any JSON strings supplied by the user.

If more than one of the supported JSON backends are installed, the `yajl-ruby`
parser is used by default. This can be changed by issuing the following before
validation:

```ruby
JSON::Validator.json_backend = :json
```

Optionally, the JSON Schema library supports using the MultiJSON library for
selecting JSON backends. If the MultiJSON library is installed, it will be
autoloaded.

Notes
-----

The 'format' attribute is only validated for the following values:

- date-time
- date
- time
- ip-address (IPv4 address in draft1, draft2 and draft3)
- ipv4 (IPv4 address in draft4)
- ipv6
- uri

All other 'format' attribute values are simply checked to ensure the instance
value is of the correct datatype (e.g., an instance value is validated to be an
integer or a float in the case of 'utc-millisec').

Additionally, JSON::Validator does not handle any json hyperschema attributes.


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ajax_Post_Controller extends CI_Controller {

    public function __construct() {
      parent::__construct();
      $this->load->helper('url_helper');
      $this->load->helper('url');
      $this->load->library('session');
    }

// Show view Page

public function index(){

$this->load->view("ajax_post_view");

}

// This function call from AJAX

public function user_data_submit() {

$data = array(

'username' => $this->input->post('name'),

'pwd'=>$this->input->post('pwd')

);

//Either you can print value or you can send value to database

echo json_encode($data);

}

}


text:
The idea here is to explore aggregation based on hashing the group by keys & using properties of
aggregate functions to arrive at the aggregates
####Properties of aggregate functions
* Sum, Min, Max, Count-- can be computed without storing the data points[Memory less]
* Average -- can be computed without storing the data points but cannot be merged[non-associative]
* Median & Quantiles -- need all the data points
* Quantiles can also be computed using Tdigest/QDigest [http://www.inf.fu-berlin.de/lehre/WS11/Wireless/papers/AgrQdigest.pdf]
Details on Qdigest & Tdigest http://info.prelert.com/blog/q-digest-an-algorithm-for-computing-approximate-quantiles-on-a-collection-of-integers
Sketch algorithms can also be used to count cardinality[HyperLogLog] & Top-N[Count-MinSketch]

Using Disk based cache to handle large data sets
As the records are parsed the group by keys are digested[compressed] into  hashkey.

* Key Cache -- maintains the hashkey and the details of the GenericGroupByKey
* Data Cache -- maintains the aggregate data [either all datapoints or only summary] for each group by combination

MurMur Hash [Guava Hashing.murmur3_128]  is used to generate hash for the groupby combination
Infinispan cache can be used to to spill to disk when overflowing the data; this will take care of large aggregation of large datasets

TODO: performance test with large data file
Running
java -jar target/aggregator-jar-with-dependencies.jar <rawfactfile> <outdir>
 Example:
java -jar target/aggregator-jar-with-dependencies.jar /tmp/fact2.csv /tmp/aggdata/


text:
dockerer
========

dockerer provides you with a CentOS VM environment with Chef/Docker/kitchen-docker enabled.
You can create an environment to run following tools on CentOS only executing `vagrant up`.

- Chef (toolkit from omnibus installer)
- Docker
- knife-solo
- test-kitchen
- kitchen-docker
- ServerSpec

How to use
==========

1. Install Vagrant

    `http://www.vagrantup.com/`

2. Execute following command inside your project directory for Chef (that you want to run test-kitchen with kitchen-docker).

    ```bash
    git clone https://github.com/ryotaro/dockerer.git
    cd dockerer
    vagrant up
    ```

3. Now, you can login to Vagrant's CentOS VM Environment that you can use above toolkit by following command.

    ```bash
    vagrant ssh
    ```

4. You can see a directory *develop* that is mounted directory to your Chef project directory.

5. Go into the *develop* directory and execute toolkits!

Contact
=======

Feel free to contact me via: ryo@longsleeper.com
(Both English and Japanese are OK)


text:
<?php

namespace JShrink\Test;

use JShrink\Minifier;

class JShrinkTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException RuntimeException
     * @expectedExceptionMessage Unclosed multiline comment at position: 1
     */
    public function testUnclosedCommentException()
    {
        \JShrink\Minifier::minify('/* This comment is hanging out.');
    }

    /**
     * @expectedException RuntimeException
     * @expectedExceptionMessage Unclosed string at position: 14
     */
    public function testUnclosedStringException()
    {
        \JShrink\Minifier::minify('var string = "This string is hanging out.');
    }

    /**
     * @expectedException RuntimeException
     * @expectedExceptionMessage Unclosed regex pattern at position: 23
     */
    public function testUnclosedRegexException()
    {
        \JShrink\Minifier::minify('var re = /[^A-Za-z0-9_
        var string = "Another Filler"');
    }

    /**
     * @jshrink
     * @dataProvider JShrinkProvider
     */
    public function testJShrink($testName, $input, $output)
    {
        $this->assertEquals($output, \JShrink\Minifier::minify($input), 'Running JShrink Test: ' . $testName);
    }

    /**
     * @uglify
     * @dataProvider uglifyProvider
     */
    public function testUglify($testName, $input, $output)
    {
        $this->assertEquals($output, \JShrink\Minifier::minify($input), 'Running Uglify Test: ' . $testName);
    }

    /**
     * @group requests
     * @dataProvider requestProvider
     */
    public function testRequests($testName, $input, $output)
    {
        $this->assertEquals($output, \JShrink\Minifier::minify($input), 'Running User Requested Test: ' . $testName);
    }

    /**
     * @group development
     * @dataProvider developmentProvider
     */
    public function testDevelopment($testName, $input, $output)
    {
        $this->assertEquals($output, \JShrink\Minifier::minify($input), 'Running Development Test: ' . $testName);
    }

    /**
     * This function loads all of the test cases from the specified group.
     * Groups are created simply by populating the appropriate directories:
     *
     *    /tests/Resources/GROUPNAME/input/
     *    /tests/Resources/GROUPNAME/output/
     *
     * Each test case should have two identically named files, with the raw
     * javascript going in the test folder and the expected results to be in
     * the output folder.
     *
     * @param $group string
     * @return array
     */
    public function getTestFiles($group)
    {
        $baseDir = __DIR__ . '/../../Resources/' . $group . '/';
        $testDir = $baseDir . 'input/';
        $expectDir = $baseDir . 'output/';

        $returnData = array();

        $testFiles = scandir($testDir);
        foreach ($testFiles as $testFile) {
            if(substr($testFile, -3) !== '.js' || !file_exists(($expectDir . $testFile)))
                continue;

            $testInput = file_get_contents($testDir . $testFile);
            $testOutput = file_get_contents($expectDir . $testFile);

            $returnData[] = array($testFile, $testInput, $testOutput);
        }

        return $returnData;
    }

    public function uglifyProvider()
    {
        return $this->getTestFiles('uglify');
    }

    public function JShrinkProvider()
    {
        return $this->getTestFiles('jshrink');
    }

    public function requestProvider()
    {
        return $this->getTestFiles('requests');
    }

    public function developmentProvider()
    {
        return $this->getTestFiles('development');
    }
}


text:
class EuclideanNormTest extends EuclideanNorm {
  public static void main(String[] args) {
    int[] v = {1,2,3,4};
    System.out.println(euclidean_norm(v)); // 5.477225575051661
  }
}


text:
VERSION="$1"
DIR="bltool-$VERSION"

lein uberjar
cd target
mkdir "$DIR"
cp -v $(ls bltool-*-standalone.jar | tail -n1) "$DIR/bltool.jar"
cp -v ../steam2backloggery.* "$DIR"
cp -v ../README.md "$DIR/README.txt"
zip -r "bltool-$VERSION.zip" "$DIR"
rm -rf "$DIR"


text:
New Smartplug

     Home

	<form data-ng-submit="create()" novalidate>

			Smart Plug ID

				<input class="form-control" type="text" data-ng-model="sid" id="sid" placeholder="Smart Plug Id" required>

			Name

				<input class="form-control" type="text" data-ng-model="name" id="name"  placeholder="Name"/>

			Type

				<input class="form-control" type="text" data-ng-model="type" id="type" placeholder="Type"/>

			Device

				<input class="form-control" type="text" data-ng-model="device" id="device" placeholder="Device"/>

			Devices

				<select class="form-control" data-ng-click="getSelectedDevice(devices)" data-ng-model="devices" ng-options="sm._id as sm.name for sm in deviceList"></select>

			<input class="form-control btn-primary btn-info" type="submit">

	</form>


text:
require 'slack-api-wrapper'
require 'logger'
require 'date'

module Slackpolice
  class Client
    def initialize(cli_options = {})
      @cli_options = cli_options
      @logger ||= Logger.new STDOUT

      @client = Slack::Client.new @cli_options[:api_token]
      @client.auth_test
    end

    def archive
      archives = []
      no_members_channels.each do |c|
        resp = @client.channels_archive('channel' => c['id'])
        archives << c if resp['ok']
      end
      archives
    end

    def delete_expired_files(ts_to = Date.today.prev_day(7))
      Enumerator.new do |y|
        expired_files(ts_to).each do |f|
          resp = @client.files_delete('file' => f['id'])
          y << f if resp['ok']
        end
      end
    end

    def no_members_channels
      @client.channels_list['channels'].select do |c|
        c['num_members'] == 0 && c['is_archived'] == false
      end
    end

    def expired_files(ts_to = Date.today.prev_day(7))
      page = 1
      Enumerator.new do |y|
        begin
          resp = @client.files_list('ts_to' => ts_to.to_time.to_i, 'page' => page)
          if resp['ok']
            pages = resp['paging']['pages']
            resp['files'].map do |file|
              y << file
            end
          end
          page += 1
        end while pages >= page && 100 > page # over 100 page is not found. api bug?
      end
    end
  end
end


text:
#ifndef RTC_BASE_ASYNCUDPSOCKET_H_
#define RTC_BASE_ASYNCUDPSOCKET_H_

#include <memory>

#include "rtc_base/asyncpacketsocket.h"
#include "rtc_base/socketfactory.h"

namespace rtc {

// Provides the ability to receive packets asynchronously.  Sends are not
// buffered since it is acceptable to drop packets under high load.
class AsyncUDPSocket : public AsyncPacketSocket {
 public:
  // Binds |socket| and creates AsyncUDPSocket for it. Takes ownership
  // of |socket|. Returns null if bind() fails (|socket| is destroyed
  // in that case).
  static AsyncUDPSocket* Create(AsyncSocket* socket,
                                const SocketAddress& bind_address);
  // Creates a new socket for sending asynchronous UDP packets using an
  // asynchronous socket from the given factory.
  static AsyncUDPSocket* Create(SocketFactory* factory,
                                const SocketAddress& bind_address);
  explicit AsyncUDPSocket(AsyncSocket* socket);
  ~AsyncUDPSocket() override;

  SocketAddress GetLocalAddress() const override;
  SocketAddress GetRemoteAddress() const override;
  int Send(const void* pv,
           size_t cb,
           const rtc::PacketOptions& options) override;
  int SendTo(const void* pv,
             size_t cb,
             const SocketAddress& addr,
             const rtc::PacketOptions& options) override;
  int Close() override;

  State GetState() const override;
  int GetOption(Socket::Option opt, int* value) override;
  int SetOption(Socket::Option opt, int value) override;
  int GetError() const override;
  void SetError(int error) override;

 private:
  // Called when the underlying socket is ready to be read from.
  void OnReadEvent(AsyncSocket* socket);
  // Called when the underlying socket is ready to send.
  void OnWriteEvent(AsyncSocket* socket);

  std::unique_ptr<AsyncSocket> socket_;
  char* buf_;
  size_t size_;
};

}  // namespace rtc

#endif  // RTC_BASE_ASYNCUDPSOCKET_H_


text:
set -e  # Exit immediately when one of the commands fails.
set -x  # Verbose

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
EXAMPLES_DIR="$(realpath "${SCRIPT_DIR}/../examples")"

PROJECT_EXT=".xcodeproj"
WORKSPACE_EXT=".xcworkspace"

# Keep a list of iOS apps which should be excluded from the CI builds.
SKIPPED_BUILDS="
gesture_classification/ios
classification_by_retrieval/ios
"

function build_ios_example {
  # Check if this directory appears in the skipped builds list.
  RELATIVE_DIR="${1#"${EXAMPLES_DIR}/"}"
  if echo "${SKIPPED_BUILDS}" | grep -qx "${RELATIVE_DIR}"; then
    echo "WARNING: Skipping build for ${RELATIVE_DIR}."
    return 0
  fi

  echo "=== BUILD STARTED: ${RELATIVE_DIR} ==="

  pushd "$1" > /dev/null

  # Cleanly install the dependencies
  # Retry a few times to workaround intermittent download errors.
  MAX_RETRY=3
  INSTALLED=false
  for i in $(seq 1 ${MAX_RETRY})
  do
    echo "Trying to install dependencies... (trial $i)"
    if pod install --verbose --repo-update --clean-install; then
      INSTALLED=true
      break
    fi
  done

  if [[ "${INSTALLED}" == false ]]; then
    echo "Exceeded the max retry limit (${MAX_RETRY}) of pod install command."
    exit 1
  fi

  # Extract the scheme names.
  PROJECT_NAME="$(find * -maxdepth 0 -type d -name "*${PROJECT_EXT}")"
  WORKSPACE_NAME="$(find * -type d -name "*${WORKSPACE_EXT}")"
  SCHEMES="$(xcodebuild -list -project "${PROJECT_NAME}" -json | jq -r ".project.schemes[]")"

  # Build each scheme without code signing.
  for scheme in ${SCHEMES}; do
    # Due to an unknown issue prior to Xcode 11.4, a non-existing test scheme
    # might appear in the list of project schemes. For now, if a scheme name
    # contains the word "Tests", skip the build for that particular scheme.
    if [[ "${scheme}" == *"Tests"* ]]; then
      continue
    fi

    echo "--- BUILDING SCHEME ${scheme} FOR PROJECT ${RELATIVE_DIR} ---"
    set -o pipefail && xcodebuild \
        CODE_SIGN_IDENTITY="" \
        CODE_SIGNING_REQUIRED="NO" \
        CODE_SIGN_ENTITLEMENTS="" \
        CODE_SIGNING_ALLOWED="NO" \
        ARCHS="arm64" \
        -scheme "${scheme}" \
        -workspace "${WORKSPACE_NAME}" \
        | xcpretty  # Pretty print the build output.
    echo "--- FINISHED BUILDING SCHEME ${scheme} FOR PROJECT ${RELATIVE_DIR} ---"
  done

  popd > /dev/null

  echo "=== BUILD FINISHED: ${RELATIVE_DIR} ==="
  echo
  echo
}

build_ios_example "$1"


text:
<?php

/**
 * This file is part of the FOSElasticaBundle project.
 *
 * (c) Tim Nagel <tim@nagel.com.au>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace FOS\ElasticaBundle\Tests\Functional;

/**
 * @group functional
 */
class SerializerTest extends WebTestCase
{
    public function testMappingIteratorToArrayField()
    {
        $client = $this->createClient(array('test_case' => 'Serializer'));
        $persister = $client->getContainer()->get('fos_elastica.object_persister.index.type');

        $object = new TypeObj();
        $object->id = 1;
        $object->coll = new \ArrayIterator(array('foo', 'bar'));
        $persister->insertOne($object);

        $object->coll = new \ArrayIterator(array('foo', 'bar', 'bazz'));
        $object->coll->offsetUnset(1);

        $persister->replaceOne($object);
    }

    public function testUnmappedType()
    {
        $client = $this->createClient(array('test_case' => 'Serializer'));
        $resetter = $client->getContainer()->get('fos_elastica.resetter');
        $resetter->resetIndex('index');
    }

    protected function setUp()
    {
        parent::setUp();

        $this->deleteTmpDir('Serializer');
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->deleteTmpDir('Serializer');
    }
}


text:
package graphcomputer;

import graph.IGraph;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap;
import it.unimi.dsi.fastutil.ints.Int2IntMap;

import java.util.concurrent.ForkJoinPool;

import centrality.ConnectedComponents;
import centrality.PageRank;
import communitydetection.LP;

public class GraphComputer {
	protected final ForkJoinPool pool;

	public GraphComputer() {
		this( Runtime.getRuntime().availableProcessors() );
	}

	public GraphComputer(int nthreads) {
		this.pool 	= new ForkJoinPool(nthreads);
	}

	/**
	 * Execute algorithm
	 * @param graph
	 * @param iterations
	 */
	public void execute(final VertexFunction vertexFunction, final IGraph graph, int iterations) {

		for(int it=0; it<iterations; it++) {
			try {
				pool.submit( () -> {
					graph.getNodeSet().parallelStream()
						.forEach( node ->
							vertexFunction.apply(graph, node)
						);
				} ).get();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void dismiss() {
		this.pool.shutdown();
	}

	public Int2IntMap getResult(LP lp) {
		return lp.getResult();
	}

	public Int2DoubleMap getResult(PageRank pg) {
		return pg.getResult();
	}

	public Int2IntMap getResult(ConnectedComponents cc) {
		return cc.getResult();
	}
}


text:
package common

import (
	"fmt"
	"github.com/mikeyhu/glipso/interfaces"
)

// Environment Provides a mechanism for creating and resolving variables
type Environment struct {
	id        int
	variables map[REF]interfaces.Value
	parent    *Environment
}

// ResolveRef will try to resolve a provided reference to a value in this or parent scope
func (env Environment) ResolveRef(ref interfaces.Type) (interfaces.Value, bool) {
	if env.variables != nil {
		if result, ok := env.variables[ref.(REF)]; ok {
			if DEBUG {
				fmt.Printf("found %v in scope %v\n", ref, env.id)
			}
			return result, true
		}
	}
	if env.parent != nil {
		return env.parent.ResolveRef(ref)
	}
	if fi, ok := inbuilt[ref.(REF)]; ok {
		if DEBUG {
			fmt.Printf("found %v in inbuilt\n", ref)
		}
		return fi, true
	}
	return nil, false
}

// CreateRef will create a variable in this scope
func (env *Environment) CreateRef(name interfaces.Type, arg interfaces.Value) interfaces.Type {
	if DEBUG {
		fmt.Printf("Adding %v %v to %v\n", name, arg, env)
	}
	if env.variables == nil {
		env.variables = map[REF]interfaces.Value{}
	}
	env.variables[name.(REF)] = arg
	return name
}

// NewChildScope creates new scope that inherits from this one
func (env Environment) NewChildScope() interfaces.Scope {
	id := nextScopeID()
	if DEBUG {
		fmt.Printf("New scope %d from %d\n", id, env.id)
	}
	return &Environment{
		id:     id,
		parent: &env,
	}
}

// DisplayEnvironment is used to display environment information for internal debugging
func (env Environment) DisplayEnvironment() {
	if DEBUG {
		env.displayEnvironment(0)
	}
}

func (env Environment) displayEnvironment(i int) {
	for k := range env.variables {
		fmt.Printf("Scope[%d %d] %v := %v\n", env.id, i, k, env.variables[k])
	}
	if env.parent != nil {
		env.parent.displayEnvironment(i + 1)
	}
}

func (env Environment) String() string {
	return fmt.Sprintf("ENV{%d}", env.id)
}

// GlobalEnvironment acts as the global scope for variables
var GlobalEnvironment *Environment

func init() {
	GlobalEnvironment = &Environment{
		id:        nextScopeID(),
		variables: map[REF]interfaces.Value{},
	}
}

var scopeID = 0

func nextScopeID() int {
	scopeID = scopeID + 1
	return scopeID
}

// DisplayDiagnostics outputs Information about the Scopes
func (env Environment) DisplayDiagnostics() {
	if DEBUG {
		fmt.Printf("Total number of scopes created: %v", scopeID)
	}
}


text:
                <title>Billing Application</title>
                <link rel="stylesheet" href="<?php echo base_url(); ?>assets/js/extjs/resources/css/ext-all.css" type="text/css" />


text:
'use strict';

angular.module('mementoMovieApp')
  .filter('formatHeader', function ($compile) {
    return function (filter, selectedFilter, isDesktop) {
      var template;
      if (selectedFilter && selectedFilter.key === filter.key) {
        template = '' + selectedFilter.value + '';
      } else {
        template = 'All ' + filter.title + '';
      }
      if (isDesktop) {
        template = ' ' + template;
      }

      return template;
    };
  });


text:
package edu.tamu.tcat.dia;

/**
 * Top-level exception for the document image analysis libraries.
 */
public class DiaException extends Exception
{

   public DiaException()
   {
   }

   public DiaException(String message)
   {
      super(message);
   }

   public DiaException(Throwable cause)
   {
      super(cause);
   }

   public DiaException(String message, Throwable cause)
   {
      super(message, cause);
   }

   public DiaException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
   {
      super(message, cause, enableSuppression, writableStackTrace);
   }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/icon_comment_bad_selected" android:state_selected="true" />
    <item android:drawable="@drawable/icon_comment_bad_selected" android:state_pressed="true" />
    <item android:drawable="@drawable/icon_comment_bad_normal"/>
</selector>


text:
import ReactDOMServer from 'react-dom/server';

import ComponentRegistry from './ComponentRegistry';
import createReactElement from './createReactElement';
import isCreateReactElementResultNonReactComponent from
  './isCreateReactElementResultNonReactComponent';
import buildConsoleReplay from './buildConsoleReplay';
import handleError from './handleError';

export default function serverRenderReactComponent(options) {
  const { name, domNodeId, trace, props, railsContext } = options;

  let htmlResult = '';
  let hasErrors = false;

  try {
    const componentObj = ComponentRegistry.get(name);
    if (componentObj.isRenderer) {
      throw new Error(`\
Detected a renderer while server rendering component '${name}'. \
See https://github.com/shakacode/react_on_rails#renderer-functions`);
    }

    const reactElementOrRouterResult = createReactElement({
      componentObj,
      domNodeId,
      trace,
      props,
      railsContext,
    });

    if (isCreateReactElementResultNonReactComponent(reactElementOrRouterResult)) {
      // We let the client side handle any redirect
      // Set hasErrors in case we want to throw a Rails exception
      hasErrors = !!reactElementOrRouterResult.routeError;

      if (hasErrors) {
        console.error(
          `React Router ERROR: ${JSON.stringify(reactElementOrRouterResult.routeError)}`,
        );
      }

      if (reactElementOrRouterResult.redirectLocation) {
        if (trace) {
          const redirectLocation = reactElementOrRouterResult.redirectLocation;
          const redirectPath = redirectLocation.pathname + redirectLocation.search;
          console.log(`\
ROUTER REDIRECT: ${name} to dom node with id: ${domNodeId}, redirect to ${redirectPath}`,
          );
        }
        // For redirects on server rendering, we can't stop Rails from returning the same result.
        // Possibly, someday, we could have the rails server redirect.
      } else {
        htmlResult = reactElementOrRouterResult.renderedHtml;
      }
    } else {
      htmlResult = ReactDOMServer.renderToString(reactElementOrRouterResult);
    }
  } catch (e) {
    hasErrors = true;
    htmlResult = handleError({
      e,
      name,
      serverSide: true,
    });
  }

  const consoleReplayScript = buildConsoleReplay();

  return JSON.stringify({
    html: htmlResult,
    consoleReplayScript,
    hasErrors,
  });
}


text:
package liquibase.samples.osgi.jpa.model;

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

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * Sample JPA model class
 *
 * @author mkeith
 */
@Entity
public class Account {

    @Id @GeneratedValue
    int id;

    double balance;

    @OneToOne(mappedBy="account")
    Customer customer;

    @OneToMany(mappedBy="account")
    @OrderBy("txTime")
    List<Transaction> txns;

    @Temporal(TemporalType.DATE)
    public Date dateCreated;

    /* Constructors */
    public Account() {
        dateCreated = new Date(System.currentTimeMillis());
    }
    public Account(Customer customer) {
        this();
        this.balance = 0;
        this.customer = customer;
        customer.setAccount(this);
        this.txns = new ArrayList<Transaction>();
    }

    /* Getters and setters */
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public double getBalance() { return balance; }
    public void setBalance(double balance) { this.balance = balance; }

    public Customer getCustomer() { return customer; }
    public void setCustomer(Customer customer) { this.customer = customer; }

    public List<Transaction> getTxns() { return txns; }
    public void setTxns(List<Transaction> txns) { this.txns = txns; }

    public String toString() {
        return "Account(" + id + ", " + ((customer!=null)?customer.getLastName():"null") + ", Balance: $" + balance + ")";
    }
}


text:
package co.yiiu.pybbs.directive;

import co.yiiu.pybbs.model.Topic;
import co.yiiu.pybbs.service.ITopicService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class OtherTopicDirective implements TemplateDirectiveModel {

    @Autowired
    private ITopicService topicService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody
            templateDirectiveBody) throws TemplateException, IOException {
        Integer userId = Integer.parseInt(map.get("userId").toString());
        Integer topicId = Integer.parseInt(map.get("topicId").toString());
        Integer limit = Integer.parseInt(map.get("limit").toString());
        List<Topic> topics = topicService.selectAuthorOtherTopic(userId, topicId, limit);

        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_28);
        environment.setVariable("topics", builder.build().wrap(topics));
        templateDirectiveBody.render(environment.getOut());
    }
}


text:
<?php

namespace Lam\MdlBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Lam\MdlBundle\Entity\Formation
 *
 * @ORM\Table(name="formation")
 * @ORM\Entity(repositoryClass="Lam\MdlBundle\Entity\FormationRepository")
 */
class Formation
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var date $date
     *
     * @ORM\Column(name="Date", type="date", nullable=false)
     */
    private $date;

    /**
     * @var string $horaire
     *
     * @ORM\Column(name="Horaire", type="string", length=30, nullable=false)
     */
    private $horaire;

    /**
     * @var string $salle
     *
     * @ORM\Column(name="Salle", type="string", length=30, nullable=false)
     */
    private $salle;

    /**
     * @var string $adresse
     *
     * @ORM\Column(name="Adresse", type="string", length=150, nullable=false)
     */
    private $adresse;

    /**
     * @var string $cout
     *
     * @ORM\Column(name="Cout", type="string", length=100, nullable=false)
     */
    private $cout;

    /**
     * @var string $repas
     *
     * @ORM\Column(name="Repas", type="string", length=100, nullable=false)
     */
    private $repas;

    /**
     * @var date $datelimite
     *
     * @ORM\Column(name="DateLimite", type="date", nullable=false)
     */
    private $datelimite;

    /**
     * @var integer $nbinscrit
     *
     * @ORM\Column(name="nbInscrit", type="integer", nullable=false)
     */
    private $nbinscrit;

    /**
     * @var Intervenant
     *
     * @ORM\ManyToMany(targetEntity="Intervenant", inversedBy="formation")
     * @ORM\JoinTable(name="formation_intervenant",
     *   joinColumns={
     *     @ORM\JoinColumn(name="formation_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="intervenant_id", referencedColumnName="id")
     *   }
     * )
     */
    private $intervenant;

    /**
     * @var Formationinformatique
     *
     * @ORM\ManyToOne(targetEntity="Formationinformatique")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="laFormationInformatique_id", referencedColumnName="id")
     * })
     */
    private $laformationinformatique;

    /**
     * @var Formationsport
     *
     * @ORM\ManyToOne(targetEntity="Formationsport")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="laFormationSport_id", referencedColumnName="id")
     * })
     */
    private $laformationsport;

    public function __construct()
    {
        $this->intervenant = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set date
     *
     * @param date $date
     */
    public function setDate($date)
    {
        $this->date = $date;
    }

    /**
     * Get date
     *
     * @return date
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * Set horaire
     *
     * @param string $horaire
     */
    public function setHoraire($horaire)
    {
        $this->horaire = $horaire;
    }

    /**
     * Get horaire
     *
     * @return string
     */
    public function getHoraire()
    {
        return $this->horaire;
    }

    /**
     * Set salle
     *
     * @param string $salle
     */
    public function setSalle($salle)
    {
        $this->salle = $salle;
    }

    /**
     * Get salle
     *
     * @return string
     */
    public function getSalle()
    {
        return $this->salle;
    }

    /**
     * Set adresse
     *
     * @param string $adresse
     */
    public function setAdresse($adresse)
    {
        $this->adresse = $adresse;
    }

    /**
     * Get adresse
     *
     * @return string
     */
    public function getAdresse()
    {
        return $this->adresse;
    }

    /**
     * Set cout
     *
     * @param string $cout
     */
    public function setCout($cout)
    {
        $this->cout = $cout;
    }

    /**
     * Get cout
     *
     * @return string
     */
    public function getCout()
    {
        return $this->cout;
    }

    /**
     * Set repas
     *
     * @param string $repas
     */
    public function setRepas($repas)
    {
        $this->repas = $repas;
    }

    /**
     * Get repas
     *
     * @return string
     */
    public function getRepas()
    {
        return $this->repas;
    }

    /**
     * Set datelimite
     *
     * @param date $datelimite
     */
    public function setDatelimite($datelimite)
    {
        $this->datelimite = $datelimite;
    }

    /**
     * Get datelimite
     *
     * @return date
     */
    public function getDatelimite()
    {
        return $this->datelimite;
    }

    /**
     * Set nbinscrit
     *
     * @param integer $nbinscrit
     */
    public function setNbinscrit($nbinscrit)
    {
        $this->nbinscrit = $nbinscrit;
    }

    /**
     * Get nbinscrit
     *
     * @return integer
     */
    public function getNbinscrit()
    {
        return $this->nbinscrit;
    }

    /**
     * Add intervenant
     *
     * @param Lam\MdlBundle\Entity\Intervenant $intervenant
     */
    public function addIntervenant(\Lam\MdlBundle\Entity\Intervenant $intervenant)
    {
        $this->intervenant[] = $intervenant;
    }

    /**
     * Get intervenant
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getIntervenant()
    {
        return $this->intervenant;
    }

    /**
     * Set laformationinformatique
     *
     * @param Lam\MdlBundle\Entity\Formationinformatique $laformationinformatique
     */
    public function setLaformationinformatique(\Lam\MdlBundle\Entity\Formationinformatique $laformationinformatique)
    {
        $this->laformationinformatique = $laformationinformatique;
    }

    /**
     * Get laformationinformatique
     *
     * @return Lam\MdlBundle\Entity\Formationinformatique
     */
    public function getLaformationinformatique()
    {
        return $this->laformationinformatique;
    }

    /**
     * Set laformationsport
     *
     * @param Lam\MdlBundle\Entity\Formationsport $laformationsport
     */
    public function setLaformationsport(\Lam\MdlBundle\Entity\Formationsport $laformationsport)
    {
        $this->laformationsport = $laformationsport;
    }

    /**
     * Get laformationsport
     *
     * @return Lam\MdlBundle\Entity\Formationsport
     */
    public function getLaformationsport()
    {
        return $this->laformationsport;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<section xmlns="http://docbook.org/ns/docbook"
    xmlns:xi="http://www.w3.org/2001/XInclude"
    xmlns:xlink="http://www.w3.org/1999/xlink" version="5.0"
    xml:id="kvm">
    <?dbhtml stop-chunking?>
    <title>KVM</title>
<para>KVM is configured as the default hypervisor for Compute. To enable KVM explicitly, add the
        following configuration options
        <filename>/etc/nova/nova.conf</filename>:<programlisting>connection_type=libvirt
libvirt_type=kvm</programlisting>
        The KVM hypervisor supports the following virtual machine image formats:<itemizedlist>
            <listitem>
                <para>Raw</para>
            </listitem>
            <listitem>
                <para>QEMU Copy-on-write (qcow2)</para>
            </listitem>
            <listitem>
                <para>VMWare virtual machine disk format (vmdk)</para>
            </listitem>
        </itemizedlist></para>
    <para>The rest of this section describes how to enable KVM on your system. You may also wish to
        consult distribution-specific documentation:<itemizedlist>
            <listitem>
                <para><link
                        xlink:href="http://fedoraproject.org/wiki/Getting_started_with_virtualization"
                        >Fedora: Getting started with virtualization</link> from the Fedora project
                    wiki.</para>
            </listitem>
            <listitem>
                <para><link xlink:href="https://help.ubuntu.com/community/KVM/Installation">Ubuntu:
                        KVM/Installation</link> from the Community Ubuntu documentation.</para>
            </listitem>
            <listitem>
                <para><link
                        xlink:href="http://static.debian-handbook.info/browse/stable/sect.virtualization.html#idp11279352"
                        >Debian: Virtualization with KVM</link> from the Debian handbook.</para>
            </listitem>
            <listitem>
                <para><link
                        xlink:href="http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Virtualization_Host_Configuration_and_Guest_Installation_Guide/sect-Virtualization_Host_Configuration_and_Guest_Installation_Guide-Host_Installation-Installing_KVM_packages_on_an_existing_Red_Hat_Enterprise_Linux_system.html"
                        >RHEL: Installing virtualization packages on an existing Red Hat Enterprise
                        Linux system</link> from the Red Hat Enterprise Linux Virtualizaiton Host
                    Configuration and Guest Installation Guide.</para>
            </listitem>
            <listitem>
                <para><link
                        xlink:href="http://doc.opensuse.org/documentation/html/openSUSE/opensuse-kvm/cha.kvm.requires.html#sec.kvm.requires.install"
                        >openSUSE: Installing KVM</link> from the openSUSE Virtualization with KVM
                    manual.</para>
            </listitem>
            <listitem>
                <para><link
                        xlink:href="http://doc.opensuse.org/products/draft/SLES/SLES-kvm_sd_draft/cha.kvm.requires.html#sec.kvm.requires.install"
                        >SLES: Installing KVM</link> from the SUSE Linux Enterprise
                    ServerVirtualization with KVM manual.</para>
            </listitem>
        </itemizedlist></para>
    <section xml:id="checking-kvm">
        <title>Checking for hardware virtualization support</title>
        <para>The processors of your compute host need to support virtualization technology (VT) to
            use KVM. </para>
        <para>If you are running on Ubuntu, use the <command>kvm-ok</command> command to check if
            your processor has VT support, it is enabled in the BIOS, and KVM is installed properly,
            as root:<screen><prompt>#</prompt> <userinput>kvm-ok</userinput></screen></para>
        <para>If KVM is enabled, the output should look something
            like:<screen><computeroutput>INFO: /dev/kvm exists
KVM acceleration can be used</computeroutput></screen></para>
        <para>If KVM is not enabled, the output should look something
            like:<screen><computeroutput>INFO: Your CPU does not support KVM extensions
KVM acceleration can NOT be used</computeroutput></screen></para>
        <para>In the case that KVM acceleration is not supported, Compute should be configured to
            use a different hypervisor, such as <link linkend="qemu">QEMU</link> or <link
                linkend="introduction-to-xen">Xen</link>.</para>
        <para>On distributions that don't have <command>kvm-ok</command>, you can check if your
            processor has VT support by looking at the processor flags in the
                <filename>/proc/cpuinfo</filename> file. For Intel processors, look for the
                <literal>vmx</literal> flag, and for AMD processors, look for the
                <literal>svm</literal> flag. A simple way to check is to run the following command
            and see if there is any
            output:<screen><prompt>$</prompt> <userinput>egrep '(vmx|svm)' --color=always /proc/cpuinfo</userinput></screen></para>
        <para>Some systems require that you enable VT support in the system BIOS. If you believe
            your processor supports hardware acceleration but the above command produced no output,
            you may need to reboot your machine, enter the system BIOS, and enable the VT
            option.</para>
    </section>

    <section xml:id="enabling-kvm">
        <title>Enabling KVM</title>
        <para>KVM requires the <literal>kvm </literal>and either <literal>kvm-intel</literal> or
                <literal>kvm-amd</literal> modules to be loaded. This may have been configured
            automatically on your distribution when KVM is installed. </para>
        <para>You can check that they have been loaded using <command>lsmod</command>, as follows,
            with expected output for Intel-based
            processors:<screen><prompt>$</prompt> <userinput>lsmod | grep kvm</userinput>
<computeroutput>kvm_intel             137721  9
kvm                   415459  1 kvm_intel</computeroutput></screen>The
            following sections describe how to load the kernel modules for Intel-based and AMD-based
            processors if they were not loaded automatically by your distribution's KVM installation
            process.</para>

        <section xml:id="kvm-intel">
            <title>Intel-based processors</title>
        <para>If your compute host is Intel-based, run the following as root to load the kernel
                modules:<screen><prompt>#</prompt> modprobe kvm
<prompt>#</prompt> modprobe kvm-intel</screen>
                Add the following lines to <filename>/etc/modules</filename> so that these modules
                will load on reboot:<programlisting>kvm
kvm-intel</programlisting></para>
</section>
        <section xml:id="kvm-amd">
            <title>AMD-based processors</title>
            <para>If your compute host is AMD-based, run the following as root to load the kernel
                modules:<screen><prompt>#</prompt> modprobe kvm
<prompt>#</prompt> modprobe kvm-amd</screen>
                Add the following lines to <filename>/etc/modules</filename> so that these modules
                will load on reboot:<programlisting>kvm
kvm-amd</programlisting></para>
           </section>
    </section>
    <section xml:id="xml-troubleshooting">
        <title>Troubleshooting</title>
        <para>Trying to launch a new virtual machine instance fails with the
                <literal>ERROR</literal> state, and the following error appears in
                <filename>/var/log/nova/nova-compute.log</filename><screen><computeroutput>libvirtError: internal error no supported architecture for os type 'hvm'</computeroutput></screen>
            This is a symptom that the KVM kernel modules have not been loaded.</para>
    </section>
</section>


text:
var express         = require('express');
var path            = require('path');
var favicon         = require('static-favicon');
var logger          = require('morgan');
var cookieParser    = require('cookie-parser');
var bodyParser      = require('body-parser');
var multer          = require('multer');
var env             = process.env.NODE_ENV || 'development';

var routes = require('./routes/index');
var bookshelf = require('./db').bookshelf;
var app = express();

app.set('bookshelf',bookshelf);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.enable('trust proxy');

app.disable('x-powered-by');

app.use(favicon());

if (env === 'development') {
app.use(logger('dev'))
} else {
app.use(logger())
};

app.use(function(req, res, next) {
  var contentType = req.headers['content-type'] || ''
    , mime = contentType.split(';')[0];

  if (mime != '') {
    return next();
  }

  var data = '';
  req.setEncoding('utf8');
  req.on('data', function(chunk) {
    data += chunk;
  });
  req.on('end', function() {
    req.rawBody = data;
    next();
  });
});

app.use(multer());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;


text:
<?xml version="1.0"?>
<ruleset name="Ilios App">
 <description>Use PSR2, exclude some directories</description>
 <rule ref="PSR2"/>
</ruleset>


text:
using base::StringPiece;

namespace content {

TEST(CrossSiteDocumentClassifierTest, IsBlockableScheme) {
  GURL data_url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA==");
  GURL ftp_url("ftp://google.com");
  GURL mailto_url("mailto:google@google.com");
  GURL about_url("about:chrome");
  GURL http_url("http://google.com");
  GURL https_url("https://google.com");

  EXPECT_FALSE(CrossSiteDocumentClassifier::IsBlockableScheme(data_url));
  EXPECT_FALSE(CrossSiteDocumentClassifier::IsBlockableScheme(ftp_url));
  EXPECT_FALSE(CrossSiteDocumentClassifier::IsBlockableScheme(mailto_url));
  EXPECT_FALSE(CrossSiteDocumentClassifier::IsBlockableScheme(about_url));
  EXPECT_TRUE(CrossSiteDocumentClassifier::IsBlockableScheme(http_url));
  EXPECT_TRUE(CrossSiteDocumentClassifier::IsBlockableScheme(https_url));
}

TEST(CrossSiteDocumentClassifierTest, IsSameSite) {
  GURL a_com_url0("https://mock1.a.com:8080/page1.html");
  GURL a_com_url1("https://mock2.a.com:9090/page2.html");
  GURL a_com_url2("https://a.com/page3.html");
  url::Origin a_com_origin0(a_com_url0);
  EXPECT_TRUE(
      CrossSiteDocumentClassifier::IsSameSite(a_com_origin0, a_com_url1));
  EXPECT_TRUE(CrossSiteDocumentClassifier::IsSameSite(url::Origin(a_com_url1),
                                                      a_com_url2));
  EXPECT_TRUE(CrossSiteDocumentClassifier::IsSameSite(url::Origin(a_com_url2),
                                                      a_com_url0));

  GURL b_com_url0("https://mock1.b.com/index.html");
  EXPECT_FALSE(
      CrossSiteDocumentClassifier::IsSameSite(a_com_origin0, b_com_url0));

  GURL about_blank_url("about:blank");
  EXPECT_FALSE(
      CrossSiteDocumentClassifier::IsSameSite(a_com_origin0, about_blank_url));

  GURL chrome_url("chrome://extension");
  EXPECT_FALSE(
      CrossSiteDocumentClassifier::IsSameSite(a_com_origin0, chrome_url));

  GURL empty_url("");
  EXPECT_FALSE(
      CrossSiteDocumentClassifier::IsSameSite(a_com_origin0, empty_url));
}

TEST(CrossSiteDocumentClassifierTest, IsValidCorsHeaderSet) {
  url::Origin frame_origin(GURL("http://www.google.com"));
  GURL site_origin_url("http://www.yahoo.com");

  EXPECT_TRUE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
      frame_origin, site_origin_url, "*"));
  EXPECT_FALSE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
      frame_origin, site_origin_url, "\"*\""));
  EXPECT_TRUE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
      frame_origin, site_origin_url, "http://mail.google.com"));
  EXPECT_FALSE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
      frame_origin, site_origin_url, "https://mail.google.com"));
  EXPECT_FALSE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
      frame_origin, site_origin_url, "http://yahoo.com"));
  EXPECT_FALSE(CrossSiteDocumentClassifier::IsValidCorsHeaderSet(
      frame_origin, site_origin_url, "www.google.com"));
}

TEST(CrossSiteDocumentClassifierTest, SniffForHTML) {
  StringPiece html_data("  \t\r\n    <HtMladfokadfkado");
  StringPiece comment_html_data(" <!-- this is comment --> <html><body>");
  StringPiece two_comments_html_data(
      "<!-- this is comment -->\n<!-- this is comment --><html><body>");
  StringPiece mixed_comments_html_data(
      "<!-- this is comment <!-- --> <script></script>");
  StringPiece non_html_data("        var name=window.location;\nadfadf");
  StringPiece comment_js_data(" <!-- this is comment -> document.write(1); ");
  StringPiece empty_data("");

  EXPECT_TRUE(CrossSiteDocumentClassifier::SniffForHTML(html_data));
  EXPECT_TRUE(CrossSiteDocumentClassifier::SniffForHTML(comment_html_data));
  EXPECT_TRUE(
      CrossSiteDocumentClassifier::SniffForHTML(two_comments_html_data));
  EXPECT_TRUE(
      CrossSiteDocumentClassifier::SniffForHTML(mixed_comments_html_data));
  EXPECT_FALSE(CrossSiteDocumentClassifier::SniffForHTML(non_html_data));
  EXPECT_FALSE(CrossSiteDocumentClassifier::SniffForHTML(comment_js_data));

  // Basic bounds check.
  EXPECT_FALSE(CrossSiteDocumentClassifier::SniffForHTML(empty_data));
}

TEST(CrossSiteDocumentClassifierTest, SniffForXML) {
  StringPiece xml_data("   \t \r \n     <?xml version=\"1.0\"?>\n <catalog");
  StringPiece non_xml_data("        var name=window.location;\nadfadf");
  StringPiece empty_data("");

  EXPECT_TRUE(CrossSiteDocumentClassifier::SniffForXML(xml_data));
  EXPECT_FALSE(CrossSiteDocumentClassifier::SniffForXML(non_xml_data));

  // Basic bounds check.
  EXPECT_FALSE(CrossSiteDocumentClassifier::SniffForXML(empty_data));
}

TEST(CrossSiteDocumentClassifierTest, SniffForJSON) {
  StringPiece json_data("\t\t\r\n   { \"name\" : \"chrome\", ");
  StringPiece non_json_data0("\t\t\r\n   { name : \"chrome\", ");
  StringPiece non_json_data1("\t\t\r\n   foo({ \"name\" : \"chrome\", ");
  StringPiece empty_data("");

  EXPECT_TRUE(CrossSiteDocumentClassifier::SniffForJSON(json_data));
  EXPECT_FALSE(CrossSiteDocumentClassifier::SniffForJSON(non_json_data0));
  EXPECT_FALSE(CrossSiteDocumentClassifier::SniffForJSON(non_json_data1));

  // Basic bounds check.
  EXPECT_FALSE(CrossSiteDocumentClassifier::SniffForJSON(empty_data));
}

}  // namespace content