text:
package simulation

import (
	"crypto/tls"
	"net"
	"time"

	"google.golang.org/grpc"

	"github.com/cockroachdb/cockroach/base"
	"github.com/cockroachdb/cockroach/gossip"
	"github.com/cockroachdb/cockroach/gossip/resolver"
	"github.com/cockroachdb/cockroach/roachpb"
	"github.com/cockroachdb/cockroach/rpc"
	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/encoding"
	"github.com/cockroachdb/cockroach/util/log"
	"github.com/cockroachdb/cockroach/util/stop"
)

// Node represents a node used in a Network. It includes information
// about the node's gossip instance, network address, and underlying
// server.
type Node struct {
	Gossip *gossip.Gossip
	Server *grpc.Server
	Addr   net.Addr
}

// Network provides access to a test gossip network of nodes.
type Network struct {
	Nodes           []*Node
	Stopper         *stop.Stopper
	nodeIDAllocator roachpb.NodeID // provides unique node IDs
	rpcContext      *rpc.Context
	tlsConfig       *tls.Config
}

// NewNetwork creates nodeCount gossip nodes.
func NewNetwork(nodeCount int) *Network {
	log.Infof("simulating gossip network with %d nodes", nodeCount)

	n := &Network{
		Nodes:   []*Node{},
		Stopper: stop.NewStopper(),
	}
	n.rpcContext = rpc.NewContext(&base.Context{Insecure: true}, nil, n.Stopper)
	var err error
	n.tlsConfig, err = n.rpcContext.GetServerTLSConfig()
	if err != nil {
		log.Fatal(err)
	}

	for i := 0; i < nodeCount; i++ {
		node, err := n.CreateNode()
		if err != nil {
			log.Fatal(err)
		}
		// Build a resolver for each instance or we'll get data races.
		r, err := resolver.NewResolverFromAddress(n.Nodes[0].Addr)
		if err != nil {
			log.Fatalf("bad gossip address %s: %s", n.Nodes[0].Addr, err)
		}
		node.Gossip.SetResolvers([]resolver.Resolver{r})
		if err := n.StartNode(node); err != nil {
			log.Fatal(err)
		}
	}
	return n
}

// CreateNode creates a simulation node and starts an RPC server for it.
func (n *Network) CreateNode() (*Node, error) {
	server := rpc.NewServer(n.rpcContext)
	ln, err := util.ListenAndServeGRPC(n.Stopper, server, util.TestAddr)
	if err != nil {
		return nil, err
	}
	node := &Node{Server: server, Addr: ln.Addr()}
	node.Gossip = gossip.New(n.rpcContext, nil, n.Stopper)
	n.Nodes = append(n.Nodes, node)
	return node, nil
}

// StartNode initializes a gossip instance for the simulation node and
// starts it.
func (n *Network) StartNode(node *Node) error {
	node.Gossip.Start(node.Server, node.Addr)
	node.Gossip.EnableSimulationCycler(true)
	n.nodeIDAllocator++
	node.Gossip.SetNodeID(n.nodeIDAllocator)
	if err := node.Gossip.SetNodeDescriptor(&roachpb.NodeDescriptor{
		NodeID:  node.Gossip.GetNodeID(),
		Address: util.MakeUnresolvedAddr(node.Addr.Network(), node.Addr.String()),
	}); err != nil {
		return err
	}
	if err := node.Gossip.AddInfo(node.Addr.String(),
		encoding.EncodeUint64Ascending(nil, 0), time.Hour); err != nil {
		return err
	}
	return nil
}

// GetNodeFromID returns the simulation node associated with
// provided node ID, or nil if there is no such node.
func (n *Network) GetNodeFromID(nodeID roachpb.NodeID) (*Node, bool) {
	for _, node := range n.Nodes {
		if node.Gossip.GetNodeID() == nodeID {
			return node, true
		}
	}
	return nil, false
}

// SimulateNetwork runs until the simCallback returns false.
//
// At each cycle, every node gossips a key equal to its address (unique)
// with the cycle as the value. The received cycle value can be used
// to determine the aging of information between any two nodes in the
// network.
//
// At each cycle of the simulation, node 0 gossips the sentinel.
//
// The simulation callback receives the cycle and the network as arguments.
func (n *Network) SimulateNetwork(simCallback func(cycle int, network *Network) bool) {
	nodes := n.Nodes
	for cycle := 1; simCallback(cycle, n); cycle++ {
		// Node 0 gossips sentinel & cluster ID every cycle.
		if err := nodes[0].Gossip.AddInfo(
			gossip.KeySentinel,
			encoding.EncodeUint64Ascending(nil, uint64(cycle)),
			time.Hour); err != nil {
			log.Fatal(err)
		}
		if err := nodes[0].Gossip.AddInfo(gossip.KeyClusterID,
			encoding.EncodeUint64Ascending(nil, uint64(cycle)), 0*time.Second); err != nil {
			log.Fatal(err)
		}
		// Every node gossips cycle.
		for _, node := range nodes {
			if err := node.Gossip.AddInfo(
				node.Addr.String(),
				encoding.EncodeUint64Ascending(nil, uint64(cycle)),
				time.Hour); err != nil {
				log.Fatal(err)
			}
			node.Gossip.SimulationCycle()
		}
		time.Sleep(5 * time.Millisecond)
	}
	log.Infof("gossip network simulation: total infos sent=%d, received=%d", n.infosSent(), n.infosReceived())
}

// Stop stops all servers and gossip nodes.
func (n *Network) Stop() {
	for _, node := range n.Nodes {
		node.Gossip.EnableSimulationCycler(false)
	}
	n.Stopper.Stop()
}

// RunUntilFullyConnected blocks until the gossip network has received
// gossip from every other node in the network. It returns the gossip
// cycle at which the network became fully connected.
func (n *Network) RunUntilFullyConnected() int {
	var connectedAtCycle int
	n.SimulateNetwork(func(cycle int, network *Network) bool {
		if network.isNetworkConnected() {
			connectedAtCycle = cycle
			return false
		}
		return true
	})
	return connectedAtCycle
}

// isNetworkConnected returns true if the network is fully connected
// with no partitions (i.e. every node knows every other node's
// network address).
func (n *Network) isNetworkConnected() bool {
	for _, leftNode := range n.Nodes {
		for _, rightNode := range n.Nodes {
			if _, err := leftNode.Gossip.GetInfo(rightNode.Addr.String()); err != nil {
				return false
			}
		}
	}
	return true
}

// infosSent returns the total count of infos sent from all nodes in
// the network.
func (n *Network) infosSent() int {
	var count int
	for _, node := range n.Nodes {
		count += node.Gossip.InfosSent()
	}
	return count
}

// infosReceived returns the total count of infos received from all
// nodes in the network.
func (n *Network) infosReceived() int {
	var count int
	for _, node := range n.Nodes {
		count += node.Gossip.InfosReceived()
	}
	return count
}


text:
![](https://raw.githubusercontent.com/x-raizor/Efficiency/master/demo/efficiency-logo.png)
Efficiency
==========
Sketch App plugins suite for faster and less apish work. Download and start Efficiency.sketchplugin to install.

*Tested in Sketch Version 42 (36781)*

# Swap Fill & Border colors (new)
An analogue of pressing 'X' in Adobe Illustrator which is interchange colors between fill and border. The amazing plugin was [written](https://github.com/nathco/Swap-Fill-Border) by [Nathan Rutzky](https://github.com/nathco) and when adopted to the latest versions of Sketch.

**Shortcut:** Cmd Shift X

# Bitmap To Pattern Fill
![Bitmap to pattern fill](https://raw.githubusercontent.com/x-raizor/Efficiency/master/demo/bitmap-to-fill.gif)
Convert selected images into rectangles with images as pattern fill.

Plugin by Aby Nimbalkar

# Soft-hyphens (Cyrillic only for the moment)
![Bitmap to pattern fill](https://raw.githubusercontent.com/x-raizor/Efficiency/master/demo/hyphen.gif)

Provides selected text with soft-hyphens in order to obtain soft right edge of left align.

**Shortcut:** Cmd Ctrl Shift T

[Algorithm](http://quittance.ru/hyphenator.php) by [Sergey Kurakin](http://quittance.ru/blog/index.php?category=7)
Web service by [Edele Gizatullin](https://github.com/edele)

# Muravjev's Typograph (Cyrillic only for the moment)
![Bitmap to pattern fill](https://raw.githubusercontent.com/x-raizor/Efficiency/master/demo/typograph.gif)

Typographics enhancer with set of rules for Russian typographics. Powered by [mdash.ru](http://mdash.ru) typograph web service which is lovely made by Evgeny Muravjev and Alexander Drutsa.

**Default options set**
* OptAlign.all = off
* Text.breakline = off
* Text.paragraphs = off
* Etc.unicode_convert = on

**Shortcut:** Cmd Ctrl Shift T

# Text leading, line spacing and tracking
![Text manipulations](https://raw.githubusercontent.com/x-raizor/Efficiency/master/demo/text_manipulation.gif)

Let you manipulate with text block leading (paragraph indent), line spacing and tracking via keyboard. With native hotkeys for font size (cmd alt =/-) and text block size changing (cmd shift ←/→) it transforms Sketch into typographics tool with immediate connection.

## Keyboard shortcuts
* Line Height +: Cmd Alt Shift =
* Line Height -: Cmd Alt Shift -
* Paragraph Gap +: Cmd Alt Ctrl =
* Paragraph Gap -: Cmd Alt Ctrl -
* Tracking-: Alt ←
* Tracking+: Alt →

# Text tracking
Press Alt ← or Alt → to decrease or increase symbols spacing (tracking). It works only then text frame selected not in edit mode.

# Keep only text layers in selection
It removes any layers except text from your current selection. Sometimes you will want to choose all text layers in the document, page or artboard. So select all layers of scope you want and apply this plugin.

# Random shift
Shifts layers in selection in random direction. It'll ask you for maximum shift size.

**Shortcut:** Cmd Alt R

![Random shift example](https://raw.githubusercontent.com/x-raizor/Efficiency/master/demo/random_shift.gif)

# Random size
Gives to layers in selection random size based on Perlin noise. It'll ask you for scale factor.

**Shortcut:** Cmd Alt Shift R

![Random size example](https://raw.githubusercontent.com/x-raizor/Efficiency/master/demo/random_size.gif)

# Toggle 'Constrain Proportions'
Toggle state of 'Constrain Proportions' layer property.

**Shortcut**: Cmd Shift K (mnemonically: Keep aspect ratio)

![Toggle Constrain Proportions](https://raw.githubusercontent.com/x-raizor/Efficiency/master/demo/toggle-constrain-proportions.gif)

# Credits
## Plugin authors
* Aby Nimbalkar
* Andrew Shapiro
* Nathan Rutzky

## Third parties
* Perlin Noise by John Haggerty [Slime](http://www.slimeland.com)
* [Mdash.ru](http://mdash.ru) typograph web service by Evgeny Muravjev and Alexander Drutsa
*  Hyphenation using Liang-Knuth algorithm by [Sergey Kurakin](http://quittance.ru/blog/index.php?category=7)
* Web service for hyphenation by [Edele Gizatullin](https://github.com/edele)

redpajama_set_name: RedPajamaGithub


text:
package org.jkiss.dbeaver.ext.wmi.model;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.DBPImage;
import org.jkiss.dbeaver.model.DBPImageProvider;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.data.DBDValueMeta;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.utils.CommonUtils;
import org.jkiss.wmi.service.*;

import java.util.*;

/**
 * WMI result set
 */
public class WMIResultSet implements DBCResultSet, DBCResultSetMetaData, DBCEntityMetaData
{
    private DBCSession session;
    private WMIClass classObject;
    private Collection<WMIObject> rows;
    private Iterator<WMIObject> iterator;
    private WMIObject row;
    private List<DBCAttributeMetaData> properties;

    public WMIResultSet(DBCSession session, WMIClass classObject, Collection<WMIObject> rows) throws WMIException
    {
        this.session = session;
        this.classObject = classObject;
        this.rows = rows;
        this.iterator = rows.iterator();
        this.row = null;
        {
            // Init meta properties
            WMIObject metaObject;
            if (classObject != null) {
                metaObject = classObject.getClassObject();
            } else if (!rows.isEmpty()) {
                metaObject = rows.iterator().next();
            } else {
                metaObject = null;
            }
            if (metaObject == null) {
                properties = Collections.emptyList();
            } else {
                Collection<WMIObjectAttribute> props = metaObject.getAttributes(WMIConstants.WBEM_FLAG_ALWAYS);
                properties = new ArrayList<>(props.size());
                int index = 0;
                for (WMIObjectAttribute prop : props) {
                    if (!prop.isSystem()) {
                        properties.add(new MetaProperty(prop, index++));
                    }
                }
            }
        }

    }

    @Override
    public DBCSession getSession()
    {
        return session;
    }

    @Override
    public DBCStatement getSourceStatement()
    {
        return null;
    }

    @Override
    public Object getAttributeValue(int index) throws DBCException
    {
        try {
            if (index >= properties.size()) {
                throw new DBCException("Column index " + index + " out of bounds (" + properties.size() + ")");
            }
            return row.getValue(properties.get(index).getName());
        } catch (WMIException e) {
            throw new DBCException(e, session.getDataSource());
        }
    }

    @Nullable
    @Override
    public Object getAttributeValue(String name) throws DBCException {
        try {
            return row.getValue(name);
        } catch (WMIException e) {
            throw new DBCException(e, session.getDataSource());
        }
    }

    @Override
    public DBDValueMeta getAttributeValueMeta(int index) throws DBCException
    {
        return null;
    }

    @Override
    public DBDValueMeta getRowMeta() throws DBCException
    {
        try {
            Collection<WMIQualifier> qualifiers = row.getQualifiers();
            if (CommonUtils.isEmpty(qualifiers)) {
                return null;
            }
            return new WMIValueMeta(qualifiers);
        } catch (WMIException e) {
            throw new DBCException("Can't read value qualifiers");
        }
    }

    @Override
    public boolean nextRow() throws DBCException
    {
        if (!this.iterator.hasNext()) {
            return false;
        }
        row = iterator.next();
        return true;
    }

    @Override
    public boolean moveTo(int position) throws DBCException
    {
        throw new DBCException("Not Implemented");
    }

    @NotNull
    @Override
    public DBCResultSetMetaData getMeta() throws DBCException
    {
        return this;
    }

    @Override
    public String getResultSetName() throws DBCException {
        return null;
    }

    @Override
    public void close()
    {
        for (WMIObject row : rows) {
            row.release();
        }
        rows.clear();
        row = null;
    }

    /////////////////////////////////////////////////////////////
    // DBCResultSetMetaData

    @NotNull
    @Override
    public List<DBCAttributeMetaData> getAttributes()
    {
        return properties;
    }

    /////////////////////////////////////////////////////////////
    // DBCTableMetaData

    @Nullable
    @Override
    public String getCatalogName() {
        return null;
    }

    @Nullable
    @Override
    public String getSchemaName() {
        return null;
    }

    @NotNull
    @Override
    public String getEntityName()
    {
        return classObject == null ? null : classObject.getName();
    }

    /////////////////////////////////////////////////////////////
    // Meta property

    private class MetaProperty implements DBCAttributeMetaData,DBPImageProvider
    {
        private final WMIObjectAttribute attribute;
        private final int index;

        private MetaProperty(WMIObjectAttribute attribute, int index)
        {
            this.attribute = attribute;
            this.index = index;
        }

        @NotNull
        @Override
        public String getName()
        {
            return attribute.getName();
        }

        @Override
        public long getMaxLength()
        {
            return 0;
        }

        @Override
        public String getTypeName()
        {
            return attribute.getTypeName();
        }

        @Override
        public String getFullTypeName() {
            return attribute.getTypeName();
        }

        @Override
        public int getTypeID()
        {
            return attribute.getType();
        }

        @Override
        public DBPDataKind getDataKind()
        {
            return WMIClassAttribute.getDataKindById(attribute.getType());
        }

        @Override
        public Integer getScale()
        {
            return 0;
        }

        @Override
        public Integer getPrecision()
        {
            return 0;
        }

        @Override
        public int getOrdinalPosition()
        {
            return index;
        }

        @Nullable
        @Override
        public Object getSource() {
            return null;
        }

        @NotNull
        @Override
        public String getLabel()
        {
            return attribute.getName();
        }

        @Nullable
        @Override
        public String getEntityName()
        {
            return classObject == null ? null : classObject.getName();
        }

        @Override
        public boolean isReadOnly()
        {
            return false;
        }

        @Nullable
        @Override
        public DBCEntityMetaData getEntityMetaData()
        {
            return WMIResultSet.this;
        }

        @Nullable
        @Override
        public DBPImage getObjectImage()
        {
            return WMIClassAttribute.getPropertyImage(attribute.getType());
        }

        @Override
        public boolean isRequired()
        {
            return false;
        }

        @Override
        public boolean isAutoGenerated() {
            return false;
        }

    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#f16863" android:state_enabled="true" />
    <item android:color="#0cb2dc" />
</selector>


text:
#ifndef TEST_HELPER_LIBRARY_H
#define TEST_HELPER_LIBRARY_H

#include <math.h>

#include <Eigen/Geometry>

void euler2quat(double roll, double pitch, double yaw, double* q);

void calculate3dRmsError(double truth[][3], double est[][3],
                         const int trajectory_length, const int start_index,
                         double* error);

void calculateQuaternionRmsError(double truth[][4], double est[][4],
                                 const int trajectory_length,
                                 const int start_index, double* error);

#endif  // TEST_HELPER_LIBRARY_H


text:
//
//  GLKEffectPropertyTransform.h
//  GLKEffects
//
//  Copyright (c) 2011-2012 Apple Inc. All rights reserved.
//

#import <GLKit/GLKEffectProperty.h>
#import <GLKit/GLKMath.h>

/*
 GLKEffectPropertyTransformm

 GLKEffectPropertyTransform maintains three primary matrices:

      _projectionMatrix
      _modelviewMatrix

 and 1 derived matrix: _normalMatrix.

 When the modelview matrix is changed the normalMatrix is marked as stale.
 If the normalMatrix is subsequently retrieved after being marked stale
 the normalMatrix selector will recalculate the normalMatrix to return
 a current result with respect to the modelviewMatrix.
*/
NS_ASSUME_NONNULL_BEGIN
NS_CLASS_AVAILABLE(10_8, 5_0)
@interface GLKEffectPropertyTransform : GLKEffectProperty
{
    @private

    // Primary matrices
    GLKMatrix4  _modelviewMatrix, _projectionMatrix;

    // Derived matrix
    GLKMatrix3  _normalMatrix;
}

// Properties                                                                                // Default Value
@property (nonatomic, assign)   GLKMatrix4   modelviewMatrix, projectionMatrix;                  // Identity for all
@property (nonatomic, readonly) GLKMatrix3   normalMatrix;                                       // Identity

@end
NS_ASSUME_NONNULL_END


text:
@interface SWPodfileParserTests : XCTestCase
@end

@implementation SWPodfileParserTests {
    SWPodfileScanner *scanner;
}

#pragma mark - Strings

- (void)testScanSingleQuoteString
{
    [self prepareScannerWithString: @"'test'"];
    [self assertValidString: @"test"];
}

- (void)testScanDoubleQuoteString
{
    [self prepareScannerWithString: @"\"test\""];
    [self assertValidString: @"test"];
}

- (void)testScanEscapedQuotes
{
    [self prepareScannerWithString: @"\"test\\\"string\""];
    [self assertValidString: @"test\"string"];
}

- (void)testScanEscapedBackslash
{
    [self prepareScannerWithString: @"\"test\\\\string\""];
    [self assertValidString: @"test\\string"];
}

- (void)testWhitespaceBeforeString
{
    [self prepareScannerWithString: @" 'testing'"];
    [self assertValidString: @"testing"];
}

#pragma mark Identifiers

- (void)testScanningIdentifier
{
    [self prepareScannerWithString: @"ident"];
    [self assertValidIdentifier: @"ident"];
}

- (void)testScanIdentifierWithDigits
{
    [self prepareScannerWithString: @"ident123"];
    [self assertValidIdentifier: @"ident123"];
}

- (void)testIdentifierCannotStartWithDigit
{
    [self prepareScannerWithString: @"123ident"];

    assertThatBool( [scanner scanIdentifier: NULL], is( @NO ) );
}

- (void)testIdentifierWithUnderscore
{
    [self prepareScannerWithString: @"_ident1_23"];
    [self assertValidIdentifier: @"_ident1_23"];
}

#pragma mark - Atoms

- (void)testScanAtom
{
    [self prepareScannerWithString: @":testing"];
    [self assertValidAtom: @"testing"];
}

- (void)testFailToScanAtomWithoutColon
{
    [self prepareScannerWithString: @"testing"];
    assertThatBool( [scanner scanAtom: nil], is( @NO ) );
}

- (void)testScanAtomWithQuotedString
{
    [self prepareScannerWithString: @":'test 123'"];
    [self assertValidAtom: @"test 123"];
}

- (void)testScanningAtomWithoutNameFails
{
    [self prepareScannerWithString: @":"];
    assertThatBool( [scanner scanAtom: NULL], is( @NO ) );
}

- (void)testFailedAtomLeavesRest
{
    [self prepareScannerWithString: @":123"];
    assertThatBool( [scanner scanAtom: NULL], is( @NO ) );
    assertThat( scanner.tailString, is( @":123" ) );
}

- (void)testIgnoringWhitespaceBeforeAtom
{
    [self prepareScannerWithString: @" :atom"];
    [self assertValidAtom: @"atom"];
}

- (void)testFailScanningAtomWithWhitespaceAfterColon
{
    [self prepareScannerWithString: @": atom2"];
    assertThatBool( [scanner scanAtom: NULL], is( @NO ) );
}

#pragma mark - Symbols

- (void)testScanComma
{
    [self prepareScannerWithString: @","];
    assertThatBool( [scanner scanComma], is( @YES ) );
}

- (void)testScanArrow
{
    [self prepareScannerWithString: @"=>"];
    assertThatBool( [scanner scanArrow], is( @YES ) );
}

- (void)testScanArrowFailsWithWhitespaceBetween
{
    [self prepareScannerWithString: @"= >"];
    assertThatBool( [scanner scanArrow], is( @NO ) );
}

- (void)testScanArrowWithWhitespaceBefore
{
    [self prepareScannerWithString: @" \t=>"];
    assertThatBool( [scanner scanArrow], is( @YES ) );
}

#pragma mark - Misc

- (void)testTailString
{
    [self prepareScannerWithString: @"some random string"];
    assertThat( scanner.tailString, is( @"some random string" ) );
}

#pragma mark - Helpers

- (void)prepareScannerWithString: (NSString *)testString
{
    scanner = [[SWPodfileScanner alloc] initWithString: testString];
}

- (void)assertValidIdentifier: (NSString *)identifier
{
    NSString *result = nil;
    assertThatBool( [scanner scanIdentifier: &result], is( @YES ) );
    assertThat( result, is( identifier ) );
}

- (void)assertValidAtom: (NSString *)atom
{
    NSString *result = nil;
    assertThatBool( [scanner scanAtom: &result], is( @YES ) );
    assertThat( result, is( atom ) );
}

- (void)assertValidString: (NSString *)string
{
    NSString *result = nil;
    assertThatBool( [scanner scanString: &result], is( @YES ) );
    assertThat( result, is( string ) );
}

@end


text:
package chanacceptor

// ChanAcceptError is an error that it returned when an external channel
// acceptor rejects a channel. Note that this error type is whitelisted and will
// be delivered to the peer initiating a channel.
type ChanAcceptError struct {
	error
}


text:
package org.apache.geode.internal.cache.tier.sockets;

import static org.apache.geode.distributed.ConfigurationProperties.*;

import java.util.Properties;

import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
import org.junit.experimental.categories.Category;

import org.apache.geode.internal.cache.OffHeapTestUtil;
import org.apache.geode.test.dunit.Invoke;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.junit.categories.DistributedTest;

/**
 * Runs force invalidate eviction tests with off-heap regions.
 *
 * @since Geode 1.0
 */
@Category({DistributedTest.class, ClientSubscriptionTest.class})
public class ForceInvalidateOffHeapEvictionDUnitTest extends ForceInvalidateEvictionDUnitTest {

  public ForceInvalidateOffHeapEvictionDUnitTest() {
    super();
  }

  @Override
  public final void preTearDownAssertions() throws Exception {
    SerializableRunnable checkOrphans = new SerializableRunnable() {

      @Override
      public void run() {
        if (hasCache()) {
          OffHeapTestUtil.checkOrphans();
        }
      }
    };
    Invoke.invokeInEveryVM(checkOrphans);
    checkOrphans.run();
  }

  @Override
  public Properties getDistributedSystemProperties() {
    Properties properties = super.getDistributedSystemProperties();
    properties.setProperty(OFF_HEAP_MEMORY_SIZE, "100m");

    return properties;
  }

  @Override
  public boolean isOffHeapEnabled() {
    return true;
  }
}


text:
npm install --save-dev foreman
Touch a Procfile
echo 'web: node server.js'
Add "nf": "nf start" to scripts in package.json
nf start and visit localhost:5000 to see application running
touch .env file


text:
/* eslint-env node */
'use strict';
const API_VERSION = require('./api-version.js');

module.exports = function(environment) {
  let ENV = {
    modulePrefix: 'ilios',
    environment,
    rootURL: '/',
    locationType: 'auto',
    redirectAfterShibLogin: true,
    contentSecurityPolicy: {
      'default-src': ["'none'"],
      'script-src':  ["'self'", "'unsafe-eval'", 'www.google-analytics.com'],
      'font-src':    ["'self'"],
      'connect-src': ["'self'", 'www.google-analytics.com'],
      'img-src':     ["'self'", 'data:', 'www.google-analytics.com'],
      'style-src':   ["'self'", "'unsafe-inline'"],
      'media-src':   ["'self'"]
    },
    flashMessageDefaults: {
      timeout: 2000,
      extendedTimeout: 3000,
      types: [ 'success', 'warning', 'info', 'alert' ]
    },
    'ember-simple-auth': {
      authorizer: 'authorizer:token'
    },
    'ember-simple-auth-token': {
      serverTokenEndpoint: '/auth/login',
      serverTokenRefreshEndpoint: '/auth/token',
      tokenPropertyName: 'jwt',
      authorizationHeaderName: 'X-JWT-Authorization',
      authorizationPrefix: 'Token ',
      refreshLeeway: 300
    },
    i18n: {
      defaultLocale: 'en'
    },
    serverVariables: {
      tagPrefix: 'iliosconfig',
      vars: ['api-host', 'api-name-space'],
      defaults: {
        'api-name-space': process.env.ILIOS_FRONTEND_API_NAMESPACE || 'api/v1',
        'api-host': process.env.ILIOS_FRONTEND_API_HOST || null,
      }
    },
    'ember-metrics': {
      includeAdapters: ['google-analytics']
    },
    moment: {
      // Full list of locales: https://github.com/moment/moment/tree/2.10.3/locale
      includeLocales: ['es', 'fr']
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        String: true,
        Array: true,
        Function: false,
        Date: false,
      }
    },

    APP: {
      apiVersion: API_VERSION,
      // Here you can pass flags/options to your application instance
      // when it is created
    },
    //Hide a feature while it is in development
    IliosFeatures: {
      allowAddNewUser: true,
      schoolSessionAttributes: true,
      accessCourseVisualizations: true,
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV.contentSecurityPolicy['script-src'].push("'unsafe-inline'");
    ENV.redirectAfterShibLogin = false;

    //Remove mirage in developemnt, we only use it in testing
    ENV['ember-cli-mirage'] = {
      enabled: false
    };

    ENV.IliosFeatures.accessCourseVisualizations = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.contentSecurityPolicy['script-src'].push("'unsafe-inline'");
    ENV.flashMessageDefaults.timeout = 100;
    ENV.flashMessageDefaults.extendedTimeout = 100;
    ENV.serverVariables.defaults['api-name-space'] = 'api';
    ENV.serverVariables.defaults['api-host'] = '';

    ENV.IliosFeatures.accessCourseVisualizations = true;

    //silence warnings in tests when dates are not initialized
    ENV.moment.allowEmpty = true;
  }

  /*
  if (environment === 'production') {
  }

  if (environment === 'staging') {
  }
  */

  if (environment === 'preview') {
    ENV.IliosFeatures.accessCourseVisualizations = true;
  }

  //add our API host to the list of acceptable data sources
  ENV.contentSecurityPolicy['connect-src'].push(ENV.serverVariables.defaults['api-host']);

  return ENV;
};


text:
package ar.com.javacuriosities.algorithms.graph.traverse;

import ar.com.javacuriosities.algorithms.graph.Graph;
import ar.com.javacuriosities.algorithms.graph.undirected.adjacency_list.GraphAdjacencyList;

public class Main {
    public static void main(String[] args) {
        DFS dfs = new DFS();
        BFS bfs = new BFS();

        Graph<Integer> graph = new GraphAdjacencyList<>();

        graph.addEdge(1, 2);
        graph.addEdge(1, 3);
        graph.addEdge(1, 4);
        graph.addEdge(2, 5);
        graph.addEdge(2, 6);

        System.out.println("Graph Adjacencies");
        System.out.println(graph);

        System.out.println("DFS Iterative Traverse");
        dfs.iterativeTraverse(graph, 1);

        System.out.println("DFS Recursive Traverse");
        dfs.recursiveTraverse(graph, 1);

        System.out.println("BFS Traverse");
        bfs.traverse(graph, 1);
    }
}


text:
#ifndef ADHOCHANDLER_H__
#define ADHOCHANDLER_H__

#include "adhoc.h"

namespace gloox
{

  /**
   * @brief A virtual interface for an Ad-hoc Command users according to @xep{0050}.
   *
   * Derived classes can be registered with the Adhoc object to receive notifications
   * about Adhoc Commands remote entities support.
   *
   * @author Jakob Schröter <js@camaya.net>
   * @since 0.9
   */
  class GLOOX_API AdhocHandler
  {
    public:
      /**
       * Virtual destructor.
       */
      virtual ~AdhocHandler() {}

      /**
       * This function is called in response to a call to Adhoc::checkSupport().
       * @param remote The queried remote entity's JID.
       * @param support Whether the remote entity supports Adhoc Commands.
       * @param context A user defined context.
       */
      virtual void handleAdhocSupport( const JID& remote, bool support, int context ) = 0;

      /**
       * This function is called in response to a call to Adhoc::getCommands()
       * and delivers a list of supported commands.
       * @param remote The queried remote entity's JID.
       * @param commands A map of supported commands and their human-readable name.
       * @param context A user defined context.
       * The map may be empty.
       */
      virtual void handleAdhocCommands( const JID& remote, const StringMap& commands, int context ) = 0;

      /**
       * This function is called in response to a call to Adhoc::getCommands() or
       * Adhoc::checkSupport() or Adhoc::execute() in case the respective request returned
       * an error.
       * @param remote The queried remote entity's JID.
       * @param error The error condition. May be 0.
       * @param context A user defined context.
       */
      virtual void handleAdhocError( const JID& remote, const Error* error, int context ) = 0;

      /**
       * This function is called in response to a remote command execution.
       * @param remote The remote entity's JID.
       * @param command The command being executed.
       * @param context A user defined context.
       */
      virtual void handleAdhocExecutionResult( const JID& remote, const Adhoc::Command& command, int context ) = 0;
  };

}

#endif // ADHOCHANDLER_H__


text:
Zend Framework 2.0.0beta5 Released!

The Zend Framework community is pleased to announce the immediate availability
of Zend Framework 2.0.0beta5. Packages and installation instructions are
available at:

    http://packages.zendframework.com/

The Zend Framework community is pleased to announce the immediate availability
of Zend Framework 2.0.0beta5. Packages and installation instructions are
available at:

    http://packages.zendframework.com/

This is the fifth and last in a series of planned beta releases. The beta
release cycle has followed the "gmail" style of betas, whereby new features
have been added in each new release, and backwards compatibility (BC) has not
been guaranteed. The desire has been for developers to adopt and work with new
components as they are shipped, and provide feedback so we can polish the
distribution.

Our plan at this time is to do some cleanup of the repository, fix some
outstanding issues and features, migrate documentation to a new repository and
format, and then begin the release candidate process. At this time, we
anticipate few if any BC breaks between now and the first release candidate (RC).
Applications built today on beta5 will operate in the way we expect them to for
the stable release.

Beta5 had a rigorous and busy schedule. We tackled a number of consistency
issues, and solidified the security the framework offers via several fixes and
the new Escaper component. We processed over 400 pull requests again, in a
shorter timeframe than we had for beta4; the community really pulled together
to get this release out the door.

    There are three primary new features for the release:

Zend\Escaper, which provides an OWASP-compliant solution
        for context-specific escaping mechanisms targetting HTML, HTML attributes,
        URLs, CSS, and JavaScript.

Zend\I18n, which leverages <acronym title="PHP Hypertext
        Preprocessor">PHP</acronym>'s ext/intl extension to
        provide localization, and also provides a new translation component.

Zend\Form now has new annotation support, allowing you
        to define annotations in your domain entities that can then be used
        to build a form and its related input filter and hydrator. Annotation
        support now has a dependency on Doctrine\Common's annotation
        library, for our default annotation syntax parser.

    2.0.0beta5 had many more changes, as you can see from the release changelog:

 - Escaper component (Padraic Brady)
    - Provides context-specific escaping mechanisms for HTML content,
      HTML attributes, URLs, CSS, and JavaScript.
    - BC BREAK: The escape() view helper was removed, and replaced with
      escapeHtml(), escapeHtmlAttr(), escapeJs(), escapeCss(), and
      escapeUrl() implementations.
 - New I18n component (Ben Scholzen, Chris Martin, Dennis Portnov,
   Matthew Weier O'Phinney)
    - New component leveraging PHP's ext/intl extension to provide
      internationalization (i18n) and localization (L10n) features and
      capabilities to applications.
    - LEVERAGES:
        - DateTime, DateTimezone, IntlDateFormatter
        - Locale
        - NumberFormatter
    - BC BREAK: REMOVES the following components:
        - Zend\Currency
        - Zend\Date
        - Zend\Locale
        - Zend\Measure
        - Zend\Translator
        - All filters, validators, and view helpers that relied on the
          above.
    - PROVIDES:
        - Zend\I18n\Translator, including support for gettext and
          PHP-array-based translations (more are planned).
        - Zend\I18n\Filter, containing localized filtering capabilites
          for Alnum (alphanumeric), Alpha (alphabetic), and NumberFormat
          (numerical strings).
        - Zend\I18n\Validator, containing localized validation
          capabilities for Alnum (alphanumeric), Alpha (alphabetic),
          Iban (international bank account number standard), Int
          (integer), and PostCode (localized postal codes).
        - Zend\I18n\View, containing localized view helpers for
          CurrencyFormat, DateFormat, NumberFormat, Translate, and
          TranslatePlural.
 - Db layer additions (Ralph Schindler, Rob Allen, Guillaume Metayer,
   Sascha Howe, Chris Testroet, Evan Coury, Ben Youngblood)
    - Metadata support
    - Postgresql adapter/driver
    - New HydratingResultSet, allowing the ability to specify a custom
      hydrator (from Zend\Stdlib\Hydrator) for hydrating row objects.
    - Many bugfixes and stabilizations
 - Form additions (Matthew Weier O'Phinney, Michaël Gallego, Yanick Rochon)
    - Annotations support: Ability to use annotations with a domain
      object in order to define a form, fieldsets, elements, inputs and
      input filters, and more.
    - Hydration of fieldsets; fieldsets may compose their own hydrators
      if desired.
    - Collection support; allows multiple instances of the same
      fieldset. As an example, you might have an interface that
      allows adding a set of form elements via an XHR call; on the
      backend, these would be defined as a collection, allowing
      arbitrary numbers of these fieldsets to be submitted.
    - New view helpers covering most HTML5-specific element types, most
      XHTML-specific element types. Additionally, a number of the
      HTML5-specific element types now have Element implementations to
      create turn-key solutions that include validation and filtering.
    - BC BREAK: Options support. Many attributes were being used not as
      HTML attributes but to define behavior. The ElementInterface now
      has an accessor and mutator for options. Examples of options
      include labels for non-radio/checkbox/select elements, the CAPTCHA
      adapter for CAPTCHA elements, CSRF tokens, etc. If you were
      defining labels in your forms, please move the label and label
      attributes definitions from the "attributes" to the "options" of
      the element, fieldset, or form.
    - BC BREAK: new interface, ElementPrepareAwareInterface, defining
      the method "prepareElement(Form $form)". The FieldsetInterface,
      and, by extension, FormInterface, extend this new interface. It is
      used to allow preparing elements prior to creating a
      representation.
 - MVC additions (Kyle Spraggs, Evan Coury, Matthew Weier O'Phinney)
    - New "Params" controller plugin. Allows retrieving query, post,
      cookie, header, and route parameters. Usage is
      $this->params()->fromQuery($name, $default).
    - New listener, Zend\Mvc\ModuleRouteListener. When enabled, if a
      route match contains a "\__NAMESPACE__" key, that namespace value
      will be prepended to the value of the "controller" key. This
      should typically be used in the root route for a given module, to
      ensure controller names do not clash.
    - Bootstrap simplification. A new "init()" method was created that
      accepts the path to a configuration file, and then creates and
      bootstraps the application; this eliminates all common boilerplate
      for the bootstrap scripts.
 - Hydrator changes (Adam Lundrigan)
    - BC BREAK: the ClassMethods hydrator now assumes by default that
      it should convert between underscore_separated names and
      camelCase.
 - BC BREAK: Doctrine Annotations Parser (Matthew Weier O'Phinney, Marco
   Pivetta, Guilherme Blanco)
    - Zend\Code\Annotation now has a dependency on Doctrine\Common for
      its annotation parser.
    - Annotations now conform to Doctrine's standards by default, but
      the AnnotationManager in ZF2 allows attaching alternate parsers
      for specific annotation types.
 - BC BREAK: Removal of Plugin Broker usage (Matthew Weier O'Phinney,
   Evan Coury)
    - All uses of the Plugin Broker / Plugin Class Locator combination
      were removed. A new class, Zend\ServiceManager\AbstractPluginManager,
      was created and used to replace all previous usages of the plugin
      broker. This provides more flexibility in creation of plugins, as
      well as reduces the number of APIs developers need to learn.
    - Configuration of plugin managers is now done at the top-level. All
      plugin manager configuration follows the format utilized by
      Zend\ServiceManager\ServiceConfiguration, and
      Zend\ModuleManager\Listener\ServiceListener has been updated to
      allow informing it of plugin manager instances it should manage,
      as well as the configuration key to utilize.
 - BC BREAK: Coding Standards (Maks3w, Sascha Prolic, Rob Allen)
    - Renamed most abstract classes to prefix them with the term
      "Abstract". In particular, ActionController and RestfulController
      are now AbstractActionController and AbstractRestfulController.
    - Renamed getters in HTTP, EventManager, and Mail components. These
      components were using accessors such as "events()", "query()",
      "headers()", etc. All such accessors were renamed to prepend
      "get", and, in the case of "events()", renamed to indicate the
      actual object retrieved ("getEventManager()").
 - SECURITY FIX: XmlRpc (Matthew Weier O'Phinney)
    - A security issue arising from XML eXternal Entity (XXE) injection
      was patched; see http://framework.zend.com/security/advisory/ZF2012-01

    The skeleton
    application and a skeleton
    module have been updated for 2.0.0beta5, and are a
    great place to look to help get you started. You may also want to check out the quick start
    guide to the MVC.

    As a reminder, all ZF2 components are also available individually as Pyrus AND composer packages;
    packages.zendframework.com is our official channel for both package formats.

I'd like to thank each and every person who has contributed ideas, feedback,
pull requests (no pull request is too small!), testing, and more -- every
contribution is leading to a better, more stable, polished framework.

Posted on 2012-07-06 12:30:00.

Last updated on 2012-07-06 12:30:00.

Tags for this entry


text:
#!/usr/bin/env node

var argv = require('minimist')(process.argv.slice(2));
if (!argv.dir_path || ! argv.locale_dir_path || !argv.locale_codes) {
    console.log('node i18n.js --dir_path={somepath} [--dir_path={anotherpath}] --locale_dir_path={somepath} --locale_codes={nl,fr,es} --mode={js|json}');
}
var UglifyJS = require("uglify-js");
var fs = require("fs");
var path = require("path");
var dirs = argv.dir_path,
    locale_dir = argv.locale_dir_path,
    locale_codes = argv.locale_codes.split(','),
    mode = argv.mode || 'js',
    clean = argv.clean,
    default_values = argv.default_values,  // Useful for json mode in Transifex
    ast = null,
    code = "",
    strings = [];
if (typeof dirs === 'string') dirs = [dirs];
dirs.forEach(function (dir_path) {
    var files = fs.readdirSync(dir_path);
    files.forEach(function(file){
        if (path.extname(file) !== '.js') return;
        code += fs.readFileSync(path.join(dir_path, file), "utf8");
    });
});
ast = UglifyJS.parse ?
    UglifyJS.parse(code) :
    UglifyJS.minify(code, {
        parse: {},
        compress: false,
        mangle: false,
        output: {
            ast: true,
            code: false  // optional - faster if false
        }
    }).ast;

ast.walk(new UglifyJS.TreeWalker(function (node) {
    if (node instanceof UglifyJS.AST_Call && node.expression.property == "_") {
        if (typeof node.args[0].value !== "undefined") {
            strings.push(node.args[0].value);
        }
    }
}));
strings.sort();

var toJS = function (locale_code, locale_path) {
    /* Needed to eval the locale files */
    L = {
        registerLocale: function (name, strings) {
            translations = strings;
        }
    };
    var translations = {},
        raw_content = "var " + locale_code + " = ";
    if (fs.existsSync(locale_path)) {
        // Will call our monkeypatched registerLocale
        eval(fs.readFileSync(locale_path, "utf8"));
    }
    strings.forEach(function (str) {
        if (!translations[str]) {
            translations[str] = default_values ? str : "";
        }
    });
    if (clean) {
        Object.keys(translations).forEach(function (str) {
            if (strings.indexOf(str) === -1) {
                delete translations[str];
            }
        });
    }
    raw_content += JSON.stringify(translations, null, 4);
    raw_content += ";\n\n";
    raw_content += 'L.registerLocale("' + locale_code + '", '+ locale_code + ');';
    return raw_content;
};

var toJSON = function (locale_code, locale_path) {
    var translations = {};
    if (fs.existsSync(locale_path)) {
        translations = JSON.parse(fs.readFileSync(locale_path, "utf8"));
    }
    strings.forEach(function (str) {
        if (!translations[str]) {
            translations[str] = default_values ? str : "";
        }
    });
    if (clean) {
        Object.keys(translations).forEach(function (str) {
            if (strings.indexOf(str) === -1) {
                delete translations[str];
            }
        });
    }
    return JSON.stringify(translations, null, 4);
};
locale_codes.forEach(function (locale_code) {
    var locale_path = path.join(locale_dir, locale_code + "." + mode);
    var func = (mode === "json")? toJSON: toJS;
    var raw_content = func(locale_code, locale_path);
    process.stdout.write('Writing file for locale "' + locale_code + '"\n');
    fs.writeFileSync(locale_path, raw_content, 'utf8');
});


text:
package org.jetbrains.plugins.scala.lang.lexer

import com.intellij.psi.xml.XmlTokenType
import junit.framework.TestCase
import org.junit.Assert._

class ScalaXmlTokenTypesTest extends TestCase {

  def testXmlTokenTypesExistInPlatformAnalog(): Unit = {
    val fields = org.jetbrains.plugins.scala.lang.lexer.ScalaXmlTokenTypes.getClass.getFields
    val tokenFields = fields.filter(_.getType == classOf[ScalaXmlLexer.ScalaXmlTokenType])

    val classFromPlatform = classOf[XmlTokenType]
    tokenFields.foreach { field =>
      try {
        classFromPlatform.getField(field.getName)
      } catch {
        case _: NoSuchFieldException =>
          fail(s"no field ${field.getName} found in class $classFromPlatform")
      }
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright (c) 2015 Ngewi Fet <ngewif@gmail.com>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:animateLayoutChanges="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.common.FormActivity">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout android:id="@+id/budget_amount_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="200dp"
            android:orientation="vertical"/>
    </ScrollView>

    <android.inputmethodservice.KeyboardView android:id="@+id/calculator_keyboard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:visibility="gone" />
</RelativeLayout>


text:
const {SourceError} = require('./sourceerror');
const path = require('path');

/** @enum {stromg} */
const DependencyType = {
  /** A file containing goog.provide statements. */
  CLOSURE_PROVIDE: 'closure provide',
  /** A file containing a goog.module statement. */
  CLOSURE_MODULE: 'closure module',
  /** An ES6 module file. */
  ES6_MODULE: 'es6 module',
  /**
   * A JavaScript file that has no goog.provide/module and is not an ES6 module.
   */
  SCRIPT: 'script',
};

/**
 * A Dependency in the dependency graph (a vertex).
 */
class Dependency {
  /**
   * @param {!DependencyType} type
   * @param {string} filepath
   * @param {!Array<string>} closureSymbols
   * @param {!Array<!Import>} imports
   * @param {string=} language
   */
  constructor(type, filepath, closureSymbols, imports, language = 'es3') {
    /** @const */
    this.type = type;

    /**
     * Full path of this file on disc.
     * @const
     */
    this.path = path.resolve(filepath);

    /**
     * Array of Closure symbols this file provides.
     * @const
     */
    this.closureSymbols = closureSymbols;

    /**
     * Array of imports in this file.
     * @const
     */
    this.imports = imports;

    for (const i of this.imports) {
      i.from = this;
    }

    /**
     * The language level of this file; e.g. "es3", "es6", etc.
     * @const
     */
    this.language = language;
  }
}

/**
 * Generic super class for all types of imports. This acts as an edge in the
 * dependency graph between two dependencies.
 *
 * @abstract
 */
class Import {
  /**
   * @param {string} symOrPath
   */
  constructor(symOrPath) {
    /**
     * Dependency this import is contained in.
     * @type {!Dependency}
     */
    this.from;
    /**
     * The Closure symbol or path that is required.
     * @const
     */
    this.symOrPath = symOrPath;
  }

  /**
   * Asserts that this import edge is valid.
   * @param {!Dependency} to
   * @abstract
   */
  validate(to) {}

  /**
   * @return {boolean}
   * @abstract
   */
  isGoogRequire() {}

  /**
   * @return {boolean}
   * @abstract
   */
  isEs6Import() {}
}

/** An import using goog.require. */
class GoogRequire extends Import {
  /** @override */
  validate(to) {
    for (const sym of to.closureSymbols) {
      if (sym === this.symOrPath) {
        return;
      }
    }

    throw new SourceError(
        `Invalid dependency edge: File ${to.path} does ` +
            `not provide symbol ${this.symOrPath}.`,
        this.from.path);
  }

  /** @override */
  isGoogRequire() {
    return true;
  }

  /** @override */
  isEs6Import() {
    return false;
  }
}

/** An ES6 import (or export from). */
class Es6Import extends Import {
  /** @override */
  toString() {
    return `import|export '${this.symOrPath}'`;
  }

  /** @override */
  validate(to) {
    if (to.type !== DependencyType.ES6_MODULE) {
      throw new SourceError(
          'Cannot import non-ES6 module: ' + to.path, this.from.path);
    }
  }

  /** @override */
  isGoogRequire() {
    return false;
  }

  /** @override */
  isEs6Import() {
    return true;
  }
}

/**
 * Interface for resolving module specifiers.
 * @interface
 */
class ModuleResolver {
  /**
   * @param {string} fromPath The path of the module that is doing the
   *     importing.
   * @param {string} importSpec The raw text of the import.
   * @return {string} The resolved path of the referenced module.
   */
  resolve(fromPath, importSpec) {}
}

/** @implements {ModuleResolver} */
class PathModuleResolver {
  /** @override */
  resolve(fromPath, importSpec) {
    return path.resolve(path.dirname(fromPath), importSpec);
  }
}

class InvalidCycleError extends Error {
  /**
   * @param {!Array<!Dependency>} deps
   */
  constructor(deps) {
    super(
        'There exists at least one cycle with a Closure file, which is ' +
        'invalid. Files involved in cycle(s):' +
        deps.map(dep => dep.path).join(', '));
    this.deps = deps;
  }
}

/**
 * Dependency graph that provides validation along with a topological sorting
 * of dependencies given an entrypoint.
 *
 * A dependency graph is not validated by default, you must call validate() if
 * you wish to perform validation.
 */
class Graph {
  /**
   * @param {!Array<!Dependency>} dependencies
   * @param {!ModuleResolver=} moduleResolver
   */
  constructor(dependencies, moduleResolver = new PathModuleResolver()) {
    /** @const {!Map<string, !Dependency>} */
    this.depsBySymbol = new Map();
    /** @const {!Map<string, !Dependency>} */
    this.depsByPath = new Map();
    /** @const */
    this.moduleResolver = moduleResolver;

    for (const dep of dependencies) {
      if (this.depsByPath.has(dep.path)) {
        throw new Error('File registered twice? ' + dep.path);
      }
      this.depsByPath.set(dep.path, dep);
      for (const sym of dep.closureSymbols) {
        const previous = this.depsBySymbol.get(sym);
        if (previous) {
          throw new SourceError(
              `The symbol "${sym}" has already been defined at ` +
                  previous.path,
              dep.path);
        }
        this.depsBySymbol.set(sym, dep);
      }
    }
  }

  /**
   * Validates the dependency graph. Throws an error if the graph is invalid.
   *
   * This method uses Tarjan's algorithm to ensure Closure files are not part
   * of any cycle. Check it out:
   * https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
   */
  validate() {
    let index = 0;

    // Map that assigns each dependency an index in visit-order.
    const indexMap = new Map();
    // Stack of dependencies that are potentially part of the current strongly
    // connected component. If any dependency has a back pointer it is kept
    // on the stack. Thus after recursion anything left on the stack above the
    // current dependency is part of the SCC. If the dependency has no back
    // pointer the SCC is created from all dependencies on the stack until the
    // current dependency is popped off and added to the SCC.
    const depStack = new Set();

    const validate = (dep) => {
      const thisIndex = index++;
      indexMap.set(dep, thisIndex);
      let lowIndex = thisIndex;

      depStack.add(dep);

      // We might modify the imports when iterating (drop unrecognized ES6
      // imports), so iterate over a copy.
      for (const i of [...dep.imports]) {
        const to = this.resolve_(i);

        if (!to) {
          if (i.isGoogRequire()) {
            throw new SourceError(`Could not find "${i.symOrPath}".`, dep.path);
          } else {
            // Just drop unrecognized ES6 imports. Assume their entire branch is
            // non-Closure, like a built-in Node module.
            dep.imports.splice(dep.imports.indexOf(i), 1);
            console.warn(
                `Could not find "${i.symOrPath}".` +
                    'Assuming it (and its transitive dependencies) are ' +
                    'non-Closure managed.',
                dep.path);
            continue;
          }
        }

        i.validate(to);

        if (!indexMap.has(to)) {
          // "to" has not been visited, recurse.
          lowIndex = Math.min(lowIndex, validate(to));
        } else if (depStack.has(to)) {
          // "to" is on the stack and thus a part of the SCC.
          lowIndex = Math.min(lowIndex, indexMap.get(to));
        }
        // else visited but not on the stack, so it is not part of the SCC. It
        // is a common dependency of some other tree, but does not reach this
        // dependency and thus is not strongly connected.
      }

      if (lowIndex === thisIndex) {
        let anyClosure = false;
        const deps = [...depStack];
        const scc = [];
        for (let i = deps.length - 1; i > -1; i--) {
          scc.push(deps[i]);
          depStack.delete(deps[i]);
          anyClosure = anyClosure ||
              deps[i].type === DependencyType.CLOSURE_PROVIDE ||
              deps[i].type === DependencyType.CLOSURE_MODULE;
          if (deps[i] === dep) {
            break;
          }
        }
        if (anyClosure && scc.length > 1) {
          throw new InvalidCycleError(scc);
        }
      }

      return lowIndex;
    };

    for (const dep of this.depsByPath.values()) {
      if (!indexMap.has(dep)) {
        validate(dep);
      }
    }
  }

  /**
   * @param {!Import} i
   * @return {!Dependency}
   * @private
   */
  resolve_(i) {
    return i instanceof GoogRequire ?
        this.depsBySymbol.get(i.symOrPath) :
        this.depsByPath.get(
            this.moduleResolver.resolve(i.from.path, i.symOrPath));
  }

  /**
   * Provides a topological sorting of dependencies given the entrypoints.
   *
   * @param {...!Dependency} entrypoints
   * @return {!Array<!Dependency>}
   */
  order(...entrypoints) {
    const deps = [];
    const visited = new Set();

    const visit = (dep) => {
      if (visited.has(dep)) return;
      visited.add(dep);
      for (const i of dep.imports) {
        const next = this.resolve_(i);
        visit(next);
      }
      deps.push(dep);
    };

    for (const entrypoint of entrypoints) {
      visit(entrypoint);
    }

    return deps;
  }
}

module.exports = {
  DependencyType,
  Dependency,
  GoogRequire,
  Es6Import,
  Graph,
  ModuleResolver,
  PathModuleResolver,
  InvalidCycleError,
};


text:
module OmniAuth
  module Strategies
    class Suzuri < OmniAuth::Strategies::OAuth2
      option :client_options, {
        site: 'https://suzuri.jp',
        authorize_url: '/oauth/authorize',
        token_url: '/oauth/token'
      }

      uid  { raw_info["id"] }

      info do
        {
          name:        raw_info["name"],
          displayName: raw_info["displayName"],
          avatarUrl:   raw_info["avatarUrl"]
        }
      end

      extra do
        { raw_info: raw_info }
      end

      def raw_info
        @raw_info ||= access_token.get('/api/v1/user').parsed["user"] || {}
      end

      def callback_url
        full_host + script_name + callback_path
      end
    end
  end
end


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

var ArticleSchema = new mongoose.Schema({
  title: String,
  url: String,
  text: String
});

ArticleSchema.virtual('date').get(function () {
  return this._id.getTimestamp();
});

var ArticleModel = mongoose.model('Article', ArticleSchema);

module.exports = ArticleModel;