text:
module.exports = function(grunt) {
    'use strict';

    var files = {
        less: {
            './static/dist/css/nano-theme.css': './static/less/nano-theme.less',
            './static/dist/css/source-code.css': './static/less/source-code.less'
        },
        uglify: {
            './static/dist/js/nano-theme.js': [
                './static/bower_components/jquery/dist/jquery.js',
                './static/js/_router.js',
                './static/js/_content.js',
                './static/js/_viewport.js'
            ],
            './static/dist/js/source-code.js': [
                './static/js/prettify/_prettify.js',
                './static/js/prettify/_lang-css.js',
                './static/js/prettify/_linenumber.js'
            ]
        },
        htmlmin: {
            'tmpl/dist/container.tmpl': 'tmpl/container.tmpl',
            'tmpl/dist/details.tmpl': 'tmpl/details.tmpl',
            'tmpl/dist/example.tmpl': 'tmpl/example.tmpl',
            'tmpl/dist/examples.tmpl': 'tmpl/examples.tmpl',
            'tmpl/dist/exceptions.tmpl': 'tmpl/exceptions.tmpl',
            'tmpl/dist/index.tmpl': 'tmpl/index.tmpl',
            'tmpl/dist/mainpage.tmpl': 'tmpl/mainpage.tmpl',
            'tmpl/dist/members.tmpl': 'tmpl/members.tmpl',
            'tmpl/dist/method.tmpl': 'tmpl/method.tmpl',
            'tmpl/dist/params.tmpl': 'tmpl/params.tmpl',
            'tmpl/dist/properties.tmpl': 'tmpl/properties.tmpl',
            'tmpl/dist/returns.tmpl': 'tmpl/returns.tmpl',
            'tmpl/dist/source.tmpl': 'tmpl/source.tmpl',
            'tmpl/dist/tutorial.tmpl': 'tmpl/tutorial.tmpl',
            'tmpl/dist/type.tmpl': 'tmpl/type.tmpl'
        }
    };

    // Config
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        less: {
            dev: {
                files: files.less,
                options: {
                    paths: ['./static/less']
                },
            },
            dist: {
                files: files.less,
                options: {
                    paths: ['./static/less'],
                    compress: true
                }
            }
        },

        uglify: {
            dev: {
                files: files.uglify,
                options: {
                    mangle: false,
                    compress: false,
                    preserveComments: 'all',
                    beautify: true
                }
            },
            dist: {
                files: files.uglify
            }
        },

        htmlmin: {
            dev: {
                files: files.htmlmin
            },
            dist: {
                files: files.htmlmin,
                options: {
                    removeComments: true,
                    collapseWhitespace: true
                }
            }
        },

        watch: {
            stylesheet: {
                files: ['./static/less/*'],
                tasks: ['less:dev', 'example']
            },
            javascript: {
                files: [
                    './static/js/*',
                    './static/js/prettify/*',
                    '!./static/dist/*',
                ],
                tasks: ['uglify:dev', 'example']
            },
            template: {
                files: ['./tmpl/*', './publish.js'],
                tasks: ['htmlmin:dev', 'example']
            }
        }
    });

    // Plugins
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-htmlmin');
    grunt.loadNpmTasks('grunt-contrib-watch');

    // Tasks
    grunt.task.registerTask(
        'example',
        'Generate the example docs. Pass example:default to generate against the default template',
        function(template) {
            var cb = this.async(),
                exec = require('child_process').exec;

            exec('node ../node_modules/jsdoc/jsdoc.js -c '+ (template === 'default' ? 'conf-default.js' : 'conf.json'), {
                maxBuffer: 5000 * 1024,
                cwd: './example'
            }, function(error, stdout, stderr) {
                if (error || stderr) {
                    grunt.log.error(error);
                }
                if (stdout) {
                    grunt.log.writeln(stdout);
                }

                cb();
            });
        }
    );

    grunt.task.registerTask(
        'release',
        'Prepare all the code for release.',
        [
            'less:dist',
            'uglify:dist',
            'htmlmin:dist'
        ]
    );
};


text:
using namespace llvm;
#include "LLVMCompat.h"

namespace {
  struct GNUObjCTypeFeedback : public ModulePass {

    typedef std::pair<CallInst*,CallInst*> callPair;
    typedef std::vector<callPair > replacementVector;
      static char ID;
    uint32_t callsiteCount;
    LLVMIntegerType *Int32Ty;
      GNUObjCTypeFeedback() : ModulePass(ID), callsiteCount(0) {}

    void profileFunction(Function &F, Constant *ModuleID) {
      for (Function::iterator i=F.begin(), e=F.end() ;
                      i != e ; ++i) {

        Module *M = F.getParent();
        replacementVector replacements;
        for (BasicBlock::iterator b=i->begin(), last=i->end() ;
            b != last ; ++b) {

          CallSite call(b);
          if (call.getInstruction() && !call.getCalledFunction()) {
            llvm::SmallVector<llvm::Value*, 4> args;
            args.push_back(call->getOperand(1));
            args.push_back(call->getOperand(0)),
            args.push_back(ModuleID);
            args.push_back(ConstantInt::get(Int32Ty, callsiteCount++));
            Constant *profile =
                M->getOrInsertFunction("objc_msg_profile",
                  Type::getVoidTy(M->getContext()),
                  args[0]->getType(), args[1]->getType(),
                  args[2]->getType(), args[3]->getType(), NULL);
            CreateCall(profile, args, "", call.getInstruction());
          }
        }
      }
    }

    public:
    virtual bool runOnModule(Module &M)
    {
      LLVMContext &VMContext = M.getContext();
      Int32Ty = IntegerType::get(VMContext, 32);
      LLVMPointerType *PtrTy = Type::getInt8PtrTy(VMContext);
      Constant *moduleName =
        ConstantArray::get(VMContext, M.getModuleIdentifier(), true);
      moduleName = new GlobalVariable(M, moduleName->getType(), true,
          GlobalValue::InternalLinkage, moduleName,
          ".objc_profile_module_name");
      std::vector<Constant*> functions;

      llvm::Constant *Zeros[2];
      Zeros[0] = ConstantInt::get(Type::getInt32Ty(VMContext), 0);
      Zeros[1] = Zeros[0];

      moduleName = ConstantExpr::getGetElementPtr(moduleName, Zeros, 2);
      functions.push_back(moduleName);;
      functions.push_back(moduleName);;

      for (Module::iterator F=M.begin(), e=M.end() ;
        F != e ; ++F) {
        if (F->isDeclaration()) { continue; }
        functions.push_back(ConstantExpr::getBitCast(F, PtrTy));

        Constant * ConstStr =
          llvm::ConstantArray::get(VMContext, F->getName());
        ConstStr = new GlobalVariable(M, ConstStr->getType(), true,
            GlobalValue::PrivateLinkage, ConstStr, "str");
        functions.push_back(
            ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2));

        profileFunction(*F, moduleName);
      }
      functions.push_back(ConstantPointerNull::get(PtrTy));
      Constant *symtab = ConstantArray::get(ArrayType::get(PtrTy,
            functions.size()), functions);
      Value *symbolTable = new GlobalVariable(M, symtab->getType(), true,
          GlobalValue::InternalLinkage, symtab, "symtab");

      Function *init =
        Function::Create(FunctionType::get(Type::getVoidTy(VMContext), false),
            GlobalValue::PrivateLinkage, "load_symbol_table", &M);
      BasicBlock * EntryBB = BasicBlock::Create(VMContext, "entry", init);
      IRBuilder<> B = IRBuilder<>(EntryBB);
      Value *syms = B.CreateStructGEP(symbolTable, 0);
      B.CreateCall(M.getOrInsertFunction("objc_profile_write_symbols",
            Type::getVoidTy(VMContext), syms->getType(), NULL),
          syms);
      B.CreateRetVoid();

      GlobalVariable *GCL = M.getGlobalVariable("llvm.global_ctors");

      std::vector<Constant*> ctors;

      ConstantArray *CA = cast<ConstantArray>(GCL->getInitializer());

      for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
        ctors.push_back(cast<ConstantStruct>(*i));
      }

      // Type of one ctor
      LLVMType *ctorTy =
        cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
      // Add the
      std::vector<Constant*> CSVals;
      CSVals.push_back(ConstantInt::get(Type::getInt32Ty(VMContext),65535));
      CSVals.push_back(init);
      ctors.push_back(GetConstantStruct(GCL->getContext(), CSVals, false));
      // Create the array initializer.
      CA = cast<ConstantArray>(ConstantArray::get(ArrayType::get(ctorTy,
            ctors.size()), ctors));
      // Create the new global and replace the old one
      GlobalVariable *NGV = new GlobalVariable(CA->getType(),
          GCL->isConstant(), GCL->getLinkage(), CA, "", GCL->isThreadLocal());
      GCL->getParent()->getGlobalList().insert(GCL, NGV);
      NGV->takeName(GCL);
      GCL->replaceAllUsesWith(NGV);
      GCL->eraseFromParent();

      return true;
    }

  };

  char GNUObjCTypeFeedback::ID = 0;
  RegisterPass<GNUObjCTypeFeedback> X("gnu-objc-type-feedback",
      "Objective-C type feedback for the GNU runtime.", false, true);
}

ModulePass *createTypeFeedbackPass(void) {
  return new GNUObjCTypeFeedback();
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Open Learning | daniel klotz |</title>
    <link rel="stylesheet" href="/css/style.css" />
    <link rel="stylesheet" href="/css/fonts.css" />

·

    hi ·

    notes ·

    gfx ·

    me ·

Open Learning

Here I share sources for autonomous learning on the internet. The idea is by and large inspired by Una Kravets.

In high school I had the epiphany that it is better to follow good teachers thengood topics. Throughout my studies I tried to follow that maxim as good as  possible, but forgot about it until recently. Albeit my pursuits follow topics, I will try to keep this in mind for this list. I prefer to share videos/audio here and not the general sources that one will find anywhere.

1. Conceptual Exploration

Awesome Explorables

Bret Victor: Kill Math

Bret Victor: Explorable Explanations

Bret Victor: Up and Down the Ladder of Abstraction

Claus Mattheck: Die Körpersprache der Bauteile

explorabl.es

Grand Illusions (Youtube Channel)

Hamish Todd: Unintuitive action at a distance in game mechanics and Explorable Explanations

Ken Perlin: On the mind field of virtual and future reality

Michael Nielsen: Thought as Technology

Michael Nielsen: Magic Paper

Negative Evidence

Nicky Case: Explorable Explanations

Nicky Case: How to Simulate the Universe, in 134 Easy Steps

Robin Arnott: Designing a Trance  Meditation and Game Design (GDC)

Tadashi Tokieda: Toy Models

4d Toys

1.1 Generative Stuff

Grammar Variational Autoencoder

Jessica Rosenkrantz: Generative Design

Samim A. Winiger: Genarative Design

UCSC: Generative Methods Day 2017

1.2 Topological Views:

Colah: Neural Networks, Manifolds, and Topology

N.J. Wilderberger: Algebraic Topology - A beginner’s course

Tadashi Tokieda: Topology and Geometry

2. Data Analysis

A Brief History of Data Visualization

Brandon Rohrer: How Support Vector Machines work / How to open a black box

Brian Caffo: Machine learning, the basics

Data Stories Podcast

Kim Rees: The Data Documentary

Lisa Charlotte Rost: A Data Point Walks Into a Bar

2.1 R Specifics

Garrett Grolemund, Hadley Wickham: R for Data Science

Hadley Wickham: PLOTCON 2016 - New open viz in R

Hadley Wickham: Data Science with R

Hadley Wickham: Managing many models with R

Hadley Wickham: Data Science in the Tidyverse

John M. Chambers: Extending R

Not So Standard Deviations

Roger Peng: Analyst Mindset

2.2 Probability

Andrew Gelman: Theoretical Statistics is the Theory of Applied Statistics: How to Think About What We Do

Taleb: Probability Moocs

3. Computational Notebooks

Bret Victor: Explorable Explanations

Distill Journal

Jupyter: Computational Narratives

ouseful: Computational Essays

Wolfram: What is a Computational Essay

Idyll (example)

3.1 Software and Stuff:

Tangle (old now, see this and this)

matbox2 (here is a nice example from jupyter)

jsReact

4. Water and Landscape

Claus Mattheck: Die Körpersprache der Bauteile

Misc

Alan Watts: On Nothingness

Listening to Music

Samwise Didier Interview

Steven Wittens: The Pixel Factory

Two Minute Papers


text:
<?php

namespace Zend\Mail\Storage\Part\Exception;

use Zend\Mail\Storage\Exception\ExceptionInterface as StorageException;

interface ExceptionInterface extends StorageException
{
}


text:
var express = require('express');
var path = require('path');
var bodyparser = require('body-parser');

var isProduction = process.env.NODE_ENV === 'production';
var port = isProduction ? process.env.PORT : 1337;

var routes = require('./server/routes/index');

var app = express();

app.use('/api/v1', routes);

app.use(function(req, res, next){
  var err = new Error('Not found');
  err.status = 404;
  next(err);
});

app.listen(port, function(){
  console.log('Server listening on port ' + port);
});


text:
<?php

declare(strict_types=1);

namespace Sonata\PageBundle\Tests\Page;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Sonata\PageBundle\Model\PageInterface;
use Sonata\PageBundle\Page\PageServiceManager;
use Sonata\PageBundle\Page\Service\PageServiceInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;

final class PageServiceManagerTest extends TestCase
{
    /**
     * @var MockObject&RouterInterface
     */
    protected $router;

    protected PageServiceManager $manager;

    protected function setUp(): void
    {
        $this->router = $this->createMock(RouterInterface::class);
        $this->manager = new PageServiceManager($this->router);
    }

    /**
     * Test adding a new page service.
     */
    public function testAdd(): void
    {
        $service = $this->createMock(PageServiceInterface::class);

        $this->manager->add('default', $service);

        static::assertSame($service, $this->manager->get('default'));
    }

    /**
     * Test getting a service using a page object.
     *
     * @depends testAdd
     */
    public function testGetByPage(): void
    {
        $service = $this->createMock(PageServiceInterface::class);
        $this->manager->add('my-type', $service);

        $page = $this->createMock(PageInterface::class);
        $page->expects(static::once())->method('getType')->willReturn('my-type');

        static::assertSame(
            $service,
            $this->manager->get($page),
            'Should return the page service'
        );
    }

    /**
     * Test getting all page services.
     *
     * @depends testAdd
     */
    public function testGetAll(): void
    {
        $this->manager->add('service1', $service1 = $this->createMock(PageServiceInterface::class));
        $this->manager->add('service2', $service2 = $this->createMock(PageServiceInterface::class));

        static::assertSame(
            ['service1' => $service1, 'service2' => $service2],
            $this->manager->getAll(),
            'Should return all page services'
        );
    }

    /**
     * @depends testAdd
     */
    public function testDefault(): void
    {
        $default = $this->createMock(PageServiceInterface::class);
        $this->manager->setDefault($default);

        static::assertSame(
            $default,
            $this->manager->get('non-existing'),
            'Should return the default page service'
        );
    }

    /**
     * Test the page execution through a service.
     *
     * @depends testDefault
     */
    public function testExecute(): void
    {
        $request = $this->createMock(Request::class);
        $response = $this->createMock(Response::class);

        $page = $this->createMock(PageInterface::class);
        $page->expects(static::once())->method('getType')->willReturn('my-type');

        $service = $this->createMock(PageServiceInterface::class);
        $service->expects(static::once())
            ->method('execute')
            ->with(static::equalTo($page), static::equalTo($request))
            ->willReturn($response);
        $this->manager->add('my-type', $service);

        static::assertSame(
            $response,
            $this->manager->execute($page, $request),
            'Should return a response'
        );
    }
}


text:
package org.smartdeveloperhub.harvesters.ci.backend.enrichment;

final class Counter {

	private final String name;
	private volatile long value;

	Counter(final String name) {
		this.name = name;
		this.value=0;
	}

	long get() {
		return this.value;
	}

	long incrementAndGet() {
		return ++this.value;
	}

	long decrementAndGet() {
		return --this.value;
	}

	@Override
	public String toString() {
		return this.name+": "+this.value;
	}

}


text:
<?php
/**
 * ExampleHook Component
 *
 * An example hook component for demonstrating hook system.
 *
 * @category Component
 * @package  Croogo
 * @version  1.0
 * @author   Nicolas Traeder <traedamatic@gmail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class SitemapComponent extends Component {

}
?>


text:
module ShoppingCart
  class Address < ActiveRecord::Base
  end
end


text:
"""
byceps.services.ticketing.ticket_creation_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from random import sample
from typing import Iterator, Optional, Sequence, Set

from ...database import db
from ...typing import UserID

from ..shop.order.transfer.models import OrderNumber

from .models.ticket import Ticket as DbTicket
from .models.ticket_bundle import TicketBundle as DbTicketBundle
from .transfer.models import TicketCategoryID, TicketCode

def create_ticket(
    category_id: TicketCategoryID,
    owned_by_id: UserID,
    *,
    order_number: Optional[OrderNumber] = None,
) -> Sequence[DbTicket]:
    """Create a single ticket."""
    tickets = create_tickets(
        category_id, owned_by_id, 1, order_number=order_number
    )
    return tickets[0]

def create_tickets(
    category_id: TicketCategoryID,
    owned_by_id: UserID,
    quantity: int,
    *,
    order_number: Optional[OrderNumber] = None,
) -> Sequence[DbTicket]:
    """Create a number of tickets of the same category for a single owner."""
    tickets = list(
        build_tickets(
            category_id, owned_by_id, quantity, order_number=order_number
        )
    )

    db.session.add_all(tickets)
    db.session.commit()

    return tickets

def build_tickets(
    category_id: TicketCategoryID,
    owned_by_id: UserID,
    quantity: int,
    *,
    bundle: Optional[DbTicketBundle] = None,
    order_number: Optional[OrderNumber] = None,
) -> Iterator[DbTicket]:
    if quantity < 1:
        raise ValueError('Ticket quantity must be positive.')

    codes: Set[TicketCode] = set()

    for _ in range(quantity):
        code = _generate_ticket_code_not_in(codes)
        codes.add(code)

        yield DbTicket(
            code,
            category_id,
            owned_by_id,
            bundle=bundle,
            order_number=order_number,
        )

_CODE_ALPHABET = 'BCDFGHJKLMNPQRSTVWXYZ'
_CODE_LENGTH = 5

def _generate_ticket_code() -> TicketCode:
    """Generate a ticket code.

    Generated codes are not necessarily unique!
    """
    return TicketCode(''.join(sample(_CODE_ALPHABET, _CODE_LENGTH)))

def _generate_ticket_code_not_in(codes: Set[TicketCode]) -> TicketCode:
    """Generate ticket codes and return the first one not in the set."""
    while True:
        code = _generate_ticket_code()
        if code not in codes:
            return code


text:
/**
 *
 */
package chess.figures;

import chess.IChessboard;
import chess.IChessboard.Player;
import chess.Position;

/**
 * @author jan
 *
 */
public abstract class RunningFigure extends Figure {

	/**
	 * @param player
	 * @param position
	 * @param chessboard
	 */
	public RunningFigure(Player player, Position position,
			IChessboard chessboard) {
		super(player, position, chessboard);
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see chess.figures.Figure#setReachablePositions()
	 */
	public void setReachablePositions(int x, int y) {

	}

}


text:
package net.automatalib.settingssources;

import net.automatalib.AutomataLibSettingsSource;
import net.automatalib.commons.util.settings.AbstractClassPathFileSource;
import org.kohsuke.MetaInfServices;

@MetaInfServices(AutomataLibSettingsSource.class)
public class AutomataLibPropertiesSource extends AbstractClassPathFileSource implements AutomataLibSettingsSource {

    public AutomataLibPropertiesSource() {
        super("automatalib.properties");
    }
}


text:
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.Internal;

namespace System.ComponentModel.Composition.ReflectionModel
{
    public static class ReflectionModelServices
    {
        public static Lazy<Type> GetPartType(ComposablePartDefinition partDefinition)
        {
            Requires.NotNull(partDefinition, nameof(partDefinition));
            Contract.Ensures(Contract.Result<Lazy<Type>>() != null);

            ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
            if (reflectionPartDefinition == null)
            {
                throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType());
            }

            return reflectionPartDefinition.GetLazyPartType();
        }

        public static bool IsDisposalRequired(ComposablePartDefinition partDefinition)
        {
            Requires.NotNull(partDefinition, nameof(partDefinition));

            ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
            if (reflectionPartDefinition == null)
            {
                throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType());
            }

            return reflectionPartDefinition.IsDisposalRequired;
        }

        public static LazyMemberInfo GetExportingMember(ExportDefinition exportDefinition)
        {
            Requires.NotNull(exportDefinition, nameof(exportDefinition));

            ReflectionMemberExportDefinition reflectionExportDefinition = exportDefinition as ReflectionMemberExportDefinition;
            if (reflectionExportDefinition == null)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidExportDefinition, exportDefinition.GetType()),
                    nameof(exportDefinition));
            }

            return reflectionExportDefinition.ExportingLazyMember;
        }

        public static LazyMemberInfo GetImportingMember(ImportDefinition importDefinition)
        {
            Requires.NotNull(importDefinition, nameof(importDefinition));

            ReflectionMemberImportDefinition reflectionMemberImportDefinition = importDefinition as ReflectionMemberImportDefinition;
            if (reflectionMemberImportDefinition == null)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidMemberImportDefinition, importDefinition.GetType()),
                    nameof(importDefinition));
            }

            return reflectionMemberImportDefinition.ImportingLazyMember;
        }

        public static Lazy<ParameterInfo> GetImportingParameter(ImportDefinition importDefinition)
        {
            Requires.NotNull(importDefinition, nameof(importDefinition));
            Contract.Ensures(Contract.Result<Lazy<ParameterInfo>>() != null);

            ReflectionParameterImportDefinition reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition;
            if (reflectionParameterImportDefinition == null)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidParameterImportDefinition, importDefinition.GetType()),
                    nameof(importDefinition));
            }

            return reflectionParameterImportDefinition.ImportingLazyParameter;
        }

        public static bool IsImportingParameter(ImportDefinition importDefinition)
        {
            Requires.NotNull(importDefinition, nameof(importDefinition));

            ReflectionImportDefinition reflectionImportDefinition = importDefinition as ReflectionImportDefinition;
            if (reflectionImportDefinition == null)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
                    nameof(importDefinition));
            }

            return (importDefinition is ReflectionParameterImportDefinition);
        }

        public static bool IsExportFactoryImportDefinition(ImportDefinition importDefinition)
        {
            Requires.NotNull(importDefinition, nameof(importDefinition));

            return (importDefinition is IPartCreatorImportDefinition);
        }

        public static ContractBasedImportDefinition GetExportFactoryProductImportDefinition(ImportDefinition importDefinition)
        {
            Requires.NotNull(importDefinition, nameof(importDefinition));
            Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null);

            IPartCreatorImportDefinition partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition;
            if (partCreatorImportDefinition == null)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
                    nameof(importDefinition));
            }

            return partCreatorImportDefinition.ProductImportDefinition;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static ComposablePartDefinition CreatePartDefinition(
            Lazy<Type> partType,
            bool isDisposalRequired,
            Lazy<IEnumerable<ImportDefinition>> imports,
            Lazy<IEnumerable<ExportDefinition>> exports,
            Lazy<IDictionary<string, object>> metadata,
            ICompositionElement origin)
        {
            Requires.NotNull(partType, nameof(partType));
            Contract.Ensures(Contract.Result<ComposablePartDefinition>() != null);

            return new ReflectionComposablePartDefinition(
                new ReflectionPartCreationInfo(
                    partType,
                    isDisposalRequired,
                    imports,
                    exports,
                    metadata,
                    origin));
        }

        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static ExportDefinition CreateExportDefinition(
            LazyMemberInfo exportingMember,
            string contractName,
            Lazy<IDictionary<string, object>> metadata,
            ICompositionElement origin)
        {
            Requires.NotNullOrEmpty(contractName, nameof(contractName));
            Requires.IsInMembertypeSet(exportingMember.MemberType, nameof(exportingMember), MemberTypes.Field | MemberTypes.Property | MemberTypes.NestedType | MemberTypes.TypeInfo | MemberTypes.Method);
            Contract.Ensures(Contract.Result<ExportDefinition>() != null);

            return new ReflectionMemberExportDefinition(
                exportingMember,
                new LazyExportDefinition(contractName, metadata),
                origin);
        }

        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static ContractBasedImportDefinition CreateImportDefinition(
            LazyMemberInfo importingMember,
            string contractName,
            string requiredTypeIdentity,
            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
            ImportCardinality cardinality,
            bool isRecomposable,
            CreationPolicy requiredCreationPolicy,
            ICompositionElement origin)
        {
            return CreateImportDefinition(importingMember, contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, requiredCreationPolicy, MetadataServices.EmptyMetadata, false, origin);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static ContractBasedImportDefinition CreateImportDefinition(
            LazyMemberInfo importingMember,
            string contractName,
            string requiredTypeIdentity,
            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
            ImportCardinality cardinality,
            bool isRecomposable,
            CreationPolicy requiredCreationPolicy,
            IDictionary<string, object> metadata,
            bool isExportFactory,
            ICompositionElement origin)
        {
            return CreateImportDefinition(
                importingMember,
                contractName,
                requiredTypeIdentity,
                requiredMetadata,
                cardinality,
                isRecomposable,
                false,
                requiredCreationPolicy,
                metadata,
                isExportFactory,
                origin);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static ContractBasedImportDefinition CreateImportDefinition(
            LazyMemberInfo importingMember,
            string contractName,
            string requiredTypeIdentity,
            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
            ImportCardinality cardinality,
            bool isRecomposable,
            bool isPreRequisite,
            CreationPolicy requiredCreationPolicy,
            IDictionary<string, object> metadata,
            bool isExportFactory,
            ICompositionElement origin)
        {
            Requires.NotNullOrEmpty(contractName, nameof(contractName));
            Requires.IsInMembertypeSet(importingMember.MemberType, nameof(importingMember), MemberTypes.Property | MemberTypes.Field);
            Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null);

            if (isExportFactory)
            {
                return new PartCreatorMemberImportDefinition(
                    importingMember,
                    origin,
                    new ContractBasedImportDefinition(
                        contractName,
                        requiredTypeIdentity,
                        requiredMetadata,
                        cardinality,
                        isRecomposable,
                        isPreRequisite,
                        CreationPolicy.NonShared,
                        metadata));
            }
            else
            {
                return new ReflectionMemberImportDefinition(
                    importingMember,
                    contractName,
                    requiredTypeIdentity,
                    requiredMetadata,
                    cardinality,
                    isRecomposable,
                    isPreRequisite,
                    requiredCreationPolicy,
                    metadata,
                    origin);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static ContractBasedImportDefinition CreateImportDefinition(
            Lazy<ParameterInfo> parameter,
            string contractName,
            string requiredTypeIdentity,
            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
            ImportCardinality cardinality,
            CreationPolicy requiredCreationPolicy,
            ICompositionElement origin)
        {
            return CreateImportDefinition(parameter, contractName, requiredTypeIdentity, requiredMetadata, cardinality, requiredCreationPolicy, MetadataServices.EmptyMetadata, false, origin);
        }

        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static ContractBasedImportDefinition CreateImportDefinition(
            Lazy<ParameterInfo> parameter,
            string contractName,
            string requiredTypeIdentity,
            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
            ImportCardinality cardinality,
            CreationPolicy requiredCreationPolicy,
            IDictionary<string, object> metadata,
            bool isExportFactory,
            ICompositionElement origin)
        {
            Requires.NotNull(parameter, nameof(parameter));
            Requires.NotNullOrEmpty(contractName, nameof(contractName));
            Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null);

            if (isExportFactory)
            {
                return new PartCreatorParameterImportDefinition(
                    parameter,
                    origin,
                    new ContractBasedImportDefinition(
                        contractName,
                        requiredTypeIdentity,
                        requiredMetadata,
                        cardinality,
                        false,
                        true,
                        CreationPolicy.NonShared,
                        metadata));
            }
            else
            {
                return new ReflectionParameterImportDefinition(
                    parameter,
                    contractName,
                    requiredTypeIdentity,
                    requiredMetadata,
                    cardinality,
                    requiredCreationPolicy,
                    metadata,
                    origin);
            }
        }

        public static bool TryMakeGenericPartDefinition(ComposablePartDefinition partDefinition, IEnumerable<Type> genericParameters, out ComposablePartDefinition specialization)
        {
            Requires.NotNull(partDefinition, nameof(partDefinition));

            specialization = null;
            ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
            if (reflectionPartDefinition == null)
            {
                throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType());
            }

            return reflectionPartDefinition.TryMakeGenericPartDefinition(genericParameters.ToArray(), out specialization);
        }
    }

internal class ReflectionPartCreationInfo : IReflectionPartCreationInfo
    {
        private readonly Lazy<Type> _partType;
        private readonly Lazy<IEnumerable<ImportDefinition>> _imports;
        private readonly Lazy<IEnumerable<ExportDefinition>> _exports;
        private readonly Lazy<IDictionary<string, object>> _metadata;
        private readonly ICompositionElement _origin;
        private ConstructorInfo _constructor;
        private bool _isDisposalRequired;

        public ReflectionPartCreationInfo(
            Lazy<Type> partType,
            bool isDisposalRequired,
            Lazy<IEnumerable<ImportDefinition>> imports,
            Lazy<IEnumerable<ExportDefinition>> exports,
            Lazy<IDictionary<string, object>> metadata,
            ICompositionElement origin)
        {
            if (partType == null)
            {
                throw new ArgumentNullException(nameof(partType));
            }

            _partType = partType;
            _isDisposalRequired = isDisposalRequired;
            _imports = imports;
            _exports = exports;
            _metadata = metadata;
            _origin = origin;
        }

        public Type GetPartType()
        {
            return _partType.GetNotNullValue("type");
        }

        public Lazy<Type> GetLazyPartType()
        {
            return _partType;
        }

        public ConstructorInfo GetConstructor()
        {
            if (_constructor == null)
            {
                ConstructorInfo[] constructors = null;
                constructors = GetImports()
                    .OfType<ReflectionParameterImportDefinition>()
                    .Select(parameterImport => parameterImport.ImportingLazyParameter.Value.Member)
                    .OfType<ConstructorInfo>()
                    .Distinct()
                    .ToArray();

                if (constructors.Length == 1)
                {
                    _constructor = constructors[0];
                }
                else if (constructors.Length == 0)
                {
                    _constructor = GetPartType().GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                }
            }
            return _constructor;
        }

        public bool IsDisposalRequired
        {
            get
            {
                return _isDisposalRequired;
            }
        }

        public bool IsIdentityComparison
        {
            get
            {
                return true;
            }
        }

        public IDictionary<string, object> GetMetadata()
        {
            return (_metadata != null) ? _metadata.Value : null;
        }

        public IEnumerable<ExportDefinition> GetExports()
        {
            if (_exports == null)
            {
                yield break;
            }

            IEnumerable<ExportDefinition> exports = _exports.Value;

            if (exports == null)
            {
                yield break;
            }

            foreach (ExportDefinition export in exports)
            {
                ReflectionMemberExportDefinition reflectionExport = export as ReflectionMemberExportDefinition;
                if (reflectionExport == null)
                {
                    throw new InvalidOperationException(
                        string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidExportDefinition, export.GetType()));
                }
                yield return reflectionExport;
            }
        }

        public IEnumerable<ImportDefinition> GetImports()
        {
            if (_imports == null)
            {
                yield break;
            }

            IEnumerable<ImportDefinition> imports = _imports.Value;

            if (imports == null)
            {
                yield break;
            }

            foreach (ImportDefinition import in imports)
            {
                ReflectionImportDefinition reflectionImport = import as ReflectionImportDefinition;
                if (reflectionImport == null)
                {
                    throw new InvalidOperationException(
                        string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidMemberImportDefinition, import.GetType()));
                }
                yield return reflectionImport;
            }
        }

        public string DisplayName
        {
            get { return GetPartType().GetDisplayName(); }
        }

        public ICompositionElement Origin
        {
            get { return _origin; }
        }
    }

    internal class LazyExportDefinition : ExportDefinition
    {
        private readonly Lazy<IDictionary<string, object>> _metadata;

        public LazyExportDefinition(string contractName, Lazy<IDictionary<string, object>> metadata)
            : base(contractName, (IDictionary<string, object>)null)
        {
            _metadata = metadata;
        }

        public override IDictionary<string, object> Metadata
        {
            get
            {
                return _metadata.Value ?? MetadataServices.EmptyMetadata;
            }
        }
    }
}


text:
/**
 *
 */
package it.wt;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author kurs
 *
 */
public class MyFrame extends JFrame {
	private JTextField txtBlabla;

	public MyFrame() {
		setAlwaysOnTop(true);
		setTitle("Schach");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(10, 10, 910, 910);
		getContentPane().setLayout(null);
		txtBlabla = new JTextField();
		txtBlabla.setBounds(30, 30, 894, 20);
		txtBlabla.setText("blabla");
		getContentPane().add(txtBlabla);
		txtBlabla.setColumns(10);

		JSplitPane splitPane = new JSplitPane();
		splitPane.setBounds(0, 846, 894, 25);
		getContentPane().add(splitPane);

		final JLabel lblLabel = new JLabel("Label");
		lblLabel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				System.out.println("mouse hat Label geklickt");
				lblLabel.setText("geklicktes Label");
			}
		});
		JButton btnOk = new JButton("ok");

		btnOk.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				System.out.println("mouse hat Label geklickt");
				lblLabel.setText("geklicktes Label");
			}
		});
		btnOk.setBounds(74, 741, 820, 23);
		getContentPane().add(btnOk);

		JButton btnNiemals = new JButton("niemals");
		btnNiemals.setBounds(429, 775, 67, 23);
		getContentPane().add(btnNiemals);

		lblLabel.setBounds(59, 63, 46, 14);
		getContentPane().add(lblLabel);
		btnNiemals.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		});

		setVisible(true);
	}

	public static void main(String[] args) {

		new MyFrame();

	}
}


text:
{% load i18n %}

{{transition|capfirst}} contributed time

    {{transition|capfirst}} the contributed time by {{users.0.full_name}}

    {% if users|length > 1 %}
        {% blocktrans with extra=users|length|add:"-1" %}
            and {{ extra }} others
        {% endblocktrans %}
    {% endif %}


text:
export default function dasherizer(string){
  return string.split(', ').join('-').split(' ').join('_').toLowerCase();
}


text:
package cn.elvea.platform.lxp.activity.service;

/**
 * 课程服务
 *
 * @author elvea
 * @since 0.0.1
 */
public interface CourseService {
}


text:
rafavalerio.com
========

Personal website/blog! :)


text:
#pragma once

#include <rtabmap/utilite/UEvent.h>
#include "rtabmap/core/SensorData.h"

namespace rtabmap
{

class CameraEvent :
	public UEvent
{
public:
	enum Code {
		kCodeData,
		kCodeNoMoreImages
	};

public:
	CameraEvent(const cv::Mat & image, int seq=0, double stamp = 0.0, const std::string & cameraName = "") :
		UEvent(kCodeData),
		data_(image, seq, stamp),
		cameraName_(cameraName)
	{
	}

	CameraEvent() :
		UEvent(kCodeNoMoreImages)
	{
	}

	CameraEvent(const SensorData & data, const std::string & cameraName = "") :
		UEvent(kCodeData),
		data_(data),
		cameraName_(cameraName)
	{
	}

	// Image or descriptors
	const SensorData & data() const {return data_;}
	const std::string & cameraName() const {return cameraName_;}

	virtual ~CameraEvent() {}
	virtual std::string getClassName() const {return std::string("CameraEvent");}

private:
	SensorData data_;
	std::string cameraName_;
};

} // namespace rtabmap


text:
<?php

    include "../Class/TemplatePage.php";
    session_start();

    $objUtilities=$_SESSION['objUtilities'];
    $objTemplate =new TemplatePage($objUtilities);
    $objTemplate->initTemplate('nabu','event');

?>


text:
namespace PivotalTrackerDotNet.Domain
{
    public enum AccountPermissions
    {
        None,
        ProjectCreation,
        TimeKeeping,
        TimeEntering,
        Administration
    }
}


text:
package unit_tests;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import logging.OutputLogger;
import output.OutputHandler;

public class OutputHandlerTests {

	private OutputHandler testOH;
	private File outputFile;
	private String[][] scheduleStr;

	@Before
	public void setUp() {

		// initialize a mock schedule to write to a file
		String[][] schedule = {{"Week", "Topic", "Monday", "Oral Presentation Speakers", "", "Wednesday", "Debate Plaintiffs", "Debate Defendants", "", "Friday", "Essays Due"},
				{"3", "Bionics", "41531", "James and John", "", "9/16/2013", "William and Patricia", "Charles", "", "9/18/2013", "\"Donald, Daniel, David, Mary, Joseph, Michael, Mark\""},
				{"4", "Copyright", "9/21/2013", "Robert", "", "9/23/2013", "Richard and Christopher", "George and Thomas", "", "9/25/2013", "\"Kenneth, Mary, Patricia, William\""},
				{"5", "Race and Gender Equality in Tech", "9/28/2013", "Michael", "", "9/30/2013", "Daniel and Mark", "Joseph and Donald", "", "10/2/2013", "\"Richard, Christopher, Charles, Thomas, Patricia, George\""},
				{"6", "Society of Leisure", "10/5/2013", "William and David", "", "10/7/2013", "Robert and George", "Mary and Kenneth", "", "10/9/2013", "\"Richard, Donald, Christopher, Charles, Daniel, James, Joseph, Thomas, John, Mark\""},
				{"7", "Privacy", "10/12/2013", "Richard", "", "10/14/2013", "James and Thomas", "Daniel", "", "10/16/2013", "\"Donald, Kenneth, Patricia, John, George, Mark\""},
				{"8", "", "10/19/2013", "FALL BREAK", "", "10/21/2013", "FALL", "BREAK", "", "10/23/2013", ""},
				{"9", "AI Effect on Society", "10/26/2013", "Charles and Joseph", "", "10/28/2013", "David and Christopher", "John", "", "10/30/2013", "\"Daniel, Mary, James, Patricia, Robert, Michael\""},
				{"10", "Net Neutrality", "11/2/2013", "Thomas", "", "11/4/2013", "Donald and Kenneth", "Michael and Mark", "", "11/6/2013", "\"Mary, Robert, George, William\""},
				{"11", "Changing Educational Needs", "11/9/2013", "Christopher and Daniel", "", "11/11/2013", "Patricia and Richard", "James", "", "11/13/2013", "\"Kenneth, David, John, William\""},
				{"12", "Hacktivism", "11/16/2013", "Mary and Mark", "", "11/18/2013", "Michael", "Robert", "", "11/20/2013", "\"Richard, Donald, Kenneth, Charles, David, Joseph, John, George, William\""},
				{"13", "Internet of Things", "11/23/2013", "Donald and Patricia", "", "11/25/2013", "Thanksgiving", "Break", "", "11/27/2013", "\"Christopher, Charles, David, James, Joseph, Thomas, Robert, Michael\""},
				{"14", "Digital Currency and the Dark Net", "11/30/2013", "George and Kenneth", "", "12/2/2013", "Joseph and John", "William", "", "12/4/2013", "\"Richard, Christopher, Daniel, James, Thomas, Robert, Michael, Mark\""},
				{"15", "", "12/7/2013", "(Exception - Debates on this day)", "", "(Exception)", "Charles and Mary", "David", "", "", ""}};

		// save a reference to the mock schedule
		scheduleStr = schedule;

		// The file to output the test schedule to
		outputFile = new File("unitTest_OutputHandler.csv");

		// Get a reference to the OutputHandler
		testOH = new OutputHandler(scheduleStr, outputFile, new OutputLogger());

		// Write the schedule to a CSV file
		testOH.writeScheduleToCSV();

	}

	@After
	public void tearDown(){
		testOH = null;
		outputFile = null;
		scheduleStr = null;
	}

	@Test
	public void testOutputHandlerNotNull() {
		assertNotNull("Unit test output handler not found or output is null!", testOH);
	}

	@Test
	public void testOutputFileExists() {
		assertTrue("Unit test output does not exist!", outputFile.exists());
	}

	@Test
	public void testOutputFileContents() {
		Scanner scanner;
		try {
			scanner = new Scanner(outputFile);
			List<String> fileContents = new ArrayList<>();
			while(scanner.hasNextLine()){
				fileContents.add(scanner.nextLine());
			}
			scanner.close();

			for (String[] row : scheduleStr){
				for (String cell : row){
					boolean containsCell = false;
					for(String str: fileContents) {
					    if (str.contains(cell)){
					    	containsCell = true;
					    	break;
					    }
					}
					if (!containsCell){
						assertTrue("Unit test file contents are incorrect!", containsCell);
						return;
					}
				}
			}
		} catch (FileNotFoundException e) {
			assertTrue("Unit test failed to open the output file to verify contents!", false);
		}
	}
}


text:
package facebook

import (
	"bytes"
	"encoding/json"
	"fmt"
	"reflect"
	"runtime"
	"strconv"
	"strings"
)

// Makes a Result from facebook Graph API response.
func MakeResult(jsonBytes []byte) (Result, error) {
	var res Result

	if bytes.Equal(jsonBytes, facebookSuccessJsonBytes) {
		return Result{}, nil
	}

	err := json.Unmarshal(jsonBytes, &res)

	if err != nil {
		err = fmt.Errorf("cannot format facebook response. %v", err)
		return nil, err
	}

	// facebook may return an error
	return res, res.Err()
}

// Gets a field.
//
// Field can be a dot separated string.
// If field name is "a.b.c", it will try to return value of res["a"]["b"]["c"].
//
// To access array items, use index value in field.
// For instance, field "a.0.c" means to read res["a"][0]["c"].
//
// It doesn't work with Result which has a key contains dot. Use GetField in this case.
//
// Returns nil if field doesn't exist.
func (res Result) Get(field string) interface{} {
	if field == "" {
		return res
	}

	f := strings.Split(field, ".")
	return res.get(f)
}

// Gets a field.
//
// Arguments are treated as keys to access value in Result.
// If arguments are "a","b","c", it will try to return value of res["a"]["b"]["c"].
//
// To access array items, use index value as a string.
// For instance, args of "a", "0", "c" means to read res["a"][0]["c"].
//
// Returns nil if field doesn't exist.
func (res Result) GetField(fields ...string) interface{} {
	if len(fields) == 0 {
		return res
	}

	return res.get(fields)
}

func (res Result) get(fields []string) interface{} {
	v, ok := res[fields[0]]

	if !ok || v == nil {
		return nil
	}

	if len(fields) == 1 {
		return v
	}

	value := getValueField(reflect.ValueOf(v), fields[1:])

	if !value.IsValid() {
		return nil
	}

	return value.Interface()
}

func getValueField(value reflect.Value, fields []string) reflect.Value {
	valueType := value.Type()
	kind := valueType.Kind()
	field := fields[0]

	switch kind {
	case reflect.Array, reflect.Slice:
		// field must be a number.
		n, err := strconv.ParseUint(field, 10, 0)

		if err != nil {
			return reflect.Value{}
		}

		if n >= uint64(value.Len()) {
			return reflect.Value{}
		}

		// work around a reflect package pitfall.
		value = reflect.ValueOf(value.Index(int(n)).Interface())

	case reflect.Map:
		v := value.MapIndex(reflect.ValueOf(field))

		if !v.IsValid() {
			return v
		}

		// get real value type.
		value = reflect.ValueOf(v.Interface())

	default:
		return reflect.Value{}
	}

	if len(fields) == 1 {
		return value
	}

	return getValueField(value, fields[1:])
}

// Decodes full result to a struct.
// It only decodes fields defined in the struct.
//
// As all facebook response fields are lower case strings,
// Decode will convert all camel-case field names to lower case string.
// e.g. field name "FooBar" will be converted to "foo_bar".
// The side effect is that if a struct has 2 fields with only capital
// differences, decoder will map these fields to a same result value.
//
// If a field is missing in the result, Decode keeps it unchanged by default.
//
// Decode can read struct field tag value to change default behavior.
//
// Examples:
//
//     type Foo struct {
//         // "id" must exist in response. note the leading comma.
//         Id string `facebook:",required"`
//
//         // use "name" as field name in response.
//         TheName string `facebook:"name"`
//     }
//
// To change default behavior, set a struct tag `facebook:",required"` to fields
// should not be missing.
//
// Returns error if v is not a struct or any required v field name absents in res.
func (res Result) Decode(v interface{}) (err error) {
	defer func() {
		if r := recover(); r != nil {
			if _, ok := r.(runtime.Error); ok {
				panic(r)
			}

			err = r.(error)
		}
	}()

	err = res.decode(reflect.ValueOf(v), "")
	return
}

// Decodes a field of result to any type, including struct.
// Field name format is defined in Result.Get().
//
// More details about decoding struct see Result.Decode().
func (res Result) DecodeField(field string, v interface{}) error {
	f := res.Get(field)

	if f == nil {
		return fmt.Errorf("field '%v' doesn't exist in result.", field)
	}

	return decodeField(reflect.ValueOf(f), reflect.ValueOf(v), field)
}

// Checks if Result is a Graph API error.
// Returns nil if Result is not an error.
//
// The returned error can be converted to Error by type assertion.
//     err := res.Err()
//     if err != nil {
//         if e, ok := err.(*Error); ok {
//             // read more details in e.Message, e.Code and e.Type
//         }
//     }
//
// For more information about Graph API Errors, see
// https://developers.facebook.com/docs/reference/api/errors/
func (res Result) Err() error {
	var err Error
	e := res.DecodeField("error", &err)

	// no "error" in result. result is not an error.
	if e != nil {
		return nil
	}

	// code may be missing in error.
	// assign a non-zero value to it.
	if err.Code == 0 {
		err.Code = ERROR_CODE_UNKNOWN
	}

	return &err
}

// Creates a PagingResult for this Result.
// Returns error if the Result cannot be used for paging.
//
// Facebook uses following JSON structure to response paging information.
// If "data" doesn't present in Result, Paging will return error.
//     {
//         "data": [...],
//         "paging": {
//             "previous": "https://graph.facebook.com/...",
//             "next": "https://graph.facebook.com/..."
//         }
//     }
func (res Result) Paging(session *Session) (*PagingResult, error) {
	return newPagingResult(session, res)
}

func (res Result) decode(v reflect.Value, fullName string) error {
	for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
		v = v.Elem()
	}

	if v.Kind() != reflect.Struct {
		return fmt.Errorf("output value must be a struct.")
	}

	if !v.CanSet() {
		return fmt.Errorf("output value cannot be set.")
	}

	if fullName != "" {
		fullName += "."
	}

	var field reflect.Value
	var name, fbTag string
	var val interface{}
	var ok, required bool
	var err error

	vType := v.Type()
	num := vType.NumField()

	for i := 0; i < num; i++ {
		name = ""
		required = false
		field = v.Field(i)
		fbTag = vType.Field(i).Tag.Get("facebook")

		// parse struct field tag
		if fbTag != "" {
			index := strings.IndexRune(fbTag, ',')

			if index == -1 {
				name = fbTag
			} else {
				name = fbTag[:index]

				if fbTag[index:] == ",required" {
					required = true
				}
			}
		}

		if name == "" {
			name = camelCaseToUnderScore(v.Type().Field(i).Name)
		}

		val, ok = res[name]

		if !ok {
			// check whether the field is required. if so, report error.
			if required {
				return fmt.Errorf("cannot find field '%v%v' in result.", fullName, name)
			}

			continue
		}

		if err = decodeField(reflect.ValueOf(val), field, fmt.Sprintf("%v%v", fullName, name)); err != nil {
			return err
		}
	}

	return nil
}

func decodeField(val reflect.Value, field reflect.Value, fullName string) error {
	if field.Kind() == reflect.Ptr {
		if field.IsNil() {
			field.Set(reflect.New(field.Type().Elem()))
		}

		field = field.Elem()
	}

	if !field.CanSet() {
		return fmt.Errorf("field '%v' cannot be decoded. make sure the output value is able to be set.", fullName)
	}

	kind := field.Kind()
	valType := val.Type()

	switch kind {
	case reflect.Bool:
		if valType.Kind() == reflect.Bool {
			field.SetBool(val.Bool())
		} else {
			return fmt.Errorf("field '%v' is not a bool in result.", fullName)
		}

	case reflect.Int8:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < -128 || n > 127 {
				return fmt.Errorf("field '%v' value exceeds the range of int8.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 127 {
				return fmt.Errorf("field '%v' value exceeds the range of int8.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < -128 || n > 127 {
				return fmt.Errorf("field '%v' value exceeds the range of int8.", fullName)
			}

			field.SetInt(int64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Int16:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < -32768 || n > 32767 {
				return fmt.Errorf("field '%v' value exceeds the range of int16.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 32767 {
				return fmt.Errorf("field '%v' value exceeds the range of int16.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < -32768 || n > 32767 {
				return fmt.Errorf("field '%v' value exceeds the range of int16.", fullName)
			}

			field.SetInt(int64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Int32:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < -2147483648 || n > 2147483647 {
				return fmt.Errorf("field '%v' value exceeds the range of int32.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 2147483647 {
				return fmt.Errorf("field '%v' value exceeds the range of int32.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < -2147483648 || n > 2147483647 {
				return fmt.Errorf("field '%v' value exceeds the range of int32.", fullName)
			}

			field.SetInt(int64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Int64:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()
			field.SetInt(n)

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 9223372036854775807 {
				return fmt.Errorf("field '%v' value exceeds the range of int64.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < -9223372036854775808 || n > 9223372036854775807 {
				return fmt.Errorf("field '%v' value exceeds the range of int64.", fullName)
			}

			field.SetInt(int64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Int:
		bits := field.Type().Bits()

		var min, max int64

		if bits == 32 {
			min = -2147483648
			max = 2147483647
		} else if bits == 64 {
			min = -9223372036854775808
			max = 9223372036854775807
		}

		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < min || n > max {
				return fmt.Errorf("field '%v' value exceeds the range of int.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > uint64(max) {
				return fmt.Errorf("field '%v' value exceeds the range of int.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < float64(min) || n > float64(max) {
				return fmt.Errorf("field '%v' value exceeds the range of int.", fullName)
			}

			field.SetInt(int64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint8:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 || n > 0xFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint8.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 0xFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint8.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > 0xFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint8.", fullName)
			}

			field.SetUint(uint64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint16:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 || n > 0xFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint16.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 0xFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint16.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > 0xFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint16.", fullName)
			}

			field.SetUint(uint64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint32:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 || n > 0xFFFFFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint32.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 0xFFFFFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint32.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > 0xFFFFFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint32.", fullName)
			}

			field.SetUint(uint64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint64:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 {
				return fmt.Errorf("field '%v' value exceeds the range of uint64.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()
			field.SetUint(n)

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > 0xFFFFFFFFFFFFFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint64.", fullName)
			}

			field.SetUint(uint64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint:
		bits := field.Type().Bits()

		var max uint64

		if bits == 32 {
			max = 0xFFFFFFFF
		} else if bits == 64 {
			max = 0xFFFFFFFFFFFFFFFF
		}

		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 || uint64(n) > max {
				return fmt.Errorf("field '%v' value exceeds the range of uint.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > max {
				return fmt.Errorf("field '%v' value exceeds the range of uint.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > float64(max) {
				return fmt.Errorf("field '%v' value exceeds the range of uint.", fullName)
			}

			field.SetUint(uint64(n))

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Float32, reflect.Float64:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()
			field.SetFloat(float64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()
			field.SetFloat(float64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()
			field.SetFloat(n)

		default:
			return fmt.Errorf("field '%v' is not a float in result.", fullName)
		}

	case reflect.String:
		if valType.Kind() != reflect.String {
			return fmt.Errorf("field '%v' is not a string in result.", fullName)
		}

		field.SetString(val.String())

	case reflect.Struct:
		if valType.Kind() != reflect.Map || valType.Key().Kind() != reflect.String {
			return fmt.Errorf("field '%v' is not a json object in result.", fullName)
		}

		// safe convert val to Result. type assertion doesn't work in this case.
		var r Result
		reflect.ValueOf(&r).Elem().Set(val)

		if err := r.decode(field, fullName); err != nil {
			return err
		}

	case reflect.Map:
		if valType.Kind() != reflect.Map || valType.Key().Kind() != reflect.String {
			return fmt.Errorf("field '%v' is not a json object in result.", fullName)
		}

		// map key must be string
		if field.Type().Key().Kind() != reflect.String {
			return fmt.Errorf("field '%v' in struct is a map with non-string key type. it's not allowed.", fullName)
		}

		var needAddr bool
		valueType := field.Type().Elem()

		// shortcut for map[string]interface{}.
		if valueType.Kind() == reflect.Interface {
			field.Set(val)
			break
		}

		if field.IsNil() {
			field.Set(reflect.MakeMap(field.Type()))
		}

		if valueType.Kind() == reflect.Ptr {
			valueType = valueType.Elem()
			needAddr = true
		}

		for _, key := range val.MapKeys() {
			// val.MapIndex(key) returns a Value with wrong type.
			// use following trick to get correct Value.
			value := reflect.ValueOf(val.MapIndex(key).Interface())
			newValue := reflect.New(valueType)

			if err := decodeField(value, newValue, fmt.Sprintf("%v.%v", fullName, key)); err != nil {
				return err
			}

			if needAddr {
				field.SetMapIndex(key, newValue)
			} else {
				field.SetMapIndex(key, newValue.Elem())
			}
		}

	case reflect.Slice, reflect.Array:
		if valType.Kind() != reflect.Slice && valType.Kind() != reflect.Array {
			return fmt.Errorf("field '%v' is not a json array in result.", fullName)
		}

		valLen := val.Len()

		if kind == reflect.Array {
			if field.Len() < valLen {
				return fmt.Errorf("cannot copy all field '%v' values to struct. expected len is %v. actual len is %v.",
					fullName, field.Len(), valLen)
			}
		}

		var slc reflect.Value
		var needAddr bool

		valueType := field.Type().Elem()

		// shortcut for array of interface
		if valueType.Kind() == reflect.Interface {
			if kind == reflect.Array {
				for i := 0; i < valLen; i++ {
					field.Index(i).Set(val.Index(i))
				}
			} else { // kind is slice
				field.Set(val)
			}

			break
		}

		if kind == reflect.Array {
			slc = field.Slice(0, valLen)
		} else {
			// kind is slice
			slc = reflect.MakeSlice(field.Type(), valLen, valLen)
			field.Set(slc)
		}

		if valueType.Kind() == reflect.Ptr {
			needAddr = true
			valueType = valueType.Elem()
		}

		for i := 0; i < valLen; i++ {
			// val.Index(i) returns a Value with wrong type.
			// use following trick to get correct Value.
			valIndexValue := reflect.ValueOf(val.Index(i).Interface())
			newValue := reflect.New(valueType)

			if err := decodeField(valIndexValue, newValue, fmt.Sprintf("%v.%v", fullName, i)); err != nil {
				return err
			}

			if needAddr {
				slc.Index(i).Set(newValue)
			} else {
				slc.Index(i).Set(newValue.Elem())
			}
		}

	default:
		return fmt.Errorf("field '%v' in struct uses unsupported type '%v'.", fullName, kind)
	}

	return nil
}


text:
function cvx_optval = det_inv( X, p )

%DET_INV determinant of the inverse of an SPD matrix.
%   For a square matrix X, DET_INV(X) returns 1.0./DET(X) if X is symmetric
%   (real) or Hermitian (complex) and positive defininte, and +Inf otherwise.
%
%   This function can be used in many convex optimization problems that call
%   for LOG(DET(X)) instead. For example, if the objective function is
%      maximize(logdet(X))
%   then it can be replaced with
%      maximize(-det_inv(X))
%   and the same optimal point will be produced.
%
%   DET_INV(X,p) computes DET_INV(X)^p. p must be a positive real scalar.
%
%   Disciplined convex programming information:
%       DET_INV(X) is convex and nonmonotonic in X; therefore, when used in
%       CVX specifications, its argument must be affine.

error( nargchk( 1, 2, nargin ) ); %#ok
n = size( X, 1 );
if ndims( X ) > 2, %#ok
    error( 'N-D arrays are not supported.' );
elseif size( X, 2 ) ~= n,
    error( 'Matrix must be square.' );
elseif nargin < 2,
    p = 1;
elseif ~isnumeric( p ) || ~isreal( p ) || numel( p ) ~=  1 || p <= 0,
    error( 'Second argument must be a positive scalar.' );
end

if nnz( X - X' ) ~= 0,

    cvx_optval = +Inf;

else

    n = size( X, 1 );
    [ R, q ] = chol( X );
    if q == 0,
        cvx_optval = prod(diag(R)).^(-p);
    else
        eigs = eig( X );
        if any( eigs <= 0 ),
            cvx_optval = +Inf;
        else
            cvx_optval = prod(eigs).^(-p);
        end
    end

end

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


text:
package metrics

import (
	"time"

	dropsonde_metrics "github.com/cloudfoundry/dropsonde/metrics"
	"github.com/pivotal-golang/clock"
	"code.cloudfoundry.org/lager"
)

type Metric string

func (name Metric) Send(value int) {
	dropsonde_metrics.SendValue(string(name), float64(value), "Metric")
}

type Duration string

func (name Duration) Send(duration time.Duration) {
	dropsonde_metrics.SendValue(string(name), float64(duration), "nanos")
}

const (
	loopDevices   = Metric("LoopDevices")
	backingStores = Metric("BackingStores")
	depotDirs     = Metric("DepotDirs")

	metricsReportingDuration = Duration("MetricsReporting")
)

type PeriodicMetronNotifier struct {
	Interval time.Duration
	Logger   lager.Logger
	Clock    clock.Clock

	metrics Metrics
	stopped chan struct{}
}

func NewPeriodicMetronNotifier(
	logger lager.Logger,
	metrics Metrics,
	interval time.Duration,
	clock clock.Clock,
) *PeriodicMetronNotifier {
	return &PeriodicMetronNotifier{
		Interval: interval,
		Logger:   logger,
		Clock:    clock,
		metrics:  metrics,

		stopped: make(chan struct{}),
	}
}

func (notifier PeriodicMetronNotifier) Start() {
	logger := notifier.Logger.Session("metrics-notifier", lager.Data{"interval": notifier.Interval.String()})
	logger.Info("starting")
	ticker := notifier.Clock.NewTicker(notifier.Interval)

	go func() {
		defer ticker.Stop()

		logger.Info("started", lager.Data{"time": notifier.Clock.Now()})
		defer logger.Info("finished")

		for {
			select {
			case <-ticker.C():
				startedAt := notifier.Clock.Now()

				loopDevices.Send(notifier.metrics.LoopDevices())
				backingStores.Send(notifier.metrics.BackingStores())
				depotDirs.Send(notifier.metrics.DepotDirs())

				finishedAt := notifier.Clock.Now()
				metricsReportingDuration.Send(finishedAt.Sub(startedAt))
			case <-notifier.stopped:
				return
			}
		}
	}()
}

func (notifier PeriodicMetronNotifier) Stop() {
	close(notifier.stopped)
}


text:
module EpubForge
  module Action
    class Git < Action2
      define_action( "git:save" ) do |action|
        action.help( "commit changes to your project to your repository" )
        action.usage( "'optional commit message'" )

        action.execute do

        end
      end

      #
      # class GitBackup < Action
      #   description "commit your project to the git repo and back it up"
      #   keywords :backup, :save, :commit
      #   usage       "#{$PROGRAM_NAME} commit <project directory (optional if current dir)> \"optional message\""
      #
      #   desc( "do:save", "save to your git repository")
      #   def do( project, *args )
      #     @project = project
      #     @message = args.length > 0 ? args.last : "incremental backup"
      #
      #     unless project_already_gitted?
      #       say_error "Not a git-backed project.  Aborting."
      #       say_instruction "Run 'epubforge gitify <project>' to create a backup repository."
      #       return false
      #     end
      #
      #     `cd #{@project.root_dir} && git commit -a -m "#{@message}" && git push`
      #   end
      #
      #

      define_action( "git:init" ) do |action|
        action.help( "create a git repository of the project folder on an external host or thumb drive" )

        action.execute do
          @project = project
          @conf = @project.config
          @gitconf = @conf.git

          @cli_sequence = CliSequence.new
          @cli_sequence.default( :verbose, true )
          @cli_sequence.default( :local_dir, @project.root_dir )

          if project_already_gitted?
            say_error "Already seems to be a git project. delete the .git folder if this is incorrect."
            return false
          end

          project_name_with_folder = @gitconf["repo_folder"].fwf_filepath

          if @gitconf["remote_host"]
            remote_host = "#{@gitconf['remote_user']}@#{@gitconf['remote_host']}"
            @cli_sequence.default( :remote, remote_host )
            project_url = "ssh://#{remote_host}#{project_name_with_folder}"

            @cli_sequence.add_remote_command( "mkdir -p #{project_name_with_folder}", "rm -rf #{project_name_with_folder}" )
            @cli_sequence.add_remote_command( "git --bare init #{project_name_with_folder}" )
            identifier = project_name_with_folder.join( @gitconf["repo_id"] )
            @cli_sequence.add_remote_command( "touch #{identifier}", "rm #{identifier}" )  # undo isn't needed here, since the directory will be wiped out.
          else
            project_url = "file://#{project_name_with_folder}"
            @cli_sequence.add_local_command( "mkdir -p #{project_name_with_folder}", "rm -rf #{project_name_with_folder}" )
            @cli_sequence.add_local_command( "git --bare init #{project_name_with_folder}" )
            identifier = project_name_with_folder.join( @gitconf["repo_id"] )
            @cli_sequence.add_local_command( "touch #{identifier}", "rm #{identifier}" )
          end

          # running locally
          @cli_sequence.add_local_command "git init", "rm -rf .git"
          @cli_sequence.add_local_command "git remote add origin #{project_url}"
          @cli_sequence.add_local_command "git add ."
          @cli_sequence.add_local_command "git commit -a -m \"Initial commit\""
          @cli_sequence.add_local_command "git config branch.master.remote origin"
          @cli_sequence.add_local_command "git config branch.master.merge refs/heads/master"
          @cli_sequence.add_local_command "git push origin master"       # need to be explicit about branch the first time

          if @cli_sequence.execute
            say_all_is_well( "All done.  The url for this project is #{project_url}" )
          else
            say_error( "Command sequence failed." )
          end
        end
      end

      protected
      def git_remote_exec( cmd )
        say_subtly( "attempting to run remotely:  #{cmd}" )
        `cd #{@project.root_dir} && ssh #{@gitconf["remote_user"]}@#{@gitconf["remote_host"]} "#{cmd}"`
        say( "Success: #{$?.success?}")
      end

      def git_local_exec( cmd )
        say_subtly( "attempting to run locally:  #{cmd}" )
        `cd #{@project.root_dir} && #{cmd}`
        say( "Success: #{$?.success?}")
      end
    end
  end
end


text:
/*
 * Copyright (C) 2006 Sun Microsystems, Inc. All rights reserved.
 * Use is subject to license terms.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met: Redistributions of source code
 * must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution. Neither the name of the Sun Microsystems nor the names of
 * is contributors may be used to endorse or promote products derived from this software
 * without specific prior written permission.

 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package org.auraframework.util.phobos.script.javascript;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.script.Bindings;
import javax.script.ScriptContext;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeJavaClass;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Wrapper;

/**
 * ExternalScriptable is an implementation of Scriptable
 * backed by a JSR 223 Bindings instance.
 *
 * @author Mike Grogan
 * @author A. Sundararajan
 * @since 1.6
 */
final class ExternalScriptable implements Scriptable {
    /* Underlying ScriptContext that we use to store
     * named variables of this scope.
     */
    private ScriptContext context;

    /* JavaScript allows variables to be named as numbers (indexed
     * properties). This way arrays, objects (scopes) are treated uniformly.
     * Note that JSR 223 API supports only String named variables and
     * so we can't store these in Bindings. Also, JavaScript allows name
     * of the property name to be even empty String! Again, JSR 223 API
     * does not support empty name. So, we use the following fallback map
     * to store such variables of this scope. This map is not exposed to
     * JSR 223 API. We can just script objects "as is" and need not convert.
     */
    private Map<Object, Object> indexedProps;

    // my prototype
    private Scriptable prototype;
    // my parent scope, if any
    private Scriptable parent;

    ExternalScriptable(ScriptContext context) {
        this(context, new HashMap<>());
    }

    ExternalScriptable(ScriptContext context, Map<Object, Object> indexedProps) {
        if (context == null) {
            throw new NullPointerException("context is null");
        }
        this.context = context;
        this.indexedProps = indexedProps;
    }

    ScriptContext getContext() {
        return context;
    }

    /*
    private boolean isInIndexedProps(Object key) {
        return indexedProps != null && indexedProps.containsKey(key);
    }
     */

    private boolean isEmpty(String name) {
        return name.equals("");
    }

    /**
     * Return the name of the class.
     */
    @Override
    public String getClassName() {
        return "Global";
    }

    /**
     * Returns the value of the named property or NOT_FOUND.
     *
     * If the property was created using defineProperty, the
     * appropriate getter method is called.
     *
     * @param name the name of the property
     * @param start the object in which the lookup began
     * @return the value of the property (may be null), or NOT_FOUND
     */
    @Override
    public synchronized Object get(String name, Scriptable start) {
        if (isEmpty(name)) {
            if (indexedProps.containsKey(name)) {
                return indexedProps.get(name);
            } else {
                return NOT_FOUND;
            }
        } else {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope != -1) {
                    Object value = context.getAttribute(name, scope);
                    return Context.javaToJS(value, this);
                } else {
                    return NOT_FOUND;
                }
            }
        }
    }

    /**
     * Returns the value of the indexed property or NOT_FOUND.
     *
     * @param index the numeric index for the property
     * @param start the object in which the lookup began
     * @return the value of the property (may be null), or NOT_FOUND
     */
    @Override
    public synchronized Object get(int index, Scriptable start) {
        Integer key = new Integer(index);
        if (indexedProps.containsKey(index)) {
            return indexedProps.get(key);
        } else {
            return NOT_FOUND;
        }
    }

    /**
     * Returns true if the named property is defined.
     *
     * @param name the name of the property
     * @param start the object in which the lookup began
     * @return true if and only if the property was found in the object
     */
    @Override
    public synchronized boolean has(String name, Scriptable start) {
        if (isEmpty(name)) {
            return indexedProps.containsKey(name);
        } else {
            synchronized (context) {
                return context.getAttributesScope(name) != -1;
            }
        }
    }

    /**
     * Returns true if the property index is defined.
     *
     * @param index the numeric index for the property
     * @param start the object in which the lookup began
     * @return true if and only if the property was found in the object
     */
    @Override
    public synchronized boolean has(int index, Scriptable start) {
        Integer key = new Integer(index);
        return indexedProps.containsKey(key);
    }

    /**
     * Sets the value of the named property, creating it if need be.
     *
     * @param name the name of the property
     * @param start the object whose property is being set
     * @param value value to set the property to
     */
    @Override
    public void put(String name, Scriptable start, Object value) {
        if (start == this) {
            synchronized (this) {
                if (isEmpty(name)) {
                    indexedProps.put(name, value);
                } else {
                    synchronized (context) {
                        int scope = context.getAttributesScope(name);
                        if (scope == -1) {
                            scope = ScriptContext.ENGINE_SCOPE;
                        }
                        context.setAttribute(name, jsToJava(value), scope);
                    }
                }
            }
        } else {
            start.put(name, start, value);
        }
    }

    /**
     * Sets the value of the indexed property, creating it if need be.
     *
     * @param index the numeric index for the property
     * @param start the object whose property is being set
     * @param value value to set the property to
     */
    @Override
    public void put(int index, Scriptable start, Object value) {
        if (start == this) {
            synchronized (this) {
                indexedProps.put(new Integer(index), value);
            }
        } else {
            start.put(index, start, value);
        }
    }

    /**
     * Removes a named property from the object.
     *
     * If the property is not found, no action is taken.
     *
     * @param name the name of the property
     */
    @Override
    public synchronized void delete(String name) {
        if (isEmpty(name)) {
            indexedProps.remove(name);
        } else {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope != -1) {
                    context.removeAttribute(name, scope);
                }
            }
        }
    }

    /**
     * Removes the indexed property from the object.
     *
     * If the property is not found, no action is taken.
     *
     * @param index the numeric index for the property
     */
    @Override
    public void delete(int index) {
        indexedProps.remove(new Integer(index));
    }

    /**
     * Get the prototype of the object.
     * @return the prototype
     */
    @Override
    public Scriptable getPrototype() {
        return prototype;
    }

    /**
     * Set the prototype of the object.
     * @param prototype the prototype to set
     */
    @Override
    public void setPrototype(Scriptable prototype) {
        this.prototype = prototype;
    }

    /**
     * Get the parent scope of the object.
     * @return the parent scope
     */
    @Override
    public Scriptable getParentScope() {
        return parent;
    }

    /**
     * Set the parent scope of the object.
     * @param parent the parent scope to set
     */
    @Override
    public void setParentScope(Scriptable parent) {
        this.parent = parent;
    }

    /**
     * Get an array of property ids.
     *
     * Not all property ids need be returned. Those properties
     * whose ids are not returned are considered non-enumerable.
     *
     * @return an array of Objects. Each entry in the array is either
     *         a java.lang.String or a java.lang.Number
     */
    @Override
    public synchronized Object[] getIds() {
        String[] keys = getAllKeys();
        int size = keys.length + indexedProps.size();
        Object[] res = new Object[size];
        System.arraycopy(keys, 0, res, 0, keys.length);
        int i = keys.length;
        // now add all indexed properties
        for (Object index : indexedProps.keySet()) {
            res[i++] = index;
        }
        return res;
    }

    /**
     * Get the default value of the object with a given hint.
     * The hints are String.class for type String, Number.class for type
     * Number, Scriptable.class for type Object, and Boolean.class for
     * type Boolean.

     *
     * A hint of null means "no hint".
     *
     * See ECMA 8.6.2.6.
     *
     * @param hint the type hint
     * @return the default value
     */
    @Override
    public Object getDefaultValue(Class<?> typeHint) {
        for (int i=0; i < 2; i++) {
            boolean tryToString;
            if (typeHint == ScriptRuntime.StringClass) {
                tryToString = (i == 0);
            } else {
                tryToString = (i == 1);
            }

            String methodName;
            Object[] args;
            if (tryToString) {
                methodName = "toString";
                args = ScriptRuntime.emptyArgs;
            } else {
                methodName = "valueOf";
                args = new Object[1];
                String hint;
                if (typeHint == null) {
                    hint = "undefined";
                } else if (typeHint == ScriptRuntime.StringClass) {
                    hint = "string";
                } else if (typeHint == ScriptRuntime.ScriptableClass) {
                    hint = "object";
                } else if (typeHint == ScriptRuntime.FunctionClass) {
                    hint = "function";
                } else if (typeHint == ScriptRuntime.BooleanClass
                        || typeHint == Boolean.TYPE)
                {
                    hint = "boolean";
                } else if (typeHint == ScriptRuntime.NumberClass ||
                        typeHint == ScriptRuntime.ByteClass ||
                        typeHint == Byte.TYPE ||
                        typeHint == ScriptRuntime.ShortClass ||
                        typeHint == Short.TYPE ||
                        typeHint == ScriptRuntime.IntegerClass ||
                        typeHint == Integer.TYPE ||
                        typeHint == ScriptRuntime.FloatClass ||
                        typeHint == Float.TYPE ||
                        typeHint == ScriptRuntime.DoubleClass ||
                        typeHint == Double.TYPE)
                {
                    hint = "number";
                } else {
                    throw Context.reportRuntimeError(
                            "Invalid JavaScript value of type " +
                                    typeHint.toString());
                }
                args[0] = hint;
            }
            Object v = ScriptableObject.getProperty(this, methodName);
            if (!(v instanceof Function))
                continue;
            Function fun = (Function) v;
            Context cx = RhinoScriptEngine.enterContext();
            try {
                v = fun.call(cx, fun.getParentScope(), this, args);
            } finally {
                Context.exit();
            }
            if (v != null) {
                if (!(v instanceof Scriptable)) {
                    return v;
                }
                if (typeHint == ScriptRuntime.ScriptableClass
                        || typeHint == ScriptRuntime.FunctionClass)
                {
                    return v;
                }
                if (tryToString && v instanceof Wrapper) {
                    // Let a wrapped java.lang.String pass for a primitive
                    // string.
                    Object u = ((Wrapper)v).unwrap();
                    if (u instanceof String)
                        return u;
                }
            }
        }
        // fall through to error
        String arg = (typeHint == null) ? "undefined" : typeHint.getName();
        throw Context.reportRuntimeError(
                "Cannot find default value for object " + arg);
    }

    /**
     * Implements the instanceof operator.
     *
     * @param instance The value that appeared on the LHS of the instanceof
     *              operator
     * @return true if "this" appears in value's prototype chain
     *
     */
    @Override
    public boolean hasInstance(Scriptable instance) {
        // Default for JS objects (other than Function) is to do prototype
        // chasing.
        Scriptable proto = instance.getPrototype();
        while (proto != null) {
            if (proto.equals(this)) return true;
            proto = proto.getPrototype();
        }
        return false;
    }

    private String[] getAllKeys() {
        ArrayList<String> list = new ArrayList<>();
        synchronized (context) {
            for (int scope : context.getScopes()) {
                Bindings bindings = context.getBindings(scope);
                if (bindings != null) {
                    list.ensureCapacity(bindings.size());
                    for (String key : bindings.keySet()) {
                        list.add(key);
                    }
                }
            }
        }
        String[] res = new String[list.size()];
        list.toArray(res);
        return res;
    }

    /**
     * We convert script values to the nearest Java value.
     * We unwrap wrapped Java objects so that access from
     * Bindings.get() would return "workable" value for Java.
     * But, at the same time, we need to make few special cases
     * and hence the following function is used.
     */
    private Object jsToJava(Object jsObj) {
        if (jsObj instanceof Wrapper) {
            Wrapper njb = (Wrapper) jsObj;
            /* importClass feature of ImporterTopLevel puts
             * NativeJavaClass in global scope. If we unwrap
             * it, importClass won't work.
             */
            if (njb instanceof NativeJavaClass) {
                return njb;
            }

            /* script may use Java primitive wrapper type objects
             * (such as java.lang.Integer, java.lang.Boolean etc)
             * explicitly. If we unwrap, then these script objects
             * will become script primitive types. For example,
             *
             *    var x = new java.lang.Double(3.0); print(typeof x);
             *
             * will print 'number'. We don't want that to happen.
             */
            Object obj = njb.unwrap();
            if (obj instanceof Number || obj instanceof String ||
                    obj instanceof Boolean || obj instanceof Character) {
                // special type wrapped -- we just leave it as is.
                return njb;
            } else {
                // return unwrapped object for any other object.
                return obj;
            }
        } else { // not-a-Java-wrapper
            return jsObj;
        }
    }
}


text:
using RentABook.Models.Poco;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace RentABook.Web.Areas.Books.Models
{
    public class BookDetailsViewModel
    {
        public int Id { get; set; }

        public string Author { get; set; }

        public string Title { get; set; }

        public string ShortDescription { get; set; }

        [UIHint("Slider")]
        [Display(Name = "Condition")]
        public int Condition { get; set; }

        public IEnumerable<string> Categories { get; set; }

        public string OwnerId { get; set; }

        public string OwnerUserName { get; set; }

        [Display(Name = "Owner")]
        public string OwnerFullName { get; set; }

        [Display(Name = "Location of book")]
        public string Address { get; set; }

        public string Town { get; set; }

        public BookState State { get; set; }

        public RentType RentType { get; set; }

        public decimal? Price { get; set; }

        public BookStateViewModel BookState { get; set; }
    }
}


text:
from setuptools import setup, find_packages
import os

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()

version = '0.8'

install_requires = [
    "setuptools",
    "Sphinx >= 1.2",
    "six",
]

setup(name='hieroglyph',
      version=version,
      description=("Generate HTML presentations from plain text "
                   "sources with all the power of Sphinx."),
      long_description=README + '\n\n' + NEWS,
      classifiers=[
        'License :: OSI Approved :: BSD License',
        'Topic :: Documentation',
        'Topic :: Text Processing',
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
      ],
      keywords='',
      author='Nathan Yergler',
      author_email='nathan@yergler.net',
      url='https://github.com/nyergler/hieroglyph',
      license='BSD',
      packages=find_packages('src'),
      package_dir={'': 'src'},
      include_package_data=True,
      zip_safe=False,
      install_requires=install_requires,
      entry_points={
          'console_scripts': [
              'hieroglyph=hieroglyph.quickstart:main',
              'hieroglyph-quickstart=hieroglyph.quickstart:quickstart',
          ],
          'hieroglyph.theme': [
              'slides=hieroglyph.themes:SLIDES',
              'single-level=hieroglyph.themes:SINGLE_LEVEL',
              'slides2=hieroglyph.themes:SLIDES2',
          ],
      },
      test_suite='hieroglyph.tests',
      tests_require=[
          'beautifulsoup4',
          'mock',
          'sphinx-testing',
      ],
      )


text:
package com.vzaar;

import com.vzaar.client.Resource;
import com.vzaar.client.RestClient;

public class EncodingPresetResource {
    private final RestClient client;

    EncodingPresetResource(RestClient client) {
        this.client = client;
    }

    /**
     * Start an encoding preset search / listing request.
     * @return the request
     */
    public EncodingPresetPageRequest list() {
        return new EncodingPresetPageRequest(resource());
    }

    /**
     * Get an encodingPresetId by id
     * @param encodingPresetId the id
     * @return the encodingPresetId
     */
    public EncodingPreset get(int encodingPresetId) {
        return id(encodingPresetId).lookup();
    }

    private Resource<EncodingPreset> resource() {
        return client.resource(EncodingPreset.class);
    }

    private Resource<EncodingPreset> id(int id) {
        return resource().id(id);
    }
}


text:
#ifndef ART_COMPILER_SEA_IR_TYPES_TYPES_H_
#define ART_COMPILER_SEA_IR_TYPES_TYPES_H_

#include "safe_map.h"
#include "verifier/reg_type.h"
#include "verifier/reg_type_cache.h"

namespace sea_ir {

// TODO: Replace typedef with an actual class implementation when we have more types.
typedef art::verifier::RegType Type;

// Stores information about the result type of each instruction.
// Note: Main purpose is to encapsulate the map<instruction id, type*>,
//       so that we can replace the underlying storage at any time.
class TypeData {
 public:
  art::SafeMap<int, const Type*>* GetTypeMap() {
    return &type_map_;
  }
  // Returns the type associated with instruction with @instruction_id.
  const Type* FindTypeOf(int instruction_id) {
    art::SafeMap<int, const Type*>::const_iterator result_it = type_map_.find(instruction_id);
    if (type_map_.end() != result_it) {
      return result_it->second;
    }
    return NULL;
  }

  // Saves the fact that instruction @instruction_id produces a value of type @type.
  void SetTypeOf(int instruction_id, const Type* type) {
    type_map_.Overwrite(instruction_id, type);
  }

 private:
  art::SafeMap<int, const Type*> type_map_;
};

}  // namespace sea_ir
#endif  // ART_COMPILER_SEA_IR_TYPES_TYPES_H_