text:
extern NSString * const PFRACErrorDomain;
extern const NSUInteger PFRACUnknownError;

@interface RACSignal (PFRACErrorHandling)

- (RACSignal *)pfrac_useDefaultErrorDescription:(NSString *)localizedDescription;

@end

redpajama_set_name: RedPajamaGithub


text:
using namespace IECore;
using namespace IECoreScene;

//////////////////////////////////////////////////////////////////////////////////////////
// Cache implementation
//////////////////////////////////////////////////////////////////////////////////////////

namespace
{

typedef IECore::LRUCache< std::string, IECoreScene::ConstSceneInterfacePtr > SceneLRUCache;

class Cache : public SceneLRUCache
{
	public :

		Cache( SceneLRUCache::Cost maxCost )
			: SceneLRUCache( fileCacheGetter, maxCost )
		{
		}

	private :

		static SceneInterfacePtr fileCacheGetter( const std::string &fileName, size_t &cost )
		{
			SceneInterfacePtr result = SceneInterface::create( fileName, IECore::IndexedIO::Read );
			cost = 1;
			return result;
		}
};

Cache &cache()
{
	static Cache *cache = new Cache( 200 );
	return *cache;
}

} // namespace

//////////////////////////////////////////////////////////////////////////////////////////
// SharedSceneInterfaces implementation
//////////////////////////////////////////////////////////////////////////////////////////

ConstSceneInterfacePtr SharedSceneInterfaces::get( const std::string &fileName )
{
	return cache().get( fileName );
}

void SharedSceneInterfaces::erase( const std::string &fileName )
{
	cache().erase( fileName );
}

void SharedSceneInterfaces::clear()
{
	cache().clear();
}

void SharedSceneInterfaces::setMaxScenes( size_t numScenes )
{
	cache().setMaxCost( numScenes );
}

size_t SharedSceneInterfaces::getMaxScenes()
{
	return cache().getMaxCost();
}

size_t SharedSceneInterfaces::numScenes()
{
	return cache().currentCost();
}


text:
use std::num::ParseIntError;

// This is a custom error type that we will be using in `parse_pos_nonzero()`.
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
    Creation(CreationError),
    ParseInt(ParseIntError)
}

impl ParsePosNonzeroError {
    fn from_creation(err: CreationError) -> ParsePosNonzeroError {
        ParsePosNonzeroError::Creation(err)
    }
    // TODO: add another error conversion function here.
}

fn parse_pos_nonzero(s: &str)
    -> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{
    // TODO: change this to return an appropriate error instead of panicking
    // when `parse()` returns an error.
    let x: i64 = s.parse().unwrap();
    PositiveNonzeroInteger::new(x)
        .map_err(ParsePosNonzeroError::from_creation)
}

// Don't change anything below this line.

#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);

#[derive(PartialEq, Debug)]
enum CreationError {
    Negative,
    Zero,
}

impl PositiveNonzeroInteger {
    fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
        match value {
            x if x < 0 => Err(CreationError::Negative),
            x if x == 0 => Err(CreationError::Zero),
            x => Ok(PositiveNonzeroInteger(x as u64))
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_parse_error() {
        // We can't construct a ParseIntError, so we have to pattern match.
        assert!(matches!(
            parse_pos_nonzero("not a number"),
            Err(ParsePosNonzeroError::ParseInt(_))
        ));
    }

    #[test]
    fn test_negative() {
        assert_eq!(
            parse_pos_nonzero("-555"),
            Err(ParsePosNonzeroError::Creation(CreationError::Negative))
        );
    }

    #[test]
    fn test_zero() {
        assert_eq!(
            parse_pos_nonzero("0"),
            Err(ParsePosNonzeroError::Creation(CreationError::Zero))
        );
    }

    #[test]
    fn test_positive() {
        let x = PositiveNonzeroInteger::new(42);
        assert!(x.is_ok());
        assert_eq!(parse_pos_nonzero("42"), Ok(x.unwrap()));
    }
}


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

namespace Larium\FormBuilder\Elements;

use Larium\FormBuilder\Element;

class Input extends Element
{
    protected $type;

    protected $file = 'input';

    public function __construct($type='submit', $name, $value, $attrs = array())
    {
        $this->type = $type;
        $this->name = $name;
        $this->value = $value;
        $attrs['type'] = $type;
        $this->attrs = $attrs;
    }

    public function getType()
    {
        return $this->type;
    }
}


text:
'use strict';

test(() => {

  const theError = new Error('a unique string');

  assert_throws_exactly(theError, () => {
    new ReadableStream({}, {
      get size() {
        throw theError;
      },
      highWaterMark: 5
    });
  }, 'construction should re-throw the error');

}, 'Readable stream: throwing strategy.size getter');

promise_test(t => {

  const controllerError = { name: 'controller error' };
  const thrownError = { name: 'thrown error' };

  let controller;
  const rs = new ReadableStream(
    {
      start(c) {
        controller = c;
      }
    },
    {
      size() {
        controller.error(controllerError);
        throw thrownError;
      },
      highWaterMark: 5
    }
  );

  assert_throws_exactly(thrownError, () => controller.enqueue('a'), 'enqueue should re-throw the error');

  return promise_rejects_exactly(t, controllerError, rs.getReader().closed);

}, 'Readable stream: strategy.size errors the stream and then throws');

promise_test(t => {

  const theError = { name: 'my error' };

  let controller;
  const rs = new ReadableStream(
    {
      start(c) {
        controller = c;
      }
    },
    {
      size() {
        controller.error(theError);
        return Infinity;
      },
      highWaterMark: 5
    }
  );

  assert_throws_js(RangeError, () => controller.enqueue('a'), 'enqueue should throw a RangeError');

  return promise_rejects_exactly(t, theError, rs.getReader().closed, 'closed should reject with the error');

}, 'Readable stream: strategy.size errors the stream and then returns Infinity');

promise_test(() => {

  const theError = new Error('a unique string');
  const rs = new ReadableStream(
    {
      start(c) {
        assert_throws_exactly(theError, () => c.enqueue('a'), 'enqueue should throw the error');
      }
    },
    {
      size() {
        throw theError;
      },
      highWaterMark: 5
    }
  );

  return rs.getReader().closed.catch(e => {
    assert_equals(e, theError, 'closed should reject with the error');
  });

}, 'Readable stream: throwing strategy.size method');

test(() => {

  const theError = new Error('a unique string');

  assert_throws_exactly(theError, () => {
    new ReadableStream({}, {
      size() {
        return 1;
      },
      get highWaterMark() {
        throw theError;
      }
    });
  }, 'construction should re-throw the error');

}, 'Readable stream: throwing strategy.highWaterMark getter');

test(() => {

  for (const highWaterMark of [-1, -Infinity, NaN, 'foo', {}]) {
    assert_throws_js(RangeError, () => {
      new ReadableStream({}, {
        size() {
          return 1;
        },
        highWaterMark
      });
    }, 'construction should throw a RangeError for ' + highWaterMark);
  }

}, 'Readable stream: invalid strategy.highWaterMark');

promise_test(() => {

  const promises = [];
  for (const size of [NaN, -Infinity, Infinity, -1]) {
    let theError;
    const rs = new ReadableStream(
      {
        start(c) {
          try {
            c.enqueue('hi');
            assert_unreached('enqueue didn\'t throw');
          } catch (error) {
            assert_equals(error.name, 'RangeError', 'enqueue should throw a RangeError for ' + size);
            theError = error;
          }
        }
      },
      {
        size() {
          return size;
        },
        highWaterMark: 5
      }
    );

    promises.push(rs.getReader().closed.catch(e => {
      assert_equals(e, theError, 'closed should reject with the error for ' + size);
    }));
  }

  return Promise.all(promises);

}, 'Readable stream: invalid strategy.size return value');


text:
"use strict";

const th = require('telehash');
const debug = require('debug')('client');

class Client {
  start() {
    th.load({id: "./.tmp/client." + Date.now() + ".json"}, this.onLoadHandler);
  }

  onLoadHandler(err, mesh) {
    if (err) throw err;
    debug("client uri: ", mesh.uri());

    mesh.discover(true);

    mesh.accept =  /* istanbul ignore next */ function(sender) {
      debug("INCOMING:", sender.hashname);
      var link = mesh.link(sender);

      link.on('status', function(up){
        debug("link status", up);

        // only the echo server has a mesh.stream handler, so all client discoveries will drop
        let chan = link.stream();
        chan.write("Hello?");
        let i = 0;

        setInterval(function () {
          chan.write(mesh.hashname.substr(0,8) + ": Test #" + (++i));
        }, 5e3);

        chan.on('data', function (data) {
          debug("DATA:", data.toString());
        });
      })
    };
  }
}

module.exports = Client;


text:
/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, 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.

// Internal Includes
#include <osvr/ClientKit/ContextC.h>
#include <osvr/ClientKit/InterfaceC.h>
#include <osvr/ClientKit/InterfaceCallbackC.h>
#include <osvr/ClientKit/InterfaceStateC.h>
#include <osvr/ClientKit/SkeletonC.h>

// Library/third-party includes

// Standard includes
#include <stdio.h>

#define NAME_BUFFER_SIZE 10000
#define MAX_CALLBACKS_TO_REPORT 10

static int numCallbacks = 0;

void mySkeletonCallback(void *userdata, const OSVR_TimeValue *timestamp,
                        const OSVR_SkeletonReport *report) {
    numCallbacks++;

    OSVR_ReturnCode rc;

    OSVR_Skeleton skel = report->state.skeleton;
    printf("-----------\n");
    printf("\tGot report: channel is %d, timestamp: %d:%d\n", report->sensor,
           timestamp->seconds, timestamp->microseconds);

    OSVR_SkeletonJointCount numJoints = 0;
    rc = osvrClientGetSkeletonNumJoints(skel, &numJoints);
    if (rc == OSVR_RETURN_FAILURE) {
        printf("\tcall to osvrClientGetSkeletonNumJoints failed\n");
    }

    OSVR_SkeletonBoneCount numBones = 0;
    rc = osvrClientGetSkeletonNumBones(skel, &numBones);
    if (rc == OSVR_RETURN_FAILURE) {
        printf("\tcall to osvrClientGetSkeletonNumJoints failed\n");
    }

    printf("\tnumJoints: %d, numBones: %d\n", numJoints, numBones);

    OSVR_SkeletonJointCount joint;
    for (joint = 0; joint < numJoints; joint++) {
        uint32_t len = 0;
        OSVR_SkeletonJointCount jointId = 0;
        rc = osvrClientGetSkeletonAvailableJointId(skel, joint, &jointId);
        if (rc == OSVR_RETURN_FAILURE) {
            printf("\tcouldn't get the joint id for joint index %d\n", joint);
            return;
        }

        rc = osvrClientGetSkeletonStringJointNameLength(skel, jointId, &len);
        if (rc == OSVR_RETURN_FAILURE) {
            printf("\tjoint %d: call to "
                   "osvrClientGetSkeletonStringJointNameLength failed",
                   joint);
            return;
        }

        char jointName[NAME_BUFFER_SIZE];
        rc = osvrClientGetSkeletonJointName(skel, jointId, jointName,
                                            NAME_BUFFER_SIZE);
        if (rc == OSVR_RETURN_FAILURE) {
            printf("\tjoint %d: osvrClientGetSkeletonJointName call "
                   "failed. Perhaps the joint name is greater than our "
                   "buffer size?\n",
                   joint);
            return;
        }

        OSVR_SkeletonJointState jointState = {0};
        rc = osvrClientGetSkeletonJointState(skel, jointId, &jointState);
        if (rc == OSVR_RETURN_FAILURE) {
            printf("\tjoint %d: osvrClientGetSkeletonJointState call "
                   "failed.\n",
                   joint);
            return;
        }

        printf("\tjoint %d: name: %s,\n\t\ttranslation: (x: %f, y: %f, z: "
               "%f)\n\t\torientation: (x: %f, y: %f, z: %f, w: %f)\n",
               joint, jointName, osvrVec3GetX(&jointState.pose.translation),
               osvrVec3GetY(&jointState.pose.translation),
               osvrVec3GetZ(&jointState.pose.translation),
               osvrQuatGetX(&jointState.pose.rotation),
               osvrQuatGetY(&jointState.pose.rotation),
               osvrQuatGetZ(&jointState.pose.rotation),
               osvrQuatGetW(&jointState.pose.rotation));
    }

    OSVR_SkeletonBoneCount bone;
    for (bone = 0; bone < numBones; bone++) {
        uint32_t len = 0;
        OSVR_SkeletonBoneCount boneId = 0;
        rc = osvrClientGetSkeletonAvailableBoneId(skel, bone, &boneId);
        if (rc == OSVR_RETURN_FAILURE) {
            printf("\tcouldn't get the bone id for bone index %d\n", bone);
            return;
        }

        rc = osvrClientGetSkeletonStringBoneNameLength(skel, boneId, &len);
        if (rc == OSVR_RETURN_FAILURE) {
            printf("\tbone %d: call to "
                   "osvrClientGetSkeletonStringBoneNameLength failed",
                   bone);
            continue;
        }

        char boneName[NAME_BUFFER_SIZE];
        rc = osvrClientGetSkeletonBoneName(skel, boneId, boneName,
                                           NAME_BUFFER_SIZE);
        if (rc == OSVR_RETURN_FAILURE) {
            printf("\tbone %d: osvrClientGetSkeletonBoneName call failed. "
                   "Perhaps the bone name is greater than our buffer "
                   "size?\n",
                   bone);
            return;
        }

        OSVR_SkeletonBoneState boneState = {0};
        rc = osvrClientGetSkeletonBoneState(skel, boneId, &boneState);
        if (rc == OSVR_RETURN_FAILURE) {
            printf("\tbone %d: osvrClientGetSkeletonBoneState call failed.\n",
                   bone);
            return;
        }

        printf("\tbone %d: name: %s,\n\t\ttranslation: (x: %f, y: %f, z: "
               "%f)\n\t\torientation: (x: %f, y: %f, z: %f, w: %f)\n",
               bone, boneName, osvrVec3GetX(&boneState.pose.translation),
               osvrVec3GetY(&boneState.pose.translation),
               osvrVec3GetZ(&boneState.pose.translation),
               osvrQuatGetX(&boneState.pose.rotation),
               osvrQuatGetY(&boneState.pose.rotation),
               osvrQuatGetZ(&boneState.pose.rotation),
               osvrQuatGetW(&boneState.pose.rotation));
    }

    OSVR_SkeletonJointCount leftWristJointId = 0;
    rc = osvrClientGetSkeletonJointId(skel, "l_wrist", &leftWristJointId);
    printf("\tasking for 'l_wrist' joint id by name: %s, jointId = %d\n",
           rc == OSVR_RETURN_SUCCESS ? "suceeded" : "failed", leftWristJointId);
}

#define CHECK_RC(rc)                                                           \
    if (rc == OSVR_RETURN_FAILURE) {                                           \
        printf("OSVR call failed");                                            \
        if (ctx) {                                                             \
            osvrClientShutdown(ctx);                                           \
        }                                                                      \
        return -1;                                                             \
    }

int main() {
    OSVR_ReturnCode rc;
    OSVR_ClientContext ctx =
        osvrClientInit("com.osvr.exampleclients.SkeletonCallback", 0);

    OSVR_ClientInterface leftHand = NULL;
    OSVR_ClientInterface rightHand = NULL;
#if 0
    OSVR_Skeleton skel = NULL;
#endif
    rc = osvrClientGetInterface(
        ctx, "/com_osvr_example_Skeleton/Skeleton/skeleton/0", &leftHand);
    CHECK_RC(rc);

    rc = osvrClientGetInterface(
        ctx, "/com_osvr_example_Skeleton/Skeleton/skeleton/1", &rightHand);
    CHECK_RC(rc);

    rc = osvrRegisterSkeletonCallback(leftHand, mySkeletonCallback, NULL);
    CHECK_RC(rc);
    rc = osvrRegisterSkeletonCallback(rightHand, mySkeletonCallback, NULL);
    CHECK_RC(rc);

    // Pretend that this is your application's mainloop.
    while (numCallbacks < MAX_CALLBACKS_TO_REPORT) {
        rc = osvrClientUpdate(ctx);
        CHECK_RC(rc);
    }

    osvrClientShutdown(ctx);
    printf("Library shut down, exiting.\n");
    return 0;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>mpx-spring2017-npennf: page_dir Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

mpx-spring2017-npennf
    NPE-NPX.R6.04282017

An Operating System Project

Main Page

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Data Fields

Data Fields

page_dir Struct Reference

#include <paging.h>

Collaboration diagram for page_dir:

<map name="page__dir_coll__map" id="page__dir_coll__map">
<area shape="rect" id="node2" href="structpage__table.html" title="page_table" alt="" coords="6,95,91,121"/>
<area shape="rect" id="node3" href="structpage__entry.html" title="page_entry" alt="" coords="5,5,92,32"/>
</map>
[legend]

Data Fields

page_table * 	tables [1024]

u32int 	tables_phys [1024]

Detailed Description

Page directory structure Limited to 1024 tables for now

Field Documentation

          page_table* tables[1024]

          u32int tables_phys[1024]

The documentation for this struct was generated from the following file:

include/mem/paging.h

<address class="footer">
Generated by

 1.8.11
</address>


text:
var assert = require("assert"),
    vows = require("vows"),
    databank = require("databank"),
    URLMaker = require("../lib/urlmaker").URLMaker,
    modelBatch = require("./lib/model").modelBatch,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var suite = vows.describe("audio module interface");

var testSchema = {
    pkey: "id",
    fields: ["author",
             "displayName",
             "embedCode",
             "published",
             "stream",
             "summary",
             "updated"]
};

var testData = {
    "create": {
        displayName: "Shake Your Rump",
        url: "http://example.com/beastie-boys/pauls-boutique/2",
        stream: {
            url: "http://example.com/beastie-boys/pauls-boutique/shake-your-rump.ogg",
            duration: 388
        }
    },
    "update": {
        displayName: "Shake Your Rump (Extended Mix)"
    }
};

suite.addBatch(modelBatch("audio", "Audio", testSchema, testData));

suite["export"](module);


text:
package org.apache.calcite.sql;

import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.SqlOperandTypeChecker;
import org.apache.calcite.sql.type.SqlOperandTypeInference;
import org.apache.calcite.sql.type.SqlReturnTypeInference;
import org.apache.calcite.sql.util.SqlBasicVisitor;
import org.apache.calcite.sql.util.SqlVisitor;
import org.apache.calcite.sql.validate.SqlMonotonicity;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorScope;
import org.apache.calcite.sql.validate.SqlValidatorUtil;
import org.apache.calcite.util.Util;

import java.util.List;

import static org.apache.calcite.util.Static.RESOURCE;

/**
 * A SqlOperator is a type of node in a SQL parse tree (it is NOT a
 * node in a SQL parse tree). It includes functions, operators such as '=', and
 * syntactic constructs such as 'case' statements. Operators may represent
 * query-level expressions (e.g. {@link SqlSelectOperator} or row-level
 * expressions (e.g. {@link org.apache.calcite.sql.fun.SqlBetweenOperator}.
 *
 *
Operators have formal operands, meaning ordered (and optionally
 * named) placeholders for the values they operate on. For example, the division
 * operator takes two operands; the first is the numerator and the second is the
 * denominator. In the context of subclass {@link SqlFunction}, formal operands
 * are referred to as parameters.
 *
 *
When an operator is instantiated via a {@link SqlCall}, it is supplied
 * with actual operands. For example, in the expression 3 /
 * 5, the literal expression 3 is the actual operand
 * corresponding to the numerator, and 5 is the actual operand
 * corresponding to the denominator. In the context of SqlFunction, actual
 * operands are referred to as arguments
 *
 *
In many cases, the formal/actual distinction is clear from context, in
 * which case we drop these qualifiers.
 */
public abstract class SqlOperator {
  //~ Static fields/initializers ---------------------------------------------

  public static final String NL = System.getProperty("line.separator");

  /**
   * Maximum precedence.
   */
  public static final int MDX_PRECEDENCE = 200;

  //~ Instance fields --------------------------------------------------------

  /**
   * The name of the operator/function. Ex. "OVERLAY" or "TRIM"
   */
  private final String name;

  /**
   * See {@link SqlKind}. It's possible to have a name that doesn't match the
   * kind
   */
  public final SqlKind kind;

  /**
   * The precedence with which this operator binds to the expression to the
   * left. This is less than the right precedence if the operator is
   * left-associative.
   */
  private final int leftPrec;

  /**
   * The precedence with which this operator binds to the expression to the
   * right. This is more than the left precedence if the operator is
   * left-associative.
   */
  private final int rightPrec;

  /**
   * used to infer the return type of a call to this operator
   */
  private final SqlReturnTypeInference returnTypeInference;

  /**
   * used to infer types of unknown operands
   */
  private final SqlOperandTypeInference operandTypeInference;

  /**
   * used to validate operand types
   */
  private final SqlOperandTypeChecker operandTypeChecker;

  //~ Constructors -----------------------------------------------------------

  /**
   * Creates an operator.
   */
  protected SqlOperator(
      String name,
      SqlKind kind,
      int leftPrecedence,
      int rightPrecedence,
      SqlReturnTypeInference returnTypeInference,
      SqlOperandTypeInference operandTypeInference,
      SqlOperandTypeChecker operandTypeChecker) {
    assert kind != null;
    this.name = name;
    this.kind = kind;
    this.leftPrec = leftPrecedence;
    this.rightPrec = rightPrecedence;
    this.returnTypeInference = returnTypeInference;
    this.operandTypeInference = operandTypeInference;
    this.operandTypeChecker = operandTypeChecker;
  }

  /**
   * Creates an operator specifying left/right associativity.
   */
  protected SqlOperator(
      String name,
      SqlKind kind,
      int prec,
      boolean leftAssoc,
      SqlReturnTypeInference returnTypeInference,
      SqlOperandTypeInference operandTypeInference,
      SqlOperandTypeChecker operandTypeChecker) {
    this(
        name,
        kind,
        leftPrec(prec, leftAssoc),
        rightPrec(prec, leftAssoc),
        returnTypeInference,
        operandTypeInference,
        operandTypeChecker);
  }

  //~ Methods ----------------------------------------------------------------

  protected static int leftPrec(int prec, boolean leftAssoc) {
    assert (prec % 2) == 0;
    if (!leftAssoc) {
      ++prec;
    }
    return prec;
  }

  protected static int rightPrec(int prec, boolean leftAssoc) {
    assert (prec % 2) == 0;
    if (leftAssoc) {
      ++prec;
    }
    return prec;
  }

  public SqlOperandTypeChecker getOperandTypeChecker() {
    return operandTypeChecker;
  }

  /**
   * Returns a constraint on the number of operands expected by this operator.
   * Subclasses may override this method; when they don't, the range is
   * derived from the {@link SqlOperandTypeChecker} associated with this
   * operator.
   *
   * @return acceptable range
   */
  public SqlOperandCountRange getOperandCountRange() {
    if (operandTypeChecker != null) {
      return operandTypeChecker.getOperandCountRange();
    }

    // If you see this error you need to override this method
    // or give operandTypeChecker a value.
    throw Util.needToImplement(this);
  }

  public String getName() {
    return name;
  }

  public SqlKind getKind() {
    return kind;
  }

  public String toString() {
    return name;
  }

  public int getLeftPrec() {
    return leftPrec;
  }

  public int getRightPrec() {
    return rightPrec;
  }

  /**
   * Returns the syntactic type of this operator, never null.
   */
  public abstract SqlSyntax getSyntax();

  /**
   * Creates a call to this operand with an array of operands.
   *
   *
The position of the resulting call is the union of the
   * pos and the positions of all of the operands.
   *
   * @param functionQualifier function qualifier (e.g. "DISTINCT"), may be
   * @param pos               parser position of the identifier of the call
   * @param operands          array of operands
   */
  public SqlCall createCall(
      SqlLiteral functionQualifier,
      SqlParserPos pos,
      SqlNode... operands) {
    pos = pos.plusAll(operands);
    return new SqlBasicCall(this, operands, pos, false, functionQualifier);
  }

  /**
   * Creates a call to this operand with an array of operands.
   *
   *
The position of the resulting call is the union of the
   * pos and the positions of all of the operands.
   *
   * @param pos      Parser position
   * @param operands List of arguments
   * @return call to this operator
   */
  public final SqlCall createCall(
      SqlParserPos pos,
      SqlNode... operands) {
    return createCall(null, pos, operands);
  }

  /**
   * Creates a call to this operand with a list of operands contained in a
   * {@link SqlNodeList}.
   *
   *
The position of the resulting call inferred from the SqlNodeList.
   *
   * @param nodeList List of arguments
   * @return call to this operator
   */
  public final SqlCall createCall(
      SqlNodeList nodeList) {
    return createCall(
        null,
        nodeList.getParserPosition(),
        nodeList.toArray());
  }

  /**
   * Creates a call to this operand with a list of operands.
   *
   *
The position of the resulting call is the union of the
   * pos and the positions of all of the operands.
   */
  public final SqlCall createCall(
      SqlParserPos pos,
      List<? extends SqlNode> operandList) {
    return createCall(
        null,
        pos,
        operandList.toArray(new SqlNode[operandList.size()]));
  }

  /**
   * Rewrites a call to this operator. Some operators are implemented as
   * trivial rewrites (e.g. NULLIF becomes CASE). However, we don't do this at
   * createCall time because we want to preserve the original SQL syntax as
   * much as possible; instead, we do this before the call is validated (so
   * the trivial operator doesn't need its own implementation of type
   * derivation methods). The default implementation is to just return the
   * original call without any rewrite.
   *
   * @param validator Validator
   * @param call      Call to be rewritten
   * @return rewritten call
   */
  public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
    return call;
  }

  /**
   * Writes a SQL representation of a call to this operator to a writer,
   * including parentheses if the operators on either side are of greater
   * precedence.
   *
   *
The default implementation of this method delegates to
   * {@link SqlSyntax#unparse}.
   */
  public void unparse(
      SqlWriter writer,
      SqlCall call,
      int leftPrec,
      int rightPrec) {
    getSyntax().unparse(writer, this, call, leftPrec, rightPrec);
  }

  // REVIEW jvs 9-June-2006: See http://issues.eigenbase.org/browse/FRG-149
  // for why this method exists.
  protected void unparseListClause(SqlWriter writer, SqlNode clause) {
    unparseListClause(writer, clause, null);
  }

  protected void unparseListClause(
      SqlWriter writer,
      SqlNode clause,
      SqlKind sepKind) {
    if (clause instanceof SqlNodeList) {
      if (sepKind != null) {
        ((SqlNodeList) clause).andOrList(writer, sepKind);
      } else {
        ((SqlNodeList) clause).commaList(writer);
      }
    } else {
      clause.unparse(writer, 0, 0);
    }
  }

  // override Object
  public boolean equals(Object obj) {
    if (!(obj instanceof SqlOperator)) {
      return false;
    }
    if (!obj.getClass().equals(this.getClass())) {
      return false;
    }
    SqlOperator other = (SqlOperator) obj;
    return name.equals(other.name) && kind == other.kind;
  }

  public boolean isName(String testName) {
    return name.equals(testName);
  }

  // override Object
  public int hashCode() {
    return kind.hashCode() + name.hashCode();
  }

  /**
   * Validates a call to this operator.
   *
   *
This method should not perform type-derivation or perform validation
   * related related to types. That is done later, by
   * {@link #deriveType(SqlValidator, SqlValidatorScope, SqlCall)}. This method
   * should focus on structural validation.
   *
   *
A typical implementation of this method first validates the operands,
   * then performs some operator-specific logic. The default implementation
   * just validates the operands.
   *
   *
This method is the default implementation of {@link SqlCall#validate};
   * but note that some sub-classes of {@link SqlCall} never call this method.
   *
   * @param call         the call to this operator
   * @param validator    the active validator
   * @param scope        validator scope
   * @param operandScope validator scope in which to validate operands to this
   *                     call; usually equal to scope, but not always because
   *                     some operators introduce new scopes
   * @see SqlNode#validateExpr(SqlValidator, SqlValidatorScope)
   * @see #deriveType(SqlValidator, SqlValidatorScope, SqlCall)
   */
  public void validateCall(
      SqlCall call,
      SqlValidator validator,
      SqlValidatorScope scope,
      SqlValidatorScope operandScope) {
    assert call.getOperator() == this;
    for (SqlNode operand : call.getOperandList()) {
      operand.validateExpr(validator, operandScope);
    }
  }

  /**
   * Validates the operands of a call, inferring the return type in the
   * process.
   *
   * @param validator active validator
   * @param scope     validation scope
   * @param call      call to be validated
   * @return inferred type
   */
  public final RelDataType validateOperands(
      SqlValidator validator,
      SqlValidatorScope scope,
      SqlCall call) {
    // Let subclasses know what's up.
    preValidateCall(validator, scope, call);

    // Check the number of operands
    checkOperandCount(validator, operandTypeChecker, call);

    SqlCallBinding opBinding = new SqlCallBinding(validator, scope, call);

    checkOperandTypes(
        opBinding,
        true);

    // Now infer the result type.
    RelDataType ret = inferReturnType(opBinding);
    validator.setValidatedNodeType(call, ret);
    return ret;
  }

  /**
   * Receives notification that validation of a call to this operator is
   * beginning. Subclasses can supply custom behavior; default implementation
   * does nothing.
   *
   * @param validator invoking validator
   * @param scope     validation scope
   * @param call      the call being validated
   */
  protected void preValidateCall(
      SqlValidator validator,
      SqlValidatorScope scope,
      SqlCall call) {
  }

  /**
   * Infers the return type of an invocation of this operator; only called
   * after the number and types of operands have already been validated.
   * Subclasses must either override this method or supply an instance of
   * {@link SqlReturnTypeInference} to the constructor.
   *
   * @param opBinding description of invocation (not necessarily a
   * {@link SqlCall})
   * @return inferred return type
   */
  public RelDataType inferReturnType(
      SqlOperatorBinding opBinding) {
    if (returnTypeInference != null) {
      return returnTypeInference.inferReturnType(opBinding);
    }

    // Derived type should have overridden this method, since it didn't
    // supply a type inference rule.
    throw Util.needToImplement(this);
  }

  /**
   * Derives the type of a call to this operator.
   *
   *
This method is an intrinsic part of the validation process so, unlike
   * {@link #inferReturnType}, specific operators would not typically override
   * this method.
   *
   * @param validator Validator
   * @param scope     Scope of validation
   * @param call      Call to this operator
   * @return Type of call
   */
  public RelDataType deriveType(
      SqlValidator validator,
      SqlValidatorScope scope,
      SqlCall call) {
    for (SqlNode operand : call.getOperandList()) {
      RelDataType nodeType = validator.deriveType(scope, operand);
      assert nodeType != null;
    }

    RelDataType type = validateOperands(validator, scope, call);

    // Validate and determine coercibility and resulting collation
    // name of binary operator if needed.
    type = adjustType(validator, call, type);
    SqlValidatorUtil.checkCharsetAndCollateConsistentIfCharType(type);
    return type;
  }

  /**
   * Validates and determines coercibility and resulting collation name of
   * binary operator if needed.
   */
  protected RelDataType adjustType(
      SqlValidator validator,
      final SqlCall call,
      RelDataType type) {
    return type;
  }

  /**
   * Infers the type of a call to this operator with a given set of operand
   * types. Shorthand for {@link #inferReturnType(SqlOperatorBinding)}.
   */
  public final RelDataType inferReturnType(
      RelDataTypeFactory typeFactory,
      List<RelDataType> operandTypes) {
    return inferReturnType(
        new ExplicitOperatorBinding(
            typeFactory,
            this,
            operandTypes));
  }

  /**
   * Checks that the operand values in a {@link SqlCall} to this operator are
   * valid. Subclasses must either override this method or supply an instance
   * of {@link SqlOperandTypeChecker} to the constructor.
   *
   * @param callBinding    description of call
   * @param throwOnFailure whether to throw an exception if check fails
   *                       (otherwise returns false in that case)
   * @return whether check succeeded
   */
  public boolean checkOperandTypes(
      SqlCallBinding callBinding,
      boolean throwOnFailure) {
    // Check that all of the operands are of the right type.
    if (null == operandTypeChecker) {
      // If you see this you must either give operandTypeChecker a value
      // or override this method.
      throw Util.needToImplement(this);
    }

    return operandTypeChecker.checkOperandTypes(
        callBinding,
        throwOnFailure);
  }

  protected void checkOperandCount(
      SqlValidator validator,
      SqlOperandTypeChecker argType,
      SqlCall call) {
    SqlOperandCountRange od = call.getOperator().getOperandCountRange();
    if (od.isValidCount(call.operandCount())) {
      return;
    }
    if (od.getMin() == od.getMax()) {
      throw validator.newValidationError(call,
          RESOURCE.invalidArgCount(call.getOperator().getName(), od.getMin()));
    } else {
      throw validator.newValidationError(call, RESOURCE.wrongNumOfArguments());
    }
  }

  /**
   * Returns whether the given operands are valid. If not valid and
   * {@code fail}, throws an assertion error.
   *
   *
Similar to {@link #checkOperandCount}, but some operators may have
   * different valid operands in {@link SqlNode} and {@code RexNode} formats
   * (some examples are CAST and AND), and this method throws internal errors,
   * not user errors.

   */
  public boolean validRexOperands(int count, boolean fail) {
    return true;
  }

  /**
   * Returns a template describing how the operator signature is to be built.
   * E.g for the binary + operator the template looks like "{1} {0} {2}" {0}
   * is the operator, subsequent numbers are operands.
   *
   * @param operandsCount is used with functions that can take a variable
   *                      number of operands
   * @return signature template, or null to indicate that a default template
   * will suffice
   */
  public String getSignatureTemplate(final int operandsCount) {
    return null;
  }

  /**
   * Returns a string describing the expected operand types of a call, e.g.
   * "SUBSTR(VARCHAR, INTEGER, INTEGER)".
   */
  public final String getAllowedSignatures() {
    return getAllowedSignatures(name);
  }

  /**
   * Returns a string describing the expected operand types of a call, e.g.
   * "SUBSTRING(VARCHAR, INTEGER, INTEGER)" where the name (SUBSTRING in this
   * example) can be replaced by a specified name.
   */
  public String getAllowedSignatures(String opNameToUse) {
    assert operandTypeChecker != null
        : "If you see this, assign operandTypeChecker a value "
        + "or override this function";
    return operandTypeChecker.getAllowedSignatures(this, opNameToUse)
        .trim();
  }

  public SqlOperandTypeInference getOperandTypeInference() {
    return operandTypeInference;
  }

  /**
   * Returns whether this operator is an aggregate function. By default,
   * subclass type is used (an instance of SqlAggFunction is assumed to be an
   * aggregator; anything else is not).
   *
   *
Per SQL:2011, there are <dfn>aggregate functions</dfn> and
   * <dfn>window functions</dfn>.
   * Every aggregate function (e.g. SUM) is also a window function.
   * There are window functions that are not aggregate functions, e.g. RANK,
   * NTILE, LEAD, FIRST_VALUE.

   *
   *
Collectively, aggregate and window functions are called <dfn>analytic
   * functions</dfn>. Despite its name, this method returns true for every
   * analytic function.

   *
   * @see #requiresOrder()
   *
   * @return whether this operator is an analytic function (aggregate function
   * or window function)
   */
  public boolean isAggregator() {
    return false;
  }

  /**
   * Returns whether this is a window function that requires ordering.
   *
   *
Per SQL:2011, 2, 6.10: "If <ntile function>, <lead or lag
   * function>, RANK or DENSE_RANK is specified, then the window ordering
   * clause shall be present."

   *
   * @see #isAggregator()
   */
  public boolean requiresOrder() {
    return false;
  }

  /**
   * Returns whether this is a window function that allows framing (i.e. a
   * ROWS or RANGE clause in the window specification).
   */
  public boolean allowsFraming() {
    return true;
  }

  /**
   * Accepts a {@link SqlVisitor}, visiting each operand of a call. Returns
   * null.
   *
   * @param visitor Visitor
   * @param call    Call to visit
   */
  public <R> R acceptCall(SqlVisitor<R> visitor, SqlCall call) {
    for (SqlNode operand : call.getOperandList()) {
      if (operand == null) {
        continue;
      }
      operand.accept(visitor);
    }
    return null;
  }

  /**
   * Accepts a {@link SqlVisitor}, directing an
   * {@link org.apache.calcite.sql.util.SqlBasicVisitor.ArgHandler}
   * to visit an operand of a call.
   *
   *
The argument handler allows fine control about how the operands are
   * visited, and how the results are combined.
   *
   * @param visitor         Visitor
   * @param call            Call to visit
   * @param onlyExpressions If true, ignores operands which are not
   *                        expressions. For example, in the call to the
   *                        AS operator
   * @param argHandler      Called for each operand
   */
  public <R> void acceptCall(
      SqlVisitor<R> visitor,
      SqlCall call,
      boolean onlyExpressions,
      SqlBasicVisitor.ArgHandler<R> argHandler) {
    List<SqlNode> operands = call.getOperandList();
    for (int i = 0; i < operands.size(); i++) {
      argHandler.visitChild(visitor, call, i, operands.get(i));
    }
  }

  /**
   * @return the return type inference strategy for this operator, or null if
   * return type inference is implemented by a subclass override
   */
  public SqlReturnTypeInference getReturnTypeInference() {
    return returnTypeInference;
  }

  /**
   * Returns whether this operator is monotonic.
   *
   *
Default implementation returns {@link SqlMonotonicity#NOT_MONOTONIC}.
   *
   * @param call  Call to this operator
   * @param scope Scope in which the call occurs
   */
  public SqlMonotonicity getMonotonicity(
      SqlCall call,
      SqlValidatorScope scope) {
    return SqlMonotonicity.NOT_MONOTONIC;
  }

  /**
   * @return true iff a call to this operator is guaranteed to always return
   * the same result given the same operands; true is assumed by default
   */
  public boolean isDeterministic() {
    return true;
  }

  /**
   * @return true iff it is unsafe to cache query plans referencing this
   * operator; false is assumed by default
   */
  public boolean isDynamicFunction() {
    return false;
  }

  /**
   * Method to check if call requires expansion when it has decimal operands.
   * The default implementation is to return true.
   */
  public boolean requiresDecimalExpansion() {
    return true;
  }

  /**
   * Returns whether the ordinalth argument to this operator must
   * be scalar (as opposed to a query).
   *
   *
If true (the default), the validator will attempt to convert the
   * argument into a scalar subquery, which must have one column and return at
   * most one row.
   *
   *
Operators such as SELECT and EXISTS override
   * this method.
   */
  public boolean argumentMustBeScalar(int ordinal) {
    return true;
  }
}

// End SqlOperator.java


text:
require_relative 'binary_trees'
require_relative './../stacks_and_queues/queue/implement_queue'

# Problem: Write a program to find the size of a binary tree

# SOLUTION 1: Depth First Search (DFS)
def size_of_binary_tree_DFS(root)
  return 0 if !root
  return 1 + size_of_binary_tree_DFS(root.left_child) + size_of_binary_tree_DFS(root.right_child)
end

# SOLUTION 2: Breath First Search (BFS)
def size_of_binary_tree_BFS(root)
  return 0 if !root

  count = 0
  queue = Queue.new()
  queue.enqueue(root)
  while !queue.is_empty?
    temporal_node = queue.dequeue
    count += 1
    queue.enqueue(temporal_node.left_child) if temporal_node.left_child
    queue.enqueue(temporal_node.right_child) if temporal_node.right_child
  end
  count
end

# TEST DRIVE
#      1
#    /    \
#   2      3
#  / \    / \
# 4   5  6   7

f = Node.new(7)
e = Node.new(6)
d = Node.new(5)
c = Node.new(4)
b = Node.new(3, e, f)
a = Node.new(2, c, d)
root = Node.new(1, a, b)

puts "Test Drive using the DFS solution"
p size_of_binary_tree_DFS(root) == 7
p size_of_binary_tree_DFS(a) == 3
p size_of_binary_tree_DFS(d) == 1

puts "\nTest Drive using the BFS (level order) solution"
p size_of_binary_tree_BFS(root) == 7
p size_of_binary_tree_BFS(a) == 3
p size_of_binary_tree_BFS(d) == 1


text:
var fix = 0;

function nf_timer_init(server_time) {
    var now = new Date();
    var server = new Date(server_time*1000);
    fix = now.getTime() - server.getTime();
}

function nf_timer(start) {
    now = new Date(new Date() - fix);
    var temp = new Date(start*1000);
    var diff = Math.floor((now.getTime() - temp.getTime())/1000);
    var seconds = diff%60;
    var minutes = Math.floor((diff-seconds)/60)%60;
    var hours = Math.floor((diff-seconds-minutes*60)/3600)%24;
    var days = Math.floor((diff-seconds-minutes*60-hours*3600)/(3600*24));
    if(seconds < 10) seconds = '0'+String(seconds);
    if(minutes < 10) minutes = '0'+String(minutes);
    if(hours < 10) hours = '0'+String(hours);
    var page_nf_timer = document.getElementById('nf_timer');
    page_nf_timer.innerHTML = days+'дн. '+hours+':'+minutes+':'+seconds;
}


text:
'use strict';

/**
 * @ngdoc function
 * @name castApp.controller:ContentCtrl
 * @description
 * # ContentCtrl
 * Controller of the castApp
 */
angular.module('castApp')
	.controller('ContentCtrl', function () {
	});


text:
package routing

import (
	"errors"

	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	key "github.com/ipfs/go-ipfs/blocks/key"
	ci "github.com/ipfs/go-ipfs/p2p/crypto"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
)

// ErrNotFound is returned when a search fails to find anything
var ErrNotFound = errors.New("routing: not found")

// IpfsRouting is the routing module interface
// It is implemented by things like DHTs, etc.
type IpfsRouting interface {
	FindProvidersAsync(context.Context, key.Key, int) <-chan peer.PeerInfo

	// Basic Put/Get

	// PutValue adds value corresponding to given Key.
	PutValue(context.Context, key.Key, []byte) error

	// GetValue searches for the value corresponding to given Key.
	GetValue(context.Context, key.Key) ([]byte, error)

	// Value provider layer of indirection.
	// This is what DSHTs (Coral and MainlineDHT) do to store large values in a DHT.

	// Announce that this node can provide value for given key
	Provide(context.Context, key.Key) error

	// Find specific Peer
	// FindPeer searches for a peer with given ID, returns a peer.PeerInfo
	// with relevant addresses.
	FindPeer(context.Context, peer.ID) (peer.PeerInfo, error)

	// Bootstrap allows callers to hint to the routing system to get into a
	// Boostrapped state
	Bootstrap(context.Context) error

	// TODO expose io.Closer or plain-old Close error
}

type PubKeyFetcher interface {
	GetPublicKey(context.Context, peer.ID) (ci.PubKey, error)
}

// KeyForPublicKey returns the key used to retrieve public keys
// from the dht.
func KeyForPublicKey(id peer.ID) key.Key {
	return key.Key("/pk/" + string(id))
}

func GetPublicKey(r IpfsRouting, ctx context.Context, pkhash []byte) (ci.PubKey, error) {
	if dht, ok := r.(PubKeyFetcher); ok {
		// If we have a DHT as our routing system, use optimized fetcher
		return dht.GetPublicKey(ctx, peer.ID(pkhash))
	} else {
		key := key.Key("/pk/" + string(pkhash))
		pkval, err := r.GetValue(ctx, key)
		if err != nil {
			return nil, err
		}

		// get PublicKey from node.Data
		return ci.UnmarshalPublicKey(pkval)
	}
}


text:
package org.wildfly.swarm.jolokia;

import java.io.File;
import java.net.URL;
import java.util.function.Consumer;
import java.util.function.Supplier;

import org.jboss.shrinkwrap.api.Archive;
import org.wildfly.swarm.jolokia.access.APIJolokiaAccessPreparer;
import org.wildfly.swarm.jolokia.access.FileJolokiaAccessPreparer;
import org.wildfly.swarm.jolokia.access.JolokiaAccess;
import org.wildfly.swarm.jolokia.access.URLJolokiaAccessPreparer;
import org.wildfly.swarm.spi.api.Fraction;

/**
 * @author Bob McWhirter
 */
public class JolokiaFraction implements Fraction<JolokiaFraction> {

    public JolokiaFraction() {
        this("jolokia");
    }

    public JolokiaFraction(String context) {
        this.context = context;
    }

    public JolokiaFraction context(String context) {
        this.context = context;
        return this;
    }

    public String context() {
        return this.context;
    }

    public JolokiaFraction prepareJolokiaWar(Consumer<Archive> jolokiaWarPreparer) {
        this.jolokiaWarPreparer = jolokiaWarPreparer;
        return this;
    }

    public Consumer<Archive> jolokiaWarPreparer() {
        return this.jolokiaWarPreparer;
    }

    public static Consumer<Archive> jolokiaAccessXml(File file) {
        return new FileJolokiaAccessPreparer(file);

    }

    public static Consumer<Archive> jolokiaAccessXml(URL url) {
        return new URLJolokiaAccessPreparer(url);
    }

    public static Consumer<Archive> jolokiaAccess(Consumer<JolokiaAccess> config) {
        JolokiaAccess access = new JolokiaAccess();
        config.accept(access);
        return new APIJolokiaAccessPreparer(access);
    }

    public static Consumer<Archive> jolokiaAccess(Supplier<JolokiaAccess> supplier) {
        return new APIJolokiaAccessPreparer(supplier.get());
    }

    private String context;

    private Consumer<Archive> jolokiaWarPreparer;

}


text:
#include "ctree.h"
#include "disk-io.h"
#include "print-tree.h"

static void print_chunk(struct extent_buffer *eb, struct btrfs_chunk *chunk)
{
	int num_stripes = btrfs_chunk_num_stripes(eb, chunk);
	int i;
	printk(KERN_INFO "\t\tchunk length %llu owner %llu type %llu "
	       "num_stripes %d\n",
	       (unsigned long long)btrfs_chunk_length(eb, chunk),
	       (unsigned long long)btrfs_chunk_owner(eb, chunk),
	       (unsigned long long)btrfs_chunk_type(eb, chunk),
	       num_stripes);
	for (i = 0 ; i < num_stripes ; i++) {
		printk(KERN_INFO "\t\t\tstripe %d devid %llu offset %llu\n", i,
		      (unsigned long long)btrfs_stripe_devid_nr(eb, chunk, i),
		      (unsigned long long)btrfs_stripe_offset_nr(eb, chunk, i));
	}
}
static void print_dev_item(struct extent_buffer *eb,
			   struct btrfs_dev_item *dev_item)
{
	printk(KERN_INFO "\t\tdev item devid %llu "
	       "total_bytes %llu bytes used %llu\n",
	       (unsigned long long)btrfs_device_id(eb, dev_item),
	       (unsigned long long)btrfs_device_total_bytes(eb, dev_item),
	       (unsigned long long)btrfs_device_bytes_used(eb, dev_item));
}
static void print_extent_data_ref(struct extent_buffer *eb,
				  struct btrfs_extent_data_ref *ref)
{
	printk(KERN_INFO "\t\textent data backref root %llu "
	       "objectid %llu offset %llu count %u\n",
	       (unsigned long long)btrfs_extent_data_ref_root(eb, ref),
	       (unsigned long long)btrfs_extent_data_ref_objectid(eb, ref),
	       (unsigned long long)btrfs_extent_data_ref_offset(eb, ref),
	       btrfs_extent_data_ref_count(eb, ref));
}

static void print_extent_item(struct extent_buffer *eb, int slot)
{
	struct btrfs_extent_item *ei;
	struct btrfs_extent_inline_ref *iref;
	struct btrfs_extent_data_ref *dref;
	struct btrfs_shared_data_ref *sref;
	struct btrfs_disk_key key;
	unsigned long end;
	unsigned long ptr;
	int type;
	u32 item_size = btrfs_item_size_nr(eb, slot);
	u64 flags;
	u64 offset;

	if (item_size < sizeof(*ei)) {
#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
		struct btrfs_extent_item_v0 *ei0;
		BUG_ON(item_size != sizeof(*ei0));
		ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
		printk(KERN_INFO "\t\textent refs %u\n",
		       btrfs_extent_refs_v0(eb, ei0));
		return;
#else
		BUG();
#endif
	}

	ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
	flags = btrfs_extent_flags(eb, ei);

	printk(KERN_INFO "\t\textent refs %llu gen %llu flags %llu\n",
	       (unsigned long long)btrfs_extent_refs(eb, ei),
	       (unsigned long long)btrfs_extent_generation(eb, ei),
	       (unsigned long long)flags);

	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
		struct btrfs_tree_block_info *info;
		info = (struct btrfs_tree_block_info *)(ei + 1);
		btrfs_tree_block_key(eb, info, &key);
		printk(KERN_INFO "\t\ttree block key (%llu %x %llu) "
		       "level %d\n",
		       (unsigned long long)btrfs_disk_key_objectid(&key),
		       key.type,
		       (unsigned long long)btrfs_disk_key_offset(&key),
		       btrfs_tree_block_level(eb, info));
		iref = (struct btrfs_extent_inline_ref *)(info + 1);
	} else {
		iref = (struct btrfs_extent_inline_ref *)(ei + 1);
	}

	ptr = (unsigned long)iref;
	end = (unsigned long)ei + item_size;
	while (ptr < end) {
		iref = (struct btrfs_extent_inline_ref *)ptr;
		type = btrfs_extent_inline_ref_type(eb, iref);
		offset = btrfs_extent_inline_ref_offset(eb, iref);
		switch (type) {
		case BTRFS_TREE_BLOCK_REF_KEY:
			printk(KERN_INFO "\t\ttree block backref "
				"root %llu\n", (unsigned long long)offset);
			break;
		case BTRFS_SHARED_BLOCK_REF_KEY:
			printk(KERN_INFO "\t\tshared block backref "
				"parent %llu\n", (unsigned long long)offset);
			break;
		case BTRFS_EXTENT_DATA_REF_KEY:
			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
			print_extent_data_ref(eb, dref);
			break;
		case BTRFS_SHARED_DATA_REF_KEY:
			sref = (struct btrfs_shared_data_ref *)(iref + 1);
			printk(KERN_INFO "\t\tshared data backref "
			       "parent %llu count %u\n",
			       (unsigned long long)offset,
			       btrfs_shared_data_ref_count(eb, sref));
			break;
		default:
			BUG();
		}
		ptr += btrfs_extent_inline_ref_size(type);
	}
	WARN_ON(ptr > end);
}

#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
static void print_extent_ref_v0(struct extent_buffer *eb, int slot)
{
	struct btrfs_extent_ref_v0 *ref0;

	ref0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_ref_v0);
	printk("\t\textent back ref root %llu gen %llu "
		"owner %llu num_refs %lu\n",
		(unsigned long long)btrfs_ref_root_v0(eb, ref0),
		(unsigned long long)btrfs_ref_generation_v0(eb, ref0),
		(unsigned long long)btrfs_ref_objectid_v0(eb, ref0),
		(unsigned long)btrfs_ref_count_v0(eb, ref0));
}
#endif

void btrfs_print_leaf(struct btrfs_root *root, struct extent_buffer *l)
{
	int i;
	u32 type, nr;
	struct btrfs_item *item;
	struct btrfs_root_item *ri;
	struct btrfs_dir_item *di;
	struct btrfs_inode_item *ii;
	struct btrfs_block_group_item *bi;
	struct btrfs_file_extent_item *fi;
	struct btrfs_extent_data_ref *dref;
	struct btrfs_shared_data_ref *sref;
	struct btrfs_dev_extent *dev_extent;
	struct btrfs_key key;
	struct btrfs_key found_key;

	if (!l)
		return;

	nr = btrfs_header_nritems(l);

	btrfs_info(root->fs_info, "leaf %llu total ptrs %d free space %d",
		(unsigned long long)btrfs_header_bytenr(l), nr,
		btrfs_leaf_free_space(root, l));
	for (i = 0 ; i < nr ; i++) {
		item = btrfs_item_nr(l, i);
		btrfs_item_key_to_cpu(l, &key, i);
		type = btrfs_key_type(&key);
		printk(KERN_INFO "\titem %d key (%llu %x %llu) itemoff %d "
		       "itemsize %d\n",
			i,
			(unsigned long long)key.objectid, type,
			(unsigned long long)key.offset,
			btrfs_item_offset(l, item), btrfs_item_size(l, item));
		switch (type) {
		case BTRFS_INODE_ITEM_KEY:
			ii = btrfs_item_ptr(l, i, struct btrfs_inode_item);
			printk(KERN_INFO "\t\tinode generation %llu size %llu "
			       "mode %o\n",
			       (unsigned long long)
			       btrfs_inode_generation(l, ii),
			      (unsigned long long)btrfs_inode_size(l, ii),
			       btrfs_inode_mode(l, ii));
			break;
		case BTRFS_DIR_ITEM_KEY:
			di = btrfs_item_ptr(l, i, struct btrfs_dir_item);
			btrfs_dir_item_key_to_cpu(l, di, &found_key);
			printk(KERN_INFO "\t\tdir oid %llu type %u\n",
				(unsigned long long)found_key.objectid,
				btrfs_dir_type(l, di));
			break;
		case BTRFS_ROOT_ITEM_KEY:
			ri = btrfs_item_ptr(l, i, struct btrfs_root_item);
			printk(KERN_INFO "\t\troot data bytenr %llu refs %u\n",
				(unsigned long long)
				btrfs_disk_root_bytenr(l, ri),
				btrfs_disk_root_refs(l, ri));
			break;
		case BTRFS_EXTENT_ITEM_KEY:
			print_extent_item(l, i);
			break;
		case BTRFS_TREE_BLOCK_REF_KEY:
			printk(KERN_INFO "\t\ttree block backref\n");
			break;
		case BTRFS_SHARED_BLOCK_REF_KEY:
			printk(KERN_INFO "\t\tshared block backref\n");
			break;
		case BTRFS_EXTENT_DATA_REF_KEY:
			dref = btrfs_item_ptr(l, i,
					      struct btrfs_extent_data_ref);
			print_extent_data_ref(l, dref);
			break;
		case BTRFS_SHARED_DATA_REF_KEY:
			sref = btrfs_item_ptr(l, i,
					      struct btrfs_shared_data_ref);
			printk(KERN_INFO "\t\tshared data backref count %u\n",
			       btrfs_shared_data_ref_count(l, sref));
			break;
		case BTRFS_EXTENT_DATA_KEY:
			fi = btrfs_item_ptr(l, i,
					    struct btrfs_file_extent_item);
			if (btrfs_file_extent_type(l, fi) ==
			    BTRFS_FILE_EXTENT_INLINE) {
				printk(KERN_INFO "\t\tinline extent data "
				       "size %u\n",
				       btrfs_file_extent_inline_len(l, fi));
				break;
			}
			printk(KERN_INFO "\t\textent data disk bytenr %llu "
			       "nr %llu\n",
			       (unsigned long long)
			       btrfs_file_extent_disk_bytenr(l, fi),
			       (unsigned long long)
			       btrfs_file_extent_disk_num_bytes(l, fi));
			printk(KERN_INFO "\t\textent data offset %llu "
			       "nr %llu ram %llu\n",
			       (unsigned long long)
			       btrfs_file_extent_offset(l, fi),
			       (unsigned long long)
			       btrfs_file_extent_num_bytes(l, fi),
			       (unsigned long long)
			       btrfs_file_extent_ram_bytes(l, fi));
			break;
		case BTRFS_EXTENT_REF_V0_KEY:
#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
			print_extent_ref_v0(l, i);
#else
			BUG();
#endif
			break;
		case BTRFS_BLOCK_GROUP_ITEM_KEY:
			bi = btrfs_item_ptr(l, i,
					    struct btrfs_block_group_item);
			printk(KERN_INFO "\t\tblock group used %llu\n",
			       (unsigned long long)
			       btrfs_disk_block_group_used(l, bi));
			break;
		case BTRFS_CHUNK_ITEM_KEY:
			print_chunk(l, btrfs_item_ptr(l, i,
						      struct btrfs_chunk));
			break;
		case BTRFS_DEV_ITEM_KEY:
			print_dev_item(l, btrfs_item_ptr(l, i,
					struct btrfs_dev_item));
			break;
		case BTRFS_DEV_EXTENT_KEY:
			dev_extent = btrfs_item_ptr(l, i,
						    struct btrfs_dev_extent);
			printk(KERN_INFO "\t\tdev extent chunk_tree %llu\n"
			       "\t\tchunk objectid %llu chunk offset %llu "
			       "length %llu\n",
			       (unsigned long long)
			       btrfs_dev_extent_chunk_tree(l, dev_extent),
			       (unsigned long long)
			       btrfs_dev_extent_chunk_objectid(l, dev_extent),
			       (unsigned long long)
			       btrfs_dev_extent_chunk_offset(l, dev_extent),
			       (unsigned long long)
			       btrfs_dev_extent_length(l, dev_extent));
			break;
		case BTRFS_DEV_STATS_KEY:
			printk(KERN_INFO "\t\tdevice stats\n");
			break;
		case BTRFS_DEV_REPLACE_KEY:
			printk(KERN_INFO "\t\tdev replace\n");
			break;
		};
	}
}

void btrfs_print_tree(struct btrfs_root *root, struct extent_buffer *c)
{
	int i; u32 nr;
	struct btrfs_key key;
	int level;

	if (!c)
		return;
	nr = btrfs_header_nritems(c);
	level = btrfs_header_level(c);
	if (level == 0) {
		btrfs_print_leaf(root, c);
		return;
	}
	btrfs_info(root->fs_info, "node %llu level %d total ptrs %d free spc %u",
		(unsigned long long)btrfs_header_bytenr(c),
		level, nr, (u32)BTRFS_NODEPTRS_PER_BLOCK(root) - nr);
	for (i = 0; i < nr; i++) {
		btrfs_node_key_to_cpu(c, &key, i);
		printk(KERN_INFO "\tkey %d (%llu %u %llu) block %llu\n",
		       i,
		       (unsigned long long)key.objectid,
		       key.type,
		       (unsigned long long)key.offset,
		       (unsigned long long)btrfs_node_blockptr(c, i));
	}
	for (i = 0; i < nr; i++) {
		struct extent_buffer *next = read_tree_block(root,
					btrfs_node_blockptr(c, i),
					btrfs_level_size(root, level - 1),
					btrfs_node_ptr_generation(c, i));
		if (btrfs_is_leaf(next) &&
		   level != 1)
			BUG();
		if (btrfs_header_level(next) !=
		       level - 1)
			BUG();
		btrfs_print_tree(root, next);
		free_extent_buffer(next);
	}
}


text:
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POINTS_HPP
#define BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POINTS_HPP

#include <algorithm>
#include <string>

#include <boost/concept_check.hpp>
#include <boost/numeric/conversion/cast.hpp>

#include <boost/geometry/arithmetic/determinant.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/strategies/side_info.hpp>
#include <boost/geometry/util/select_calculation_type.hpp>
#include <boost/geometry/util/select_most_precise.hpp>

namespace boost { namespace geometry
{

namespace policies { namespace relate
{

template <typename S1, typename S2, typename ReturnType, typename CalculationType = void>
struct segments_intersection_points
{
    typedef ReturnType return_type;
    typedef S1 segment_type1;
    typedef S2 segment_type2;

    typedef typename select_calculation_type
        <
            S1, S2, CalculationType
        >::type coordinate_type;

	template <typename R>
    static inline return_type segments_intersect(side_info const&,
					R const& r,
                    coordinate_type const& dx1, coordinate_type const& dy1,
                    coordinate_type const& dx2, coordinate_type const& dy2,
                    S1 const& s1, S2 const& s2)
    {
        typedef typename geometry::coordinate_type
            <
                typename return_type::point_type
            >::type return_coordinate_type;

        coordinate_type const s1x = get<0, 0>(s1);
        coordinate_type const s1y = get<0, 1>(s1);

        return_type result;
        result.count = 1;
        set<0>(result.intersections[0],
            boost::numeric_cast<return_coordinate_type>(R(s1x) + r * R(dx1)));
        set<1>(result.intersections[0],
            boost::numeric_cast<return_coordinate_type>(R(s1y) + r * R(dy1)));

        return result;
    }

    static inline return_type collinear_touch(coordinate_type const& x,
                coordinate_type const& y, int, int)
    {
        return_type result;
        result.count = 1;
        set<0>(result.intersections[0], x);
        set<1>(result.intersections[0], y);
        return result;
    }

    template <typename S>
    static inline return_type collinear_inside(S const& s, int index1 = 0, int index2 = 1)
    {
        return_type result;
        result.count = 2;
        set<0>(result.intersections[index1], get<0, 0>(s));
        set<1>(result.intersections[index1], get<0, 1>(s));
        set<0>(result.intersections[index2], get<1, 0>(s));
        set<1>(result.intersections[index2], get<1, 1>(s));
        return result;
    }

    template <typename S>
    static inline return_type collinear_interior_boundary_intersect(S const& s, bool a_in_b,
                int, int, bool opposite)
    {
        int index1 = opposite && ! a_in_b ? 1 : 0;
        return collinear_inside(s, index1, 1 - index1);
    }

    static inline return_type collinear_a_in_b(S1 const& s, bool)
    {
        return collinear_inside(s);
    }
    static inline return_type collinear_b_in_a(S2 const& s, bool opposite)
    {
        int index1 = opposite ? 1 : 0;
        return collinear_inside(s, index1, 1 - index1);
    }

    static inline return_type collinear_overlaps(
                coordinate_type const& x1, coordinate_type const& y1,
                coordinate_type const& x2, coordinate_type const& y2,
                int, int, bool)
    {
        return_type result;
        result.count = 2;
        set<0>(result.intersections[0], x1);
        set<1>(result.intersections[0], y1);
        set<0>(result.intersections[1], x2);
        set<1>(result.intersections[1], y2);
        return result;
    }

    static inline return_type segment_equal(S1 const& s, bool)
    {
        return_type result;
        result.count = 2;
        // TODO: order of IP's
        set<0>(result.intersections[0], get<0, 0>(s));
        set<1>(result.intersections[0], get<0, 1>(s));
        set<0>(result.intersections[1], get<1, 0>(s));
        set<1>(result.intersections[1], get<1, 1>(s));
        return result;
    }

    static inline return_type disjoint()
    {
        return return_type();
    }
    static inline return_type error(std::string const&)
    {
        return return_type();
    }

    static inline return_type collinear_disjoint()
    {
        return return_type();
    }

    static inline return_type degenerate(S1 const& s, bool)
    {
        return_type result;
        result.count = 1;
        set<0>(result.intersections[0], get<0, 0>(s));
        set<1>(result.intersections[0], get<0, 1>(s));
        return result;
    }
};

}} // namespace policies::relate

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POINTS_HPP


text:
$(document).ready(function() {
  addAllTheCake();
  watchForPageChanges();
  manageNewComment();
  manageTabs();
});

function addAllTheCake() {
  addWordWrapCheckbox();
  addSideBySideCheckbox();
  addNoWhitespaceCheckbox();
}

function addWordWrapCheckbox() {
  var $clickFn = function(event) {
    if ($(this).is(':checked')) {
       $('#files .data').addClass('word-wrap');
    } else {
       $('#files .data').removeClass('word-wrap');
    }
  };

  addOneCheckbox('wordwrap', 'octicon-gift', 'Word wrap', $clickFn, false);
}

function addSideBySideCheckbox() {
  var $clickFn = function(event) {
    if ($(this).is(':checked')) {
      enlarge();
      splitDiffs();
    } else {
      shrink();
      resetDiffs();
    }
  };
  addOneCheckbox('octosplit', 'octicon-mirror-public', 'Side by side', $clickFn, false);
}

function addNoWhitespaceCheckbox() {
  var $clickFn = function(event) {
    if ($(this).is(':checked')) {
      addNoWhitespaceParam();
    } else {
      removeNoWhitespaceParam();
    }
  };
  addOneCheckbox('no-whitespace', 'octicon-telescope', 'No whitespace', $clickFn, hasNoWhitespaceParam());
}

function addOneCheckbox($id, $labelSpanClasses, $labelInner, $clickFn, $checked) {
  var $checkedStr = $checked ? 'checked' : '';
  var $checkbox = $('<input type="checkbox" id="' + $id + '" ' + $checkedStr +' class="octosplit-checkbox" />');
  var $label    = $('' + $labelInner + '');

  $('#toc .toc-diff-stats').append($label, $checkbox);

  $checkbox.on('click', $clickFn);
}

function watchForPageChanges() {
  var pjaxContainer = $("#js-repo-pjax-container");
  if (pjaxContainer.size() == 0) {
    return;
  }
  var currentToc = $("#toc").get(0);
  var observer = new MutationObserver(function(records) {
    var newToc = $("#toc").get(0);
    if (newToc != currentToc) {
      addAllTheCake();
      currentToc = newToc;
    }
  });
  observer.observe(pjaxContainer.get(0), {childList: true, subtree: true});
}

function manageNewComment() {
  $('#files').on('click', function(event) {
    if (!$('#octosplit').is(':checked')) {
      return;
    }

    $elmt = $(event.target);
    if (!$elmt.hasClass('add-line-comment')) {
      return;
    }

    window.setTimeout(function() {
      splitInlineComment($($elmt.parent().parent().next()));
    }, 800);
  });
}

function manageTabs() {
  $('.tabnav .tabnav-tab', $('.new-pull-request, .view-pull-request')).on('click', function(event) {
    window.setTimeout(function() {
      if (isFilesBucketTab() && $('#octosplit').is(':checked')) {
        enlarge();
      } else {
        shrink();
      }
    }, 100);
  });
}

function enlarge() {
  $('.wrapper .container').addClass('large');
}

function shrink() {
  $('.wrapper .container.large').removeClass('large');
}

function splitDiffs() {
  $('table.diff-table').each(function() {
    if (isSplittable($(this))) {
      $('tbody tr', $(this)).each(function() {
        if ($(this).hasClass('inline-comments')) {
          splitInlineComment($(this));
        } else if ($(this).hasClass('js-expandable-line')) {
          splitExpandableLine($(this));
        } else {
          splitDiffLine($(this))
        }
      });
    }
  })
}

function resetDiffs() {
  $('table.diff-table').each(function() {
    if (isResettable($(this))) {
      $('tbody tr', $(this)).each(function() {
        if ($(this).hasClass('inline-comments')) {
          resetInlineComment($(this));
        } else if ($(this).hasClass('js-expandable-line')) {
          resetExpandableLine($(this));
        } else {
          resetDiffLine($(this))
        }
      });
    }
  })
}

function splitDiffLine($line) {
  var $children = $line.children();

  var $oldNumber = $($children[0]);
  var $newNumber = $($children[1]);
  var $LOC = $($children[2]);

  var $oldLOC = $('	');
  var $newLOC = $('	');

  if ($oldNumber.hasClass('blob-num-deletion')) {
    $oldLOC.html($LOC.html());
    $oldLOC.attr('class', $LOC.attr('class'));
    $newLOC.addClass('nd');
    $newNumber.addClass('nd');
    $newLOC.html('');
  } else if ($newNumber.hasClass('blob-num-addition')) {
    $oldLOC.html('');
    $newLOC.attr('class', $LOC.attr('class'));
    $newLOC.html($LOC.html());
    $oldLOC.addClass('nd');
    $oldNumber.addClass('nd');
  } else {
    $oldLOC.html($LOC.html());
    $oldLOC.attr('class', $LOC.attr('class'));
    $newLOC.html($LOC.html());
    $newLOC.attr('class', $LOC.attr('class'));
  }

  $newNumber.addClass('new-number');

  if($oldLOC.children().first().hasClass('add-bubble')) {
    $oldLOC.children().first().remove();
  }

  $oldLOC.insertAfter($oldNumber);
  $newLOC.insertAfter($newNumber);
  $LOC.remove();
}

function resetDiffLine($line) {
  var $children = $line.children();

  var $oldNumber = $($children[0]);
  var $oldLOC    = $($children[1]);
  var $newNumber = $($children[2]);
  var $newLOC    = $($children[3]);

  if ($oldNumber.hasClass('blob-num-deletion')) {
    $newLOC.html($oldLOC.html());
    $newLOC.attr('class', $oldLOC.attr('class'));
  }

  $oldLOC.remove();

  $oldNumber.removeClass('nd');
  $newNumber.removeClass('nd');
  $newLOC.removeClass('nd');
}

function splitInlineComment($line) {
  $line.children().first().attr('colspan', 1);
  $line.children().last().attr('colspan', 3);
}

function resetInlineComment($line) {
  $line.children().first().attr('colspan', 2);
  $line.children().last().attr('colspan', 1);
}

function splitExpandableLine($line) {
  $line.children('.expandable-line-num').attr('colspan', 1);
  $line.children('.blob-code').attr('colspan', 3);
  $line.children('.expandable-line-code').attr('colspan', 3);
}

function resetExpandableLine($line) {
  $line.children('.expandable-line-num').attr('colspan', 2);
  $line.children('.blob-code').attr('colspan', 1);
  $line.children('.expandable-line-code').attr('colspan', 1);
}

function isFilesBucketTab() {
  return ($('.tabnav-tab.selected').attr('href') == '#files_bucket') || ($('.tabnav-tab.selected').data().containerId == 'files_bucket');
}

function isSplittable($table) {
  return ($('tr > td.blob-num-deletion', $table).length || $('tr > td.blob-num-addition', $table).length);
}

function isResettable($table) {
  return ($('.new-number', $table).length > 0)
}

function hasNoWhitespaceParam() {
  return getURLParameter('w') !== null; // Right now w can have any value as long is present gh will remove whitespace
}

function removeNoWhitespaceParam() {
  document.location = removeParameter(document.location.href, 'w');
}

function addNoWhitespaceParam() {
  if (!hasNoWhitespaceParam()) {
    insertParameter('w', '1');
  }
}

// Some Utility methods
// Barely based on http://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript
function insertParameter(key, value) {
  key = encodeURIComponent(key); value = encodeURIComponent(value);

  var s = removeParameter(document.location.search, key); // We remove it in case is there already
  var kvp = key+"="+value;

  s += (s.indexOf('?') !== -1 ? '&' : '?') + kvp;

  document.location.search = s;
}
// Stolen from http://stackoverflow.com/questions/1634748/how-can-i-delete-a-query-string-parameter-in-javascript
function removeParameter(url, parameter) {
  var urlparts= url.split('?');

  if (urlparts.length>=2) {
    var urlBase=urlparts.shift(); //get first part, and remove from array
    var queryString=urlparts.join("?"); //join it back up

    var prefix = encodeURIComponent(parameter)+'=';
    var pars = queryString.split(/[&;]/g);
    if (pars.length > 0) {
      for (var i= pars.length; i-->0;)               //reverse iteration as may be destructive
        if (pars[i].lastIndexOf(prefix, 0)!==-1)   //idiom for string.startsWith
          pars.splice(i, 1);
      url = urlBase+'?'+pars.join('&');
    }
  }

  // remove trailing ?
  if(url.substr(-1) == '?') {
    url = url.substr(0, url.length - 1);
  }

  return url;
}
// From http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(document.location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}


text:
package br.com.cmabreu.webomt.wrapper;

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

import br.com.cmabreu.webomt.ieee1516e.Attribute;
import br.com.cmabreu.webomt.ieee1516e.ReferenceType;

public class FomAttribute {
	private String name;
	private String dataType;
	private Attribute attribute;
	private List<String> dimensions;
	private String ownerShip;
	private String order;
	private String semantics;
	private String sharing;
	private String transportation;
	private String updateCondition;
	private String updateType;

	public FomAttribute( Attribute attribute ) {
		this.attribute = attribute;
		name = attribute.getName().getValue();
		dataType = attribute.getDataType().getValue();
		dimensions = new ArrayList<String>();
		order = attribute.getOrder().getValue().toString();
		ownerShip = attribute.getOwnership().getValue().toString();

		if ( attribute.getUpdateType() != null ) {
			updateType = attribute.getUpdateType().getValue().toString();
		}
		if ( attribute.getUpdateCondition() != null ) {
			updateCondition = attribute.getUpdateCondition().getValue();
		}
		if ( attribute.getTransportation() != null ) {
			transportation = attribute.getTransportation().getValue();
		}
		if ( attribute.getSharing() != null ) {
			sharing = attribute.getSharing().getValue().toString();
		}
		if ( attribute.getSemantics() != null ) {
			semantics = attribute.getSemantics().getValue();
		}
		if ( attribute.getDimensions() != null ) {
			for ( ReferenceType dim : attribute.getDimensions().getDimension() ) {
				dimensions.add( dim.getValue() );
			}
		}
	}

	public Attribute getAttribute() {
		return attribute;
	}

	public String getName() {
		return name;
	}

	public String getDataType() {
		return dataType;
	}

	public List<String> getDimensions() {
		return dimensions;
	}

	public String getOrder() {
		return order;
	}

	public String getOwnerShip() {
		return ownerShip;
	}

	public String getSemantics() {
		return semantics;
	}

	public String getSharing() {
		return sharing;
	}

	public String getTransportation() {
		return transportation;
	}

	public String getUpdateCondition() {
		return updateCondition;
	}

	public String getUpdateType() {
		return updateType;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>giddy.mobility — giddy v2.3.3 Manual</title>
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../_static/pysal-styles.css" />

    <link rel="shortcut icon" href="../../_static/pysal_favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          giddy
        2.3.3

Installation

Tutorial

API

References

  Site

Contents:

Installation

Installing released version

Installing development version

Tutorial

Spatially Explicit Markov Methods

Full Rank Markov and Geographic Rank Markov

Measures of Income Mobility

Directional Analysis of Dynamic LISAs

Rank based Methods

Alignment-based sequence methods

API

Markov Methods

Directional LISA

Economic Mobility Indices

Exchange Mobility Methods

Alignment-based Sequence Methods

Utility Functions

References

  Page

<form class="navbar-form navbar-right" action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Source code for giddy.mobility

"""
Income mobility measures.
"""

__author__ = "Wei Kang <weikang9009@gmail.com>, Sergio J. Rey <sjsrey@gmail.com>"

__all__ = ["markov_mobility"]

import numpy as np
import numpy.linalg as la

[docs]def markov_mobility(p, measure="P", ini=None):
    """
    Markov-based mobility index.

    Parameters
    ----------
    p       : array
              (k, k), Markov transition probability matrix.
    measure : string
              If measure= "P",
              :math:`M_{P} = \\frac{m-\sum_{i=1}^m P_{ii}}{m-1}`;
              if measure = "D",
              :math:`M_{D} = 1 - |\det(P)|`,
              where :math:`\det(P)` is the determinant of :math:`P`;
              if measure = "L2",
              :math:`M_{L2} = 1  - |\lambda_2|`,
              where :math:`\lambda_2` is the second largest eigenvalue of
              :math:`P`;
              if measure = "B1",
              :math:`M_{B1} = \\frac{m-m \sum_{i=1}^m \pi_i P_{ii}}{m-1}`,
              where :math:`\pi` is the initial income distribution;
              if measure == "B2",
              :math:`M_{B2} = \\frac{1}{m-1} \sum_{i=1}^m \sum_{
              j=1}^m \pi_i P_{ij} |i-j|`,
              where :math:`\pi` is the initial income distribution.
    ini     : array
              (k,), initial distribution. Need to be specified if
              measure = "B1" or "B2". If not,
              the initial distribution would be treated as a uniform
              distribution.

    Returns
    -------
    mobi    : float
              Mobility value.

    Notes
    -----
    The mobility indices are based on :cite:`Formby:2004fk`.

    Examples
    --------
    >>> import numpy as np
    >>> import libpysal
    >>> import mapclassify as mc
    >>> from giddy.markov import Markov
    >>> from giddy.mobility import markov_mobility
    >>> f = libpysal.io.open(libpysal.examples.get_path("usjoin.csv"))
    >>> pci = np.array([f.by_col[str(y)] for y in range(1929,2010)])
    >>> q5 = np.array([mc.Quantiles(y).yb for y in pci]).transpose()
    >>> m = Markov(q5)
    The Markov Chain is irreducible and is composed by:
    1 Recurrent class (indices):
    [0 1 2 3 4]
    0 Transient classes.
    The Markov Chain has 0 absorbing states.
    >>> m.p
    array([[0.91011236, 0.0886392 , 0.00124844, 0.        , 0.        ],
           [0.09972299, 0.78531856, 0.11080332, 0.00415512, 0.        ],
           [0.        , 0.10125   , 0.78875   , 0.1075    , 0.0025    ],
           [0.        , 0.00417827, 0.11977716, 0.79805014, 0.07799443],
           [0.        , 0.        , 0.00125156, 0.07133917, 0.92740926]])

    (1) Estimate Shorrock1 mobility index:

    >>> mobi_1 = markov_mobility(m.p, measure="P")
    >>> print("{:.5f}".format(mobi_1))
    0.19759

    (2) Estimate Shorrock2 mobility index:

    >>> mobi_2 = markov_mobility(m.p, measure="D")
    >>> print("{:.5f}".format(mobi_2))
    0.60685

    (3) Estimate Sommers and Conlisk mobility index:

    >>> mobi_3 = markov_mobility(m.p, measure="L2")
    >>> print("{:.5f}".format(mobi_3))
    0.03978

    (4) Estimate Bartholomew1 mobility index (note that the initial
    distribution should be given):

    >>> ini = np.array([0.1,0.2,0.2,0.4,0.1])
    >>> mobi_4 = markov_mobility(m.p, measure = "B1", ini=ini)
    >>> print("{:.5f}".format(mobi_4))
    0.22777

    (5) Estimate Bartholomew2 mobility index (note that the initial
    distribution should be given):

    >>> ini = np.array([0.1,0.2,0.2,0.4,0.1])
    >>> mobi_5 = markov_mobility(m.p, measure = "B2", ini=ini)
    >>> print("{:.5f}".format(mobi_5))
    0.04637

    """

    p = np.array(p)
    k = p.shape[1]
    if measure == "P":
        t = np.trace(p)
        mobi = (k - t) / (k - 1)
    elif measure == "D":
        mobi = 1 - abs(la.det(p))
    elif measure == "L2":
        w, v = la.eig(p)
        eigen_value_abs = abs(w)
        mobi = 1 - np.sort(eigen_value_abs)[-2]
    elif measure == "B1":
        if ini is None:
            ini = 1.0 / k * np.ones(k)
        mobi = (k - k * np.sum(ini * np.diag(p))) / (k - 1)
    elif measure == "B2":
        mobi = 0
        if ini is None:
            ini = 1.0 / k * np.ones(k)
        for i in range(k):
            for j in range(k):
                mobi = mobi + ini[i] * p[i, j] * abs(i - j)
        mobi = mobi / (k - 1)

    return mobi

      Back to top

        © Copyright 2018-, pysal developers.

      Created using Sphinx 3.4.3.


text:
#include <iostream>
#include <vector>

/*
 * Solution: see this video --> https://www.youtube.com/watch?v=siKFOI8PNKM
 *
 * Time complexity: O(n * m) [where n is the number of rows in the input matrix and m is the number of columns in the input matrix]
 * Space complexity: O(1)
 */

std::vector<int> spiralOrder(std::vector<std::vector<int>> & matrix)
{
    std::vector<int> traversal;

    if(matrix.empty())
    {
        return traversal;
    }

    int rows=int(matrix.size());

    int columns=int(matrix[0].size());

    int topRow=0;

    int bottomRow=rows-1;

    int leftColumn=0;

    int rightColumn=columns-1;

    int direction=0;

    while(topRow <= bottomRow && leftColumn <= rightColumn)
    {
        if(direction==0)
        {
            for(int i=leftColumn;i<=rightColumn;++i)
            {
                traversal.push_back(matrix[topRow][i]);
            }

            topRow++;
        }
        else if(direction==1)
        {
            for(int i=topRow;i<=bottomRow;++i)
            {
                traversal.push_back(matrix[i][rightColumn]);
            }

            rightColumn--;
        }
        else if(direction==2)
        {
            for(int i=rightColumn;i>=leftColumn;--i)
            {
                traversal.push_back(matrix[bottomRow][i]);
            }

            bottomRow--;
        }
        else if(direction==3)
        {
            for(int i=bottomRow;i>=topRow;--i)
            {
                traversal.push_back(matrix[i][leftColumn]);
            }

            leftColumn++;
        }

        direction=(direction + 1) % 4;
    }

    return traversal;
}


text:
namespace AGE
{
	OpenGLState::State OpenGLState::_currentState;

	const OpenGLState::ToStateMode OpenGLState::_glToStateMode[State::NUMBER_OF_MODES] =
	{
		{ GL_ALPHA_TEST, State::ALPHA_TEST },
		{ GL_BLEND, State::BLEND },
		{ GL_CULL_FACE, State::CULL_FACE },
		{ GL_DEPTH_TEST, State::DEPTH_TEST },
		{ GL_STENCIL_TEST, State::STENCIL_TEST },
		{ GL_SCISSOR_TEST, State::SCISSOR_TEST },
		{ GL_TEXTURE_1D, State::TEXTURE_1D },
		{ GL_TEXTURE_2D, State::TEXTURE_2D },
		{ GL_TEXTURE_3D, State::TEXTURE_3D },
		{ GL_TEXTURE_CUBE_MAP, State::TEXTURE_CUBE_MAP }
	};

	OpenGLState::State::State()
	{
		depth.func = GL_LESS;
		depth.mask = GL_TRUE;
		stencil.func = GL_ALWAYS;
		stencil.ref = 0;
		stencil.mask = 0xFFFFFFFF;
		stencil.op.sfail = GL_KEEP;
		stencil.op.dpfail = GL_KEEP;
		stencil.op.dppass = GL_KEEP;
		blend.sfactor = GL_ONE;
		blend.dfactor = GL_ZERO;
		blend.equation = GL_FUNC_ADD;
		cullFace = GL_BACK;
		colorMask = glm::bvec4(true);
		clearColor = glm::vec4(0);
		clearDepth = 1.0;
		clearStencil = 0;
	}

	void OpenGLState::glEnable(GLenum cap)
	{
		State::Modes mode = _findMode(cap);

		assert(mode != State::NUMBER_OF_MODES);
		if (_currentState.enabledModes[mode] == false)
		{
			::glEnable(cap);
			_currentState.enabledModes[mode] = true;
		}
	}

	void OpenGLState::glDisable(GLenum cap)
	{
		State::Modes mode = _findMode(cap);

		assert(mode != State::NUMBER_OF_MODES);
		if (_currentState.enabledModes[mode] == true)
		{
			::glDisable(cap);
			_currentState.enabledModes[mode] = false;
		}
	}

	void OpenGLState::glDepthFunc(GLenum func)
	{
		if (_currentState.depth.func != func)
		{
			::glDepthFunc(func);
			_currentState.depth.func = func;
		}
	}

	void OpenGLState::glDepthMask(GLenum flag)
	{
		if (_currentState.depth.mask != flag)
		{
			::glDepthMask(flag);
			_currentState.depth.mask = flag;
		}
	}

	void OpenGLState::glStencilFunc(GLenum func, GLint ref, GLuint mask)
	{
		if (_currentState.stencil.func != func ||
			_currentState.stencil.ref != ref ||
			_currentState.stencil.mask != mask)
		{
			::glStencilFunc(func, ref, mask);
			_currentState.stencil.func = func;
			_currentState.stencil.ref = ref;
			_currentState.stencil.mask = mask;
		}
	}

	void OpenGLState::glStencilOp(GLenum sfail, GLenum dpfail, GLenum dppass)
	{
		if (_currentState.stencil.op.sfail != sfail ||
			_currentState.stencil.op.dpfail != dpfail ||
			_currentState.stencil.op.dppass != dppass)
		{
			::glStencilOp(sfail, dpfail, dppass);
			_currentState.stencil.op.sfail = sfail;
			_currentState.stencil.op.dpfail = dpfail;
			_currentState.stencil.op.dppass = dppass;
		}
	}

	void OpenGLState::glBlendFunc(GLenum sfactor, GLenum dfactor)
	{
		if (_currentState.blend.sfactor != sfactor ||
			_currentState.blend.dfactor != dfactor)
		{
			::glBlendFunc(sfactor, dfactor);
			_currentState.blend.sfactor = sfactor;
			_currentState.blend.dfactor = dfactor;
		}
	}

	void OpenGLState::glBlendEquation(GLenum mode)
	{
		if (_currentState.blend.equation != mode)
		{
			::glBlendEquation(mode);
			_currentState.blend.equation = mode;
		}
	}

	void OpenGLState::glCullFace(GLenum mode)
	{
		if (_currentState.cullFace != mode)
		{
			::glCullFace(mode);
			_currentState.cullFace = mode;
		}
	}

	void OpenGLState::glColorMask(glm::bvec4 const &mask)
	{
		if (_currentState.colorMask != mask)
		{
			::glColorMask(mask.r, mask.g, mask.b, mask.a);
			_currentState.colorMask = mask;
		}
	}

	void OpenGLState::glClearColor(glm::vec4 const &ref)
	{
		if (_currentState.clearColor != ref)
		{
			::glClearColor(ref.r, ref.g, ref.b, ref.a);
			_currentState.clearColor = ref;
		}
	}

	void OpenGLState::glClearDepth(GLclampd ref)
	{
		if (_currentState.clearDepth != ref)
		{
			::glClearDepth(ref);
			_currentState.clearDepth = ref;
		}
	}

	void OpenGLState::glClearStencil(GLint ref)
	{
		if (_currentState.clearStencil != ref)
		{
			::glClearStencil(ref);
			_currentState.clearStencil = ref;
		}
	}

	OpenGLState::State::Modes OpenGLState::_findMode(GLenum ogl)
	{
		for (int i = 0; i < State::NUMBER_OF_MODES; ++i)
		{
			if (_glToStateMode[i].ogl == ogl)
				return (_glToStateMode[i].mode);
		}
		return (State::NUMBER_OF_MODES);
	}

	void OpenGLState::setCurrentState(State const &toSet)
	{
		for (int i = 0; i < State::NUMBER_OF_MODES; ++i)
		{
			if (_currentState.enabledModes[i] != toSet.enabledModes[i])
			{
				::glEnable(_glToStateMode[i].ogl);
			}
		}
		_currentState.enabledModes = toSet.enabledModes;
		glDepthFunc(toSet.depth.func);
		glDepthMask(toSet.depth.mask);
		glStencilFunc(toSet.stencil.func, toSet.stencil.ref, toSet.stencil.mask);
		glStencilOp(toSet.stencil.op.sfail, toSet.stencil.op.dpfail, toSet.stencil.op.dppass);
		glBlendFunc(toSet.blend.sfactor, toSet.blend.dfactor);
		glBlendEquation(toSet.blend.equation);
		glCullFace(toSet.cullFace);
		glClearColor(toSet.clearColor);
		glClearDepth(toSet.clearDepth);
		glClearStencil(toSet.clearStencil);
	}

}


text:
layout: article
title: null
permalink: /links/
comments: true
published: true
---

A collection of data science resources. Inspired by the Awesome sites listed below, but rather than being an exhaustive collection only recommended resources are listed.

{% include toc.html %}

## Awesome Sites

- [Awesome R](https://github.com/qinwf/awesome-R){:target="_blank"}
- [Awesome Python](http://awesome-python.com/){:target="_blank"}
- [Awesome Machine Learning](https://github.com/josephmisiti/awesome-machine-learning){:target="_blank"}
- [Awesome Data Science Books](https://github.com/josephmisiti/awesome-machine-learning/blob/master/books.md){:target="_blank"}
- [Awesome Public Datasets](https://github.com/caesar0301/awesome-public-datasets){:target="_blank"}

## Forums/Social Media

- [Quora](http://quora.com){:target="_blank"} - my guide for everything geeky, and possibly the rest of my life.
	- [Quora: How can I become a data scientist?](https://www.quora.com/How-can-I-become-a-data-scientist){:target="_blank"} - Experienced data scientists share their thoughts on how to approach the task of becoming a data scientist.
- [Cross Validated](http://stats.stackexchange.com/){:target="_blank"}
- [R-bloggers](http://www.r-bloggers.com/){:target="_blank"}
- [KDnuggets](http://www.kdnuggets.com/){:target="_blank"}

## Data Science MOOCs

- [MITx: Introduction to Computer Science and Programming Using Python](https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-6){:target="_blank"} - 6.00.1x is one of the best introductions to CS and programming available online, and it is also in Python.
- [MITx: Introduction to Computational Thinking and Data Science](https://www.edx.org/course/introduction-computational-thinking-data-mitx-6-00-2x-3){:target="_blank"} - 6.00.2x, the continuation of 6.00.1x
- [Stanford University: Algorithms: Design and Analysis, Part 1](https://www.coursera.org/course/algo){:target="_blank"}
- [Stanford University: Algorithms: Design and Analysis, Part 2](https://www.coursera.org/course/algo2){:target="_blank"}
- [Duke University: Data Analysis and Statistical Inference](https://www.coursera.org/course/statistics){:target="_blank"}
- [MITx: Introduction to Probability](https://www.edx.org/course/introduction-probability-science-mitx-6-041x-1){:target="_blank"}
- [MITx: The Analytics Edge](https://www.edx.org/course/analytics-edge-mitx-15-071x-0){:target="_blank"}
- [Johns Hopkins University: Data Science Specialization](https://www.coursera.org/specializations/jhu-data-science){:target="_blank"}
	- [Course notes by Xing Su](http://sux13.github.io/DataScienceSpCourseNotes/){:target="_blank"}
	- [Community Content](http://datasciencespecialization.github.io/){:target="_blank"}
- [Harvard University: CS109 Data Science](http://cs109.github.io/2015/){:target="_blank"}
- [Stanford University: Statistical Learning](https://lagunita.stanford.edu/courses/HumanitiesSciences/StatLearning/Winter2016/about){:target="_blank"}
- [Stanford University: Machine Learning](https://www.coursera.org/learn/machine-learning){:target="_blank"}
	- [Course notes on Coursera wiki](https://share.coursera.org/wiki/index.php/ML:Main){:target="_blank"}
	- [Other course notes, with figures](http://www.holehouse.org/mlclass/index.html){:target="_blank"}
- [Caltech: Learning From Data](http://work.caltech.edu/telecourse.html){:target="_blank"}
- [Stanford Databases mini-courses](https://lagunita.stanford.edu/courses/DB/2014/SelfPaced/about)
  - My course notes in HTML for [DB4 Relational Algebra](https://dl.dropboxusercontent.com/s/0t7a8do7voge3yv/Relational%20Algebra%20Notes.html?){:target="_blank"} and [DB5 SQL](https://dl.dropboxusercontent.com/s/zpey789p9ndryvr/SQL%20Notes.html?dl=0){:target="_blank"}, or in modifiable IPython notebook format in my [GitHub repository](https://github.com/rasnes/SQLLectureNotes){:target="_blank"}

## Data Science Books (free)

- [Awesome Data Science Books](https://github.com/josephmisiti/awesome-machine-learning/blob/master/books.md){:target="_blank"}
- [Advanced R, by Hadley Wickham](http://adv-r.had.co.nz/){:target="_blank"}
- [R Tutorial - An R Introduction to Statistics](http://www.r-tutor.com/){:target="_blank"}
- [Cookbook for R](http://www.cookbook-r.com/){:target="_blank"}
- Books written as part of the Johns Hopkins Data Science Specialization
	- [R Programming for Data Science](https://leanpub.com/rprogramming){:target="_blank"}
	- [Report Writing for Data Science in R](https://leanpub.com/reportwriting){:target="_blank"}
	- [Exploratory Data Analysis with R](https://leanpub.com/exdata){:target="_blank"}
	- [The Art of Data Science](https://leanpub.com/artofdatascience){:target="_blank"}
	- [The Elements of Data Analytic Style](https://leanpub.com/datastyle){:target="_blank"}
- [Dive Into Python](http://www.diveintopython.net/toc/index.html){:target="_blank"}
- [OpenIntro Statistics](https://www.openintro.org/stat/textbook.php?stat_book=os){:target="_blank"} - A good statistics intro book, written by the creator of the [Data Analysis and Statistical Inference MOOC](https://www.coursera.org/course/statistics){:target="_blank"}.
- [An Introduction to Statistical Learning](http://www-bcf.usc.edu/~gareth/ISL/){:target="_blank"}
- [The Elements of Statistical Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/){:target="_blank"} - The machine learning "bible".

## Data Science Books (paid)

- [Bayesian Data Analysis](http://www.amazon.com/gp/product/1439840954?colid=SAMJAHRTU0H4&coliid=I2HBQ23BX3JOJ&ref_=wl_it_dp_o_pC_nS_ttl){:target="_blank"}
- [Applied Predictive Modeling](http://www.amazon.com/gp/product/1439840954?colid=SAMJAHRTU0H4&coliid=I2HBQ23BX3JOJ&ref_=wl_it_dp_o_pC_nS_ttl){:target="_blank"}
- [The Visual Display of Quantitative Information](http://www.amazon.com/gp/product/0961392142?colid=SAMJAHRTU0H4&coliid=IMRXVDTEVFWT6&ref_=wl_it_dp_o_pC_nS_ttl){:target="_blank"}

## R

- [Awesome R](https://github.com/qinwf/awesome-R){:target="_blank"}
- [RStudio Cheat Sheets](https://www.rstudio.com/resources/cheatsheets/){:target="_blank"} - Very handy cheat sheets for RStudio IDE, Shiny, data visualization with ggplot2, package development, data wrangling with dplyr and tidyr and R Markdown.
- [Quick-R, accessing the power of R](http://www.statmethods.net/){:target="_blank"} - A concise reference on base R.
- [R Documentation](http://www.rdocumentation.org/){:target="_blank"} - The official R documentation nicely formatted online, with syntax highlighting etc.
- [Thesaurus of Mathematical Languages - R vs Python vs MatLab](http://mathesaurus.sourceforge.net/){:target="_blank"}
- [R Grouping functions: sapply vs. lapply vs. apply. vs. tapply vs. by vs. aggregate](http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega){:target="_blank"} - A great Stackexchange thread about R's might-be confusing apply family of functions.
- [How to make great R reproducible example?](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example){:target="_blank"} - A helpful Stackexchange thread about how to post your R problems on R-help or Stackexchange.
- [R swirl library](http://swirlstats.com/){:target="_blank"} - A great interactive R tutorial, right in the R console.

## Python

- [Awesome Python](http://awesome-python.com/){:target="_blank"}
- [Numpy for Matlab Users](http://scipy.github.io/old-wiki/pages/NumPy_for_Matlab_Users.html){:target="_blank"}
- [Learn Python the Hard Way](http://learnpythonthehardway.org/book/){:target="_blank"} - A good place to start if you are unfamiliar with Python or programming. (You could perhaps skip most of the object oriented stuff at the end if your main focus is Data Science, and rather spend your time on Numpy, Pandas, etc.)
- [R vs Python](http://blog.datacamp.com/r-or-python-for-data-analysis/){:target="_blank"} - An unbiased visual comparison of R and Python for data science.
- [Beginner's Resources to Learn Programming Languages](https://www.vodien.com/blog/education/beginners-resources-to-learn-programming-languages.php){:target="_blank"} - A comprehensive overview of learning resources for several progamming languages, including Python.

## Machine Learning

- [Awesome Machine Learning](https://github.com/josephmisiti/awesome-machine-learning){:target="_blank"}
- [Stanford University: UFLDL Tutorial](http://ufldl.stanford.edu/wiki/index.php/UFLDL_Tutorial){:target="_blank"}
- [UBC: Machine Learning Lecture Notes](http://www.cs.ubc.ca/~nando/540-2013/lectures.html){:target="_blank"}
- [Stanford University: CS 229 Lectore Notes](http://cs229.stanford.edu/materials.html){:target="_blank"}

<!-- Resources questionable if I can recommend:
- [R packages, by Hadley Wickham](http://r-pkgs.had.co.nz/){:target="_blank"}
- [Statistical Inference for Data Science](https://leanpub.com/LittleInferenceBook){:target="_blank"}
- [Regression Models for Data Science in R](https://leanpub.com/regmods){:target="_blank"}
- [Forecasting: principles and practice](https://www.otexts.org/book/fpp){:target="_blank"}
- [A Little Book of R for Time Series](https://a-little-book-of-r-for-time-series.readthedocs.org/en/latest/){:target="_blank"}
- [Introduction to R, course notes by Ramnath Vaidyanathan](https://ramnathv.github.io/pycon2014-r/){:target="_blank"}

-->


text:
namespace Epic.Numbers.ConvertTo
{
    public struct ConverterTo<T>
    {
        public T Value { get; private set; }

        public ConverterTo(T value) : this()
        {
            Value = value;
        }

        public T2 To<T2>()
        {
            return ConvertToUtil<T, T2>.ConvertTo(Value);
        }
    }
}


text:
CGCU Wordpress Theme
===============

This repository holds the legacy theme for the [CGCU Website](http://www.cgcu.net).


text:
<?php

namespace Doctrine\Tests\Common\Cache;

use Riak\Bucket;
use Riak\Connection;
use Riak\Exception;
use Doctrine\Common\Cache\CacheProvider;
use Doctrine\Common\Cache\RiakCache;

/**
 * RiakCache test
 *
 * @group Riak
 * @requires extension riak
 */
class RiakCacheTest extends CacheTest
{
    /**
     * @var \Riak\Connection
     */
    private $connection;

    /**
     * @var \Riak\Bucket
     */
    private $bucket;

    protected function setUp() : void
    {
        try {
            $this->connection = new Connection('127.0.0.1', 8087);
            $this->bucket     = new Bucket($this->connection, 'test');
        } catch (Exception\RiakException $e) {
            $this->markTestSkipped('Cannot connect to Riak.');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function testGetStats() : void
    {
        $cache = $this->_getCacheDriver();
        $stats = $cache->getStats();

        self::assertNull($stats);
    }

    /**
     * Retrieve RiakCache instance.
     */
    protected function _getCacheDriver() : CacheProvider
    {
        return new RiakCache($this->bucket);
    }
}