text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>9</version>
    </parent>

    <groupId>biz.paluch.logging</groupId>
    <version>1.5.3</version>
    <artifactId>logstash-gelf</artifactId>

    <name>logstash logging connectors</name>
    <url>https://github.com/mp911de/logstash-gelf/</url>
    <inceptionYear>2013</inceptionYear>

    <scm>
        <connection>scm:git://github.com/mp911de/logstash-gelf.git</connection>
        <developerConnection>scm:git:git@github.com:mp911de/logstash-gelf.git</developerConnection>
        <url>http://github.com/mp911de/logstash-gelf/</url>
        <tag>logstash-gelf-1.5.3</tag>
    </scm>

    <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/mp911de/logstash-gelf/issues</url>
    </issueManagement>

    <licenses>
        <license>
            <name>MIT License</name>
            <url>http://www.opensource.org/licenses/mit-license.php</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <distributionManagement>
        <site>
            <id>site</id>
            <url>scm:git:git@github.com:mp911de/logging.paluch.biz.git</url>
        </site>
    </distributionManagement>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>1.6</maven.compiler.target>
        <maven.compiler.source>1.6</maven.compiler.source>
        <logstash-gelf-release-version>1.5.3</logstash-gelf-release-version>

        <github.site.upload.skip>true</github.site.upload.skip>
        <test.withRedis>false</test.withRedis>

        <!-- Versions -->
        <com.googlecode.json-simple.version>1.1.1</com.googlecode.json-simple.version>
        <log4j.version>1.2.14</log4j.version>
        <log4j2.version>2.0</log4j2.version>
        <junit.version>4.11</junit.version>
        <mockito.version>1.9.5</mockito.version>
        <jedis.version>2.5.1</jedis.version>
        <jedis-commons-pool2.version>2.2</jedis-commons-pool2.version>
        <slf4j-api.version>1.7.5</slf4j-api.version>
        <logback-classic.version>1.0.13</logback-classic.version>
        <org.jboss.logmanager.version>1.5.2.Final</org.jboss.logmanager.version>

        <site-plugin.version>3.3</site-plugin.version>
        <maven-javadoc-plugin.version>2.7</maven-javadoc-plugin.version>
        <maven-surefire-plugin.version>2.17</maven-surefire-plugin.version>
        <doxia-module-markdown.version>1.3</doxia-module-markdown.version>
        <maven-project-info-reports-plugin.version>2.7</maven-project-info-reports-plugin.version>
        <cobertura-maven-plugin.version>2.6</cobertura-maven-plugin.version>
        <coveralls-maven-plugin.version>2.2.0</coveralls-maven-plugin.version>
        <maven-release-plugin.version>2.5</maven-release-plugin.version>
        <netty-all.version>4.0.12.Final</netty-all.version>
        <maven-scm-publish-plugin.version>1.1</maven-scm-publish-plugin.version>
        <tempus-fugit.version>1.1</tempus-fugit.version>
        <maven-dependency-plugin.version>2.8</maven-dependency-plugin.version>
        <maven-assembly-plugin.version>2.2-beta-5</maven-assembly-plugin.version>
        <maven-scm-provider-gitexe.version>1.9</maven-scm-provider-gitexe.version>
    </properties>

    <developers>
        <developer>
            <email>mpaluch@paluch.biz</email>
            <name>Mark Paluch</name>
            <timezone>Europe/Berlin</timezone>
            <url>http://www.paluch.biz</url>
        </developer>
    </developers>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>${maven-assembly-plugin.version}</version>
                <executions>
                    <execution>
                        <id>dist-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <descriptor>src/main/assembly/assembly.xml</descriptor>
                    <attach>true</attach>
                    <classifier>module</classifier>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>${maven-dependency-plugin.version}</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <redirectTestOutputToFile>true</redirectTestOutputToFile>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>${maven-release-plugin.version}</version>
                <configuration>
                    <releaseProfiles>sonatype-oss-release</releaseProfiles>
                    <goals>deploy</goals>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.eluder.coveralls</groupId>
                <artifactId>coveralls-maven-plugin</artifactId>
                <version>${coveralls-maven-plugin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>${cobertura-maven-plugin.version}</version>
                <configuration>
                    <format>xml</format>
                    <maxmem>256m</maxmem>
                    <aggregate>true</aggregate>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>${site-plugin.version}</version>
                <configuration>
                    <relativizeDecorationLinks>false</relativizeDecorationLinks>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.doxia</groupId>
                        <artifactId>doxia-module-markdown</artifactId>
                        <version>${doxia-module-markdown.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.maven.scm</groupId>
                        <artifactId>maven-scm-provider-gitexe</artifactId>
                        <version>${maven-scm-provider-gitexe.version}</version>
                    </dependency>
                </dependencies>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-scm-publish-plugin</artifactId>
                <version>${maven-scm-publish-plugin.version}</version>
                <configuration>
                    <scmBranch>gh-pages</scmBranch>
                    <content>${project.build.directory}/site</content>
                    <skipCheckin>${github.site.upload.skip}</skipCheckin>
                </configuration>
                <executions>
                    <execution>
                        <id>publish-scm</id>
                        <goals>
                            <goal>publish-scm</goal>
                        </goals>
                        <phase>post-site</phase>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>${com.googlecode.json-simple.version}</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- log4j2 START -->

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j2.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j2.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- log4j2 END -->

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j-api.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback-classic.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>${netty-all.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.google.code.tempus-fugit</groupId>
            <artifactId>tempus-fugit</artifactId>
            <version>${tempus-fugit.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Redis Client -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${jedis.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>${jedis-commons-pool2.version}</version>
        </dependency>

		<!--JBoss Logging -->
		<dependency>
			<groupId>org.jboss.logmanager</groupId>
			<artifactId>jboss-logmanager</artifactId>
			<version>${org.jboss.logmanager.version}</version>
			<scope>provided</scope>
		</dependency>
    </dependencies>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${maven-javadoc-plugin.version}</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>${maven-project-info-reports-plugin.version}</version>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>index</report>
                            <report>plugin-management</report>
                            <report>distribution-management</report>
                            <report>dependency-info</report>
                            <report>dependencies</report>
                            <report>scm</report>
                            <report>issue-tracking</report>
                            <report>cim</report>
                            <report>dependency-management</report>
                            <report>project-team</report>
                            <report>summary</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
        </plugins>
    </reporting>
</project>


text:
<?php

namespace Magento\Framework\Module\Service;

/**
 * The list of test interfaces.
 */
interface FooV1Interface
{
    public function someMethod();
}
interface BarV1Interface
{
    public function someMethod();
}
interface FooBarV1Interface
{
    public function someMethod();
}
namespace Magento\Framework\Module\Service\Foo;

interface BarV1Interface
{
    public function someMethod();
}

redpajama_set_name: RedPajamaGithub


text:
from .calchasTreeVisitor import CalchasTreeVisitor
from .calchasTreeVisitor import StdSympyFunction
from .calchasTree import FunctionCall as CalchasFunctionCall
from sympy import *

class SympyTreeBuilder(CalchasTreeVisitor):
    def __init__(self):
        super().__init__()

    def visitCalchasId(self, tree, debug=False):
        if not tree.getId() in self.variables.keys():
            if debug :
                print("New id: "+str(tree.getId()))
            self.variables[tree.getId()] = symbols(tree.getId())
        return self.variables[tree.getId()]

    def visitCalchasNumber(self, tree, debug=False):
        if tree.getType() == int:
            return Integer(tree.getNumber())
        return Rational(str(tree.getNumber()))

    def visitCalchasFunctionCall(self, tree, debug=False):
        function = tree.getFunction()
        if isinstance(function, CalchasFunctionCall):
            function = self.visitCalchasTree(function, debug=debug)
            args = tuple(self.visitCalchasTree(e, debug=debug) for e in tree.getArgs())
            return function(*args)
        if not function in self.functions.keys():
            if debug:
                print("New function: "+str(function))
            self.functions[function] = StdSympyFunction(symbols(function, cls=Function), len(tree.getArgs()))
        if not (self.functions[function]).isArity(tree.getArity()):
            if debug:
                print("Syntax error")
            raise SyntaxError
        f = self.functions[function]
        args = tuple(self.visitCalchasTree(e, debug=debug) for e in tree.getArgs())
        if debug:
            print(tuple(type(e) for e in args))
            print(args)
        a = f.callFunctionWithUnrearrangedArgs(args, debug=debug)
        if debug:
            print("visitCalchasFunctionCall: ", end="")
            print(type(a))
            print("                          ", end="")
            print(a)
        return a

    def toSympyTree(self, tree, debug=False):
        if debug:
            print("toSympyTree > tree: ", end="")
            print(tree)
        c = simplify(self.visitCalchasTree(tree, debug=debug))
        return c


text:
package com.twelvemonkeys.imageio.stream;

import javax.imageio.stream.ImageInputStreamImpl;
import java.io.IOException;
import java.io.InputStream;

import static com.twelvemonkeys.lang.Validate.isTrue;
import static com.twelvemonkeys.lang.Validate.notNull;

/**
 * An {@code ImageInputStream} that adapts an {@code InputSteam},
 * by reading directly from the stream without and form of caching or buffering.
 *

 * Note: This is not a general-purpose {@code ImageInputStream}, and is designed for reading large chunks,
 * typically of pixel data, from an {@code InputStream}.
 * It does not support backwards seeking, or reading bits.
 *

 */
public final class DirectImageInputStream extends ImageInputStreamImpl {
    private final InputStream stream;
    private final long length;

    public DirectImageInputStream(final InputStream stream) {
        this(stream, -1L);
    }

    public DirectImageInputStream(final InputStream stream, long length) {
        this.stream = notNull(stream, "stream");
        this.length = isTrue(length >= 0L || length == -1L, length, "negative length: %d");
    }

    @Override
    public int read() throws IOException {
        bitOffset = 0;
        streamPos++;
        return stream.read();
    }

    @Override
    public int read(final byte[] bytes, int off, int len) throws IOException {
        bitOffset = 0;

        int read = stream.read(bytes, off, len);
        if (read > 0) {
            streamPos += read;
        }

        return read;
    }

    @Override
    public void seek(long pos) throws IOException {
        checkClosed();

        if (pos < streamPos) {
            // Handle as if flushedPos == streamPos at any time
            throw new IndexOutOfBoundsException("pos < flushedPos");
        }

        bitOffset = 0;

        while (streamPos < pos) {
            long skipped = stream.skip(pos - streamPos);

            if (skipped <= 0) {
                break;
            }

            streamPos += skipped;
        }
    }

    @Override
    public long getFlushedPosition() {
        // Handle as if flushedPos == streamPos at any time
        return streamPos;
    }

    @Override
    public long length() {
        return length;
    }

    @SuppressWarnings("RedundantThrows")
    @Override
    public int readBit() throws IOException {
        throw new UnsupportedOperationException("Bit reading not supported");
    }

    @SuppressWarnings("RedundantThrows")
    @Override
    public long readBits(int numBits) throws IOException {
        throw new UnsupportedOperationException("Bit reading not supported");
    }

    @Override
    public void close() throws IOException {
        // We could seek to EOF here, but the usual case is we know where the next chunk of data is

        stream.close();
        super.close();
    }
}


text:
FileIcon
========

FileIcon is a full CSS configurable file icon.

Usage
-----

Output:

![FileIcon](FileIcon.png)


text:
class PanelOptions(object):
    """
    Each Panel has an instance of PanelOptions at panel._meta
    """
    def __init__(self, meta):
        self.meta = meta
        self.dimensions = {}
        self.title = ''
        self.event_type = ''
        self.routing_key = ''

    def contribute_to_class(self, cls, name):
        cls._meta = self
        self.title = getattr(self.meta, 'title', cls.__name__)
        self.event_type = getattr(self.meta, 'event_type', self.title.replace(' ', '_')).lower()
        self.routing_key = getattr(self.meta, 'routing_key', 'tapz.event.%s' % self.event_type)

    def get_dimension(self, name):
        return self.dimensions[name]


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import 'hammerjs';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AgmCoreModule } from '@agm/core';

import { AppComponent } from './app.component';
import { ToolbarComponent } from './toolbar/toolbar.component';
import { AccountComponent } from './account/account.component';
import { MapComponent } from './map/map.component';
import { AppRoutingModule } from './app-routing.module'
import { MdInputModule } from '@angular/material';
import { MdAutocompleteModule } from '@angular/material';
import { BookComponent } from './book/book.component';

@NgModule({
  declarations: [
    AppComponent,
    ToolbarComponent,
    AccountComponent,
    MapComponent,
    BookComponent
  ],
  imports: [
    MdAutocompleteModule,
    MdInputModule,
    BrowserModule,
    [BrowserAnimationsModule],
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule,
    AgmCoreModule.forRoot({
      apiKey: 'AIzaSyCjU3_9873uVzSoXU50oV6pYyB1W0ExKBE'
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {

}


text:
/* global define */
define(['./deps', './Library', './mergeInto', 'tmclasses/tmclasses', './__'], function(__deps, __Library, __mergeInto, __tmclasses, __tmlib){
	var __Array = __deps.Array;
	var __undefined = __deps.undefined;

	/*
	Library: objects

	Library for working with javascript objects
	*/
	var __objects = new __Library({
		/*
		Function: addProperties

		Add properties to an object.

		Parameters:
			object(Object): Object to add properties to
			properties(Map): Map of named properties with values to add to object
		*/
		addProperties: function(_object, _properties){
			for(var key in _properties){
				if(_properties.hasOwnProperty(key)){
					this.addProperty(_object, key, _properties[key]);
				}
			}
		}
		/*
		Function: addProperty

		Add a property to an object.  From tmclasses.
		*/
		,addProperty: __tmclasses.addProperty

		/*
		Function: getLength

		Gets the number of keys an object has, as if it were an array.  Was __.lib.getObjectLength

		Parameters:
			object(object): object to check 'length' of
			doCountInherited(boolean): count inherited properties if true, otherwise just hasOwnProperty properties
		*/
		,getLength: function(_object, _doCountInherited){
			if(_doCountInherited === __undefined){
				_doCountInherited = false;
			}
			var length = 0;
			for(var key in _object){
				if(_object.hasOwnProperty(key) || _doCountInherited){
					++length;
				}
			}
			return length;
		}

		/*
		Function: hasKey

		Determine if object/array has at least one of given key(s).    Uses 'hasOwnProperty', so keys must be object's own property (may want to change this for dealing with inheritance).  Was __.lib.hasKey

		Parameters:
			needles(String|Array): string key or array of keys to ensure exist
			haystack(Array|Object): object to look for key(s) in

		Dependencies:
			__.lib.each (should remove for efficiency)
			__.lib.isArray (could do typoef)
		*/
		,hasKey: function(_needles, _haystack){
			if(!__tmlib.lib.isArray(_needles)){
				_needles = [_needles];
			}
			__tmlib.lib.each(_needles, function(argValue){
				if(_haystack.hasOwnProperty(argValue)){
					return true;
				}
			});
			return false;
		}

		/*
		Function: hasKeys

		Determine if object/array has given key(s).  Uses 'hasOwnProperty', so keys must be object's own property (may want to change this for dealing with inheritance).  Was __.lib.hasKeys

		Parameters:
			needles(String|Array): string key or array of keys to ensure exist
			haystack(Array|Object): object to look for key(s) in

		Dependencies:
			__.lib.each (should remove for efficiency)
			__.lib.isArray (could do typoef)
		*/
		,hasKeys: function(_needles, _haystack){
			var _has = true;
			if(!__tmlib.lib.isArray(_needles)){
				_needles = [_needles];
			}
			__tmlib.lib.each(_needles, function(argValue){
				if(!(_has && _haystack.hasOwnProperty(argValue))){
					_has = false;
				}
			});
			return _has;
		}

		/*
		Function: merge

		Merge all keys from all passed in objects into a new object, preferring keys to the right.

		Paramaters:
			any number of objects to merge into a new object, with properties from objects to the right overriding those to the left.  Was __.lib.merge

		Returns:
			new object with all keys of all passed in objects

		Sources:
			http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically

		See Also:
			<mergeInto>
		*/
		,merge: function(){
			var _args = arguments;
			var _object = {};
			__Array.prototype.unshift.call(_args, _object);

			return __mergeInto(_args);
		}

		/*
		Function: mergeInto

		Defined in 'core/mergeInto' because it is needed for many base objects.
		*/
		,mergeInto: __mergeInto
	});

	//--add to tmlib and export
	__tmlib.__('.core', {objects: __objects});
	return __objects;
});


text:
'use strict';

/*
 * Defining the Package
 */
var Module = require('meanio').Module;

var PandaPackage = new Module('pandaPackage');

/*
 * All MEAN packages require registration
 * Dependency injection is used to define required modules
 */

 // Make sure this one loads first by adding 'system'
PandaPackage.register(function(app, auth, database, system) {

  //We enable routing. By default the Package Object is passed to the routes
  PandaPackage.routes(app, auth, database);

  //We are adding a link to the main menu for all authenticated users
  PandaPackage.menus.add({
    title: 'hello',
    link: 'link1',
    roles: ['authenticated','anonymous'],
    menu: 'mymain'
  });

  PandaPackage.menus.add({
    title: 'hello2',
    link: 'link2',
    roles: ['authenticated','anonymous'],
    menu: 'mymain'
  });

  PandaPackage.menus.add({
    title: 'pandaPackage3',
    link: 'link3',
    roles: ['authenticated','anonymous'],
    menu: 'mymain'
  });

  // Set views path, template engine and default layout
  // I COPIED AND PASTED FROM CORE FILES
  app.set('views', __dirname + '/server/views');

  PandaPackage.aggregateAsset('css', 'pandaPackage.css');
  PandaPackage.angularDependencies(['mean.system']);

  /**
    //Uncomment to use. Requires meanio@0.3.7 or above
    // Save settings with callback
    // Use this for saving data from administration pages
    PandaPackage.settings({
        'someSetting': 'some value'
    }, function(err, settings) {
        //you now have the settings object
    });

    // Another save settings example this time with no callback
    // This writes over the last settings.
    PandaPackage.settings({
        'anotherSettings': 'some value'
    });

    // Get settings. Retrieves latest saved settigns
    PandaPackage.settings(function(err, settings) {
        //you now have the settings object
    });
    */

  return PandaPackage;
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>{% block title %} prettyunit {% endblock %}</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/siimple.min.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}">

    {%  block nav %}

        prettunit.

500 SERVER ERROR

See a system administrator

         Go home.

        Built by Drowned Coast.
        Made using Siimple and chart.js.

    {% endblock %}


text:
<?php
namespace app\components\umengsdk\notification\ios;

use app\components\umengsdk\notification\IOSNotification;

class IOSUnicast extends IOSNotification {
	function __construct() {
		parent::__construct();
		$this->data["type"] = "unicast";
		$this->data["device_tokens"] = NULL;
	}

}


text:
<?php

namespace Magento\Setup\Test\Unit\Module\Dependency\Report\Circular\Data;

use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;

class ConfigTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Setup\Module\Dependency\Report\Circular\Data\Module|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $moduleFirst;

    /**
     * @var \Magento\Setup\Module\Dependency\Report\Circular\Data\Module|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $moduleSecond;

    /**
     * @var \Magento\Setup\Module\Dependency\Report\Circular\Data\Config
     */
    protected $config;

    public function setUp()
    {
        $this->moduleFirst = $this->getMock(
            'Magento\Setup\Module\Dependency\Report\Circular\Data\Module',
            [],
            [],
            '',
            false
        );
        $this->moduleSecond = $this->getMock(
            'Magento\Setup\Module\Dependency\Report\Circular\Data\Module',
            [],
            [],
            '',
            false
        );

        $objectManagerHelper = new ObjectManager($this);
        $this->config = $objectManagerHelper->getObject(
            'Magento\Setup\Module\Dependency\Report\Circular\Data\Config',
            ['modules' => [$this->moduleFirst, $this->moduleSecond]]
        );
    }

    public function testGetDependenciesCount()
    {
        $this->moduleFirst->expects($this->once())->method('getChainsCount')->will($this->returnValue(0));
        $this->moduleSecond->expects($this->once())->method('getChainsCount')->will($this->returnValue(2));

        $this->assertEquals(2, $this->config->getDependenciesCount());
    }
}


text:
<?php

namespace Bolt\Extension\BoltAuth\Auth\Storage\Repository;

use Bolt\Extension\BoltAuth\Auth\Storage\Entity;

class Oauth extends AbstractAuthRepository
{
    const ALIAS = 'o';

    /**
     * Fetches an OAuth entries by GUID.
     *
     * @param string $guid
     *
     * @return Entity\Oauth|false
     */
    public function getOauthByGuid($guid)
    {
        $query = $this->getOauthByGuidQuery($guid);

        return $this->findOneWith($query);
    }

    public function getOauthByGuidQuery($guid)
    {
        $qb = $this->createQueryBuilder();
        $qb->select('*')
            ->where('guid = :guid')
            ->setParameter('guid', $guid)
        ;

        return $qb;
    }

    /**
     * Fetches an OAuth entries by Resource Owner ID.
     *
     * @param string $resourceOwnerId
     *
     * @return Entity\Oauth|false
     */
    public function getOauthByResourceOwnerId($resourceOwnerId)
    {
        $query = $this->getOauthByResourceOwnerIdQuery($resourceOwnerId);

        return $this->findOneWith($query);
    }

    public function getOauthByResourceOwnerIdQuery($resourceOwnerId)
    {
        $qb = $this->createQueryBuilder();
        $qb->select('*')
            ->andWhere('resource_owner_id = :resource_owner_id')
            ->setParameter('resource_owner_id', $resourceOwnerId)
        ;

        return $qb;
    }
}


text:
"""
Ansible module to manage symbolic link alternatives.
(c) 2014, Gabe Mulley <gabe.mulley@gmail.com>
(c) 2015, David Wittman <dwittman@gmail.com>

This file is part of Ansible

Ansible is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Ansible is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
"""

DOCUMENTATION = '''
---
module: alternatives
short_description: Manages alternative programs for common commands
description:
    - Manages symbolic links using the 'update-alternatives' tool
    - Useful when multiple programs are installed but provide similar functionality (e.g. different editors).
version_added: "1.6"
author:
    - "David Wittman (@DavidWittman)"
    - "Gabe Mulley (@mulby)"
options:
  name:
    description:
      - The generic name of the link.
    required: true
  path:
    description:
      - The path to the real executable that the link should point to.
      - Can be set to auto to set the default link
    required: true
  link:
    description:
      - The path to the symbolic link that should point to the real executable.
      - This option is required on RHEL-based distributions
    required: false
requirements: [ update-alternatives ]
'''

EXAMPLES = '''
- name: correct java version selected
  alternatives: name=java path=/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java

- name: alternatives link created
  alternatives: name=hadoop-conf link=/etc/hadoop/conf path=/etc/hadoop/conf.ansible
'''

DEFAULT_LINK_PRIORITY = 50

import re

def main():

    module = AnsibleModule(
        argument_spec = dict(
            name = dict(required=True),
            path = dict(required=True, type='path'),
            link = dict(required=False, type='path'),
        ),
        supports_check_mode=True,
    )

    params = module.params
    name = params['name']
    path = params['path']
    link = params['link']

    UPDATE_ALTERNATIVES = module.get_bin_path('update-alternatives',True)

    current_path = None
    all_alternatives = []

    # Run `update-alternatives --display <name>` to find existing alternatives
    (rc, display_output, _) = module.run_command(
        ['env', 'LC_ALL=C', UPDATE_ALTERNATIVES, '--display', name]
    )

    if rc == 0:
        # Alternatives already exist for this link group
        # Parse the output to determine the current path of the symlink and
        # available alternatives
        current_path_regex = re.compile(r'^\s*link currently points to (.*)$',
                                        re.MULTILINE)
        alternative_regex = re.compile(r'^(\/.*)\s-\spriority', re.MULTILINE)
        auto_regex = re.compile(r'^.*\s-\sstatus is (manual|auto)\.$', re.MULTILINE)

        current_path = current_path_regex.search(display_output).group(1)
        all_alternatives = alternative_regex.findall(display_output)
        is_auto = auto_regex.search(display_output).group(1) == 'auto'

        if not link:
            # Read the current symlink target from `update-alternatives --query`
            # in case we need to install the new alternative before setting it.
            #
            # This is only compatible on Debian-based systems, as the other
            # alternatives don't have --query available
            rc, query_output, _ = module.run_command(
                ['env', 'LC_ALL=C', UPDATE_ALTERNATIVES, '--query', name]
            )
            if rc == 0:
                for line in query_output.splitlines():
                    if line.startswith('Link:'):
                        link = line.split()[1]
                        break

    if path == 'auto' and not is_auto:
        if module.check_mode:
            module.exit_json(changed=True, is_auto=is_auto)
        else:
            try:
                module.run_command(
                    [UPDATE_ALTERNATIVES, '--auto', name],
                    check_rc=True
                )
                module.exit_json(changed=True)
            except subprocess.CalledProcessError as cpe:
                module.fail_json(msg=str(dir(cpe)))

    elif path != 'auto' and current_path != path:
        if module.check_mode:
            module.exit_json(changed=True, current_path=current_path)
        try:
            # install the requested path if necessary
            if path not in all_alternatives:
                if not link:
                    module.fail_json(msg="Needed to install the alternative, but unable to do so as we are missing the link")

                module.run_command(
                    [UPDATE_ALTERNATIVES, '--install', link, name, path, str(DEFAULT_LINK_PRIORITY)],
                    check_rc=True
                )

            # select the requested path
            module.run_command(
                [UPDATE_ALTERNATIVES, '--set', name, path],
                check_rc=True
            )

            module.exit_json(changed=True)
        except subprocess.CalledProcessError as cpe:
            module.fail_json(msg=str(dir(cpe)))
    else:
        module.exit_json(changed=False)

# import module snippets
from ansible.module_utils.basic import *
main()


text:
module Ufo
  class LogGroup
    include AwsService

    def initialize(task_definition, options)
      @task_definition, @options = task_definition, options
    end

    def create
      puts "Ensuring log group for #{@task_definition.color(:green)} task definition exists"
      return if @options[:noop]
      return if @options[:rollback] # dont need to create log group because previously deployed

      Ufo.check_task_definition!(@task_definition)
      task_def = JSON.load(IO.read(task_def_path))
      task_def["containerDefinitions"].each do |container_def|
        begin
          log_group_name = container_def["logConfiguration"]["options"]["awslogs-group"]
          puts "Log group name: #{log_group_name}"
        rescue NoMethodError
          # silence when the logConfiguration is not specified
        end

        create_log_group(log_group_name) if log_group_name
      end
    end

    def create_log_group(log_group_name)
      resp = cloudwatchlogs.describe_log_groups(log_group_name_prefix: log_group_name)
      exists = resp.log_groups.find { |lg| lg.log_group_name == log_group_name }
      cloudwatchlogs.create_log_group(log_group_name: log_group_name) unless exists
    end

    def task_def_path
      "#{Ufo.root}/.ufo/output/#{@task_definition}.json"
    end
  end
end


text:
/**
 * Re-exports users controller methods.
 */
const getCurrentUser = require('./getCurrentUser');
const loginUser = require('./loginUser');
const logoutUser = require('./logoutUser');

module.exports = {
  getCurrentUser,
  loginUser,
  logoutUser
};


text:
import LoggedInUser from './LoggedInUser';
import config from '../config';
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');

class CognitoAuth {
  constructor() {
    const poolData = {
      UserPoolId: config.cognito.userPoolId,
      ClientId: config.cognito.userPoolClientId
    };
    this.userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
    if (typeof window.AWSCognito !== 'undefined') {
      window.AWSCognito.config.region = config.cognito.region;
    }
    this.registerLoggedInUserChangeCallbacks = [];
  }

  signup(username, email, location, password, signupCallback) {
    const attributes = [
      generateDataAttribute('email', email),
      generateDataAttribute('custom:location', location)
    ];

    this.userPool.signUp(username, password, attributes, null, signupCallback);
  }

  verify(username, code, verifyCallback) {
    const cognitoUser = getCognitoUser(this.userPool, username);
    cognitoUser.confirmRegistration(code, true, verifyCallback);
  }

  signin(username, password, successCallback, failureCallback) {
    const cognitoUser = getCognitoUser(this.userPool, username);
    const authenticationData = {
      Username: username,
      Password: password
    };
    const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
    cognitoUser.authenticateUser(authenticationDetails, {
      onSuccess: this.localAuthenticationSuccessCallback.bind(this, successCallback, failureCallback),
      onFailure: failureCallback
    });
  }

  logout() {
    if (LoggedInUser.isLoggedIn) {
      const cognitoUser = getCognitoUser(this.userPool, LoggedInUser.username);
      cognitoUser.signOut();
      LoggedInUser.isLoggedIn = false;
      this.registerLoggedInUserChangeCallbacks.map(c => c());
    }
  }

  registerLoggedInUserChangeCallback(loggedInUserChangeCallback) {
    this.registerLoggedInUserChangeCallbacks.push(loggedInUserChangeCallback);
  }

  localAuthenticationSuccessCallback(successCallback, errorCallback, result) {
    const accessToken = result.getIdToken().getJwtToken();
    const payload = result.getIdToken().decodePayload();
    LoggedInUser.isLoggedIn = true;
    LoggedInUser.token = accessToken;
    LoggedInUser.username = payload['cognito:username'];
    LoggedInUser.email = payload['email'];
    LoggedInUser.location = payload['custom:location'];
    LoggedInUser.sub = payload['sub'];
    console.log(`Successfully logged in user ${LoggedInUser.username}`);
    console.log(`Token is ${accessToken}`);
    this.registerLoggedInUserChangeCallbacks.map(c => c());

    successCallback();
  }

};

const getCognitoUser = (pool, username) => {
  return new AmazonCognitoIdentity.CognitoUser({
    Username: username,
    Pool: pool
  });
};

const generateDataAttribute = (attributeName, attributeValue) => {
  return new AmazonCognitoIdentity.CognitoUserAttribute({
    Name: attributeName,
    Value: attributeValue
  });
};

export default CognitoAuth = new CognitoAuth();


text:
package ludum.mighty.ld36.screen;

import ludum.mighty.ld36.assets.SoundAssets;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import ludum.mighty.ld36.settings.DefaultValues;

public class HistoryScreen extends DefaultScreen implements Screen {

	SpriteBatch batch;
	Texture img;
	Sprite spr;
	OrthographicCamera cam;
	StretchViewport sv;

	int waitFramesForHandle = DefaultValues.WAIT_TIME;

	public HistoryScreen(Game game, SoundAssets sa) {
		super(game, sa);

		this.cam = new OrthographicCamera();
		this.sv = new StretchViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), this.cam);
		this.cam.position.set(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2, 0);

		this.batch = new SpriteBatch();
		this.img = new Texture("history.png");
		this.spr = new Sprite(this.img);
		this.spr.setPosition(0, 0);
		this.spr.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
	}

	public void render(float delta) {
		Gdx.gl.glClearColor(0, 0, 0, 1);
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

		this.waitFramesForHandle -= 1;
		if (this.waitFramesForHandle <= 0)
			handleInput();

		batch.setProjectionMatrix(this.cam.combined);

		this.batch.begin();
		this.spr.draw(batch);
		this.batch.end();
	}

	@Override
	public void resize(int width, int height) {
		this.sv.update(width, height);
	}

	private void handleInput() {
		if (Gdx.input.isKeyPressed(Input.Keys.ANY_KEY)) {
			this.mightyGame.setScreen(new InstructionsScreen(this.mightyGame,
					this.soundAssets));
		}
	}

}


text:
@interface MARequestStringValueController : NSWindowController

@property (strong) NSString *titleText;
@property (strong) NSString *descriptionText;
@property (strong) NSString *labelText;
@property (strong) NSString *stringValue;
@property (strong) NSString *windowTitleText;
@property (strong) NSString *okButtonTitle;
@property (strong) NSString *cancelButtonTitle;

- (void)setDefaultValues;
- (IBAction)okAction:(id)sender;
- (IBAction)cancelAction:(id)sender;

@end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

/**
 * Package containing the data models for ElevationClient. The Azure Maps Elevation API provides an HTTP interface to
 * query elevation data on the surface of the Earth. Elevation data can be retrieved at specific locations by sending
 * lat/lon coordinates, by defining an ordered set of vertices that form a Polyline and a number of sample points along
 * the length of a Polyline, or by defining a bounding box that consists of equally spaced vertices as rows and columns.
 * The vertical datum is EPSG:3855. This datum uses the EGM2008 geoid model applied to the WGS84 ellipsoid as its zero
 * height reference surface. The vertical unit is measured in meters, the spatial resolution of the elevation data is
 * 0.8 arc-second for global coverage (~24 meters).
 */
package com.azure.maps.elevation.implementation.models;


text:
package org.testng.internal.protocols;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.testng.collections.Lists;
import org.testng.internal.Utils;

class JarProcessor extends Processor {
  @Override
  public List<String> process(Input input, URL url) {
    try {
      return processJar(
          url,
          input.getIncluded(),
          input.getExcluded(),
          input.getPackageWithoutWildCards(),
          input.isRecursive(),
          input.getPackageDirName(),
          input.getPackageName());
    } catch (IOException e) {
      throw new UnhandledIOException(e);
    }
  }

  private static List<String> processJar(
      URL url,
      List<String> included,
      List<String> excluded,
      String packageOnly,
      boolean recursive,
      String packageDirName,
      String packageName)
      throws IOException {
    List<String> vResult = Lists.newArrayList();
    JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry = entries.nextElement();
      String name = entry.getName();
      if (name.startsWith("module-info") || name.startsWith("META-INF")) {
        continue;
      }
      if (name.charAt(0) == '/') {
        name = name.substring(1);
      }
      if (name.startsWith(packageDirName)) {
        int idx = name.lastIndexOf('/');
        if (idx != -1) {
          packageName = name.substring(0, idx).replace('/', '.');
        }

        if (recursive || packageName.equals(packageOnly)) {
          // it's not inside a deeper dir
          Utils.log(CLS_NAME, 4, "Package name is " + packageName);
          if (name.endsWith(".class") && !entry.isDirectory()) {
            String className = name.substring(packageName.length() + 1, name.length() - 6);
            Utils.log(
                CLS_NAME,
                4,
                "Found class " + className + ", seeing it if it's included or excluded");
            List<String> processedList =
                includeOrExcludeClass(packageName, className, included, excluded);
            vResult.addAll(processedList);
          }
        }
      }
    }
    return vResult;
  }
}


text:
require 'pony'

class SendEmailOperation

    def initialize(value)
        subject = value["data"]["subject"] || "SendEmailOperation"
        body = value["data"]["body"] || "Empty body"
        emails = value["data"]["emails"]
        # [ "a@a.com", "b@b.com"]
        attachments = value["data"]["attachments"] || {}
        # {"foo.zip" => File.read("path/to/foo.zip"), "hello.txt" => "hello!"}

        emails.each do |email|
            log "[#{Time.now}] [SendEmail] Begin Sending email to #{email}..."

            # Detailed Pony options
            # https://github.com/benprew/pony
            Pony.mail({
              :to => email,
              :from => $smtp_from,
              :subject => subject,
              :body => body,
              :via => :smtp,
              :via_options => $smtp_via_options,
              :attachments => attachments
            })

            log "[#{Time.now}] [SendEmail] Ended sending email to #{email}..."
        end
    end

end


text:
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/content', 'scroll'); ?>
<?php endwhile; ?>


text:
describe('ratgraph histogram', function () {
	var histogram, fixture, chainedMethods,
		dimensionStub, chart, axis;

	beforeEach(function() {
		fixture = d3.select('body').append('div').classed('test', true);

		dimensionStub = {
			bottom: function (_) { return [{createdDate:''}]; },
			top: function(_) { return [{createdDate:''}]; }
		};
		chainedMethods = ['margins', 'dimension', 'group', 'x', 'round', 'xUnits', 'elasticY', 'yAxisLabel', 'renderHorizontalGridLines', 'height', 'width'];
		chart = jasmine.createSpyObj('chart', chainedMethods.concat(['xAxis','yAxis']));
		chainedMethods.forEach(function (methodName) {
			chart[methodName].and.returnValue(chart);
		});
		axis = jasmine.createSpyObj('axis', ['tickFormat','ticks']);
		chart['xAxis'].and.returnValue(axis);
		chart['yAxis'].and.returnValue(axis);

		spyOn(dc, "barChart").and.returnValue(chart);

		histogram = ratgraph.histogram('.test', dimensionStub);
	});

	afterEach(function() {
		fixture.remove();
	});

	it('should be based on a dc.js bar chart', function () {
		expect(dc.barChart).toHaveBeenCalled();
		expect(dc).toBeDefined();
	});

	it('should call all chained methods', function () {
		chainedMethods.forEach(function (methodName) {
			expect(chart[methodName]).toHaveBeenCalled();
		});
	});

	it('should set up the axes', function () {
		expect(chart.xAxis).toHaveBeenCalled();
		expect(chart.yAxis).toHaveBeenCalled();
		expect(axis.tickFormat).toHaveBeenCalled();
		expect(axis.ticks).toHaveBeenCalled();
		expect(axis.ticks.calls.count()).toBe(2);
	});
});


text:
#ifndef _CARTO_TEXTURE_H_
#define _CARTO_TEXTURE_H_

#include "renderers/utils/GLResource.h"

#include <memory>

#include <cglib/vec.h>

namespace carto {
    class Bitmap;

    class Texture : public GLResource {
    public:
        virtual ~Texture();

        bool isMipmaps() const;

        bool isRepeat() const;

        std::size_t getSize() const;

        const cglib::vec2<float>& getTexCoordScale() const;

        GLuint getTexId() const;

    protected:
        friend GLResourceManager;

        Texture(const std::weak_ptr<GLResourceManager>& manager, const std::shared_ptr<Bitmap>& bitmap, bool genMipmaps, bool repeat);

        virtual void create();
        virtual void destroy();

    private:
        static const int MAX_ANISOTROPY;

        static const double MIPMAP_SIZE_MULTIPLIER;

        static GLuint LoadFromBitmap(const Bitmap& bitmap, bool genMipmaps, bool repeat);

        std::shared_ptr<Bitmap> _bitmap;
        bool _mipmaps;
        bool _repeat;
        std::size_t _sizeInBytes;
        cglib::vec2<float> _texCoordScale;

        GLuint _texId;
    };

}

#endif


text:
flux4j
======

An implementation of the flux framework in Java for use in GWT

### Publish
```
gradlew :runtime:bintrayUpload
gradlew :annotation-processors:bintrayUpload
```


text:
<?php

namespace BlogBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ArticleType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('titre')->add('contenu')->add('themes');
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'BlogBundle\Entity\Article',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'csrf_token_id'   => 'task_item',
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'blogbundle_article';
    }

}


text:
<?php
namespace LoopAnime\AppBundle\Queue\Exception;

class WorkerNotDefinedException extends \Exception
{

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arch.CMessaging.Client.Core.Collections
{
    public class ChunkedProducerConsumer<TItem> : AbstractProducerConsumer<TItem, ChunkedNotifyQueue<TItem>>
    {
        private const int ONE_ITEM_CHUNK = 1;
        private const int NOTIFY_AFTER_ONE_SECOND = 1;
        private const int ONLY_ONE_CONSUMER = 1;
        private int maxCountOneChunk;
        private ChunkedNotifyQueue<TItem> blockingQueue;
        public ChunkedProducerConsumer(int capacity)
            : this(capacity, ONLY_ONE_CONSUMER, NOTIFY_AFTER_ONE_SECOND, ONE_ITEM_CHUNK, ONE_ITEM_CHUNK) { }

        public ChunkedProducerConsumer(
            int capacity,
            int maxConsumerCount,
            int timeoutToNotify,
            int maxCountOneChunk,
            int reachCountToNotify)
            :base(maxConsumerCount)
        {
            this.maxCountOneChunk = maxCountOneChunk;
            this.blockingQueue = new ChunkedNotifyQueue<TItem>(capacity, reachCountToNotify, timeoutToNotify);
        }

        protected override ChunkedNotifyQueue<TItem> BlockingQueue
        {
            get { return blockingQueue; }
        }

        protected override IConsumingItem TakeConsumingItem()
        {
            return new ChunkedConsumingItem<TItem>(blockingQueue.TakeBatch(maxCountOneChunk));
        }
    }
}


text:
/* Generic definitions */

/* Assertions (useful to generate conditional code) */
/* Current type and class (and size, if applicable) */
/* Value methods */
/* Interfaces (keys) */
/* Interfaces (values) */
/* Abstract implementations (keys) */
/* Abstract implementations (values) */
/* Static containers (keys) */
/* Static containers (values) */
/* Implementations */
/* Synchronized wrappers */
/* Unmodifiable wrappers */
/* Other wrappers */
/* Methods (keys) */
/* Methods (values) */
/* Methods (keys/values) */
/* Methods that have special names depending on keys (but the special names depend on values) */
/* Equality */
/* Object/Reference-only definitions (keys) */
/* Primitive-type-only definitions (keys) */
/* Object/Reference-only definitions (values) */
/*
 * Copyright (C) 2010-2013 Sebastiano Vigna
 *
 * 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.
 */
package it.unimi.dsi.fastutil.doubles;
import java.util.List;
import it.unimi.dsi.fastutil.BigList;
/** A type-specific {@link BigList}; provides some additional methods that use polymorphism to avoid (un)boxing.
 *
 *
Additionally, this interface strengthens {@link #iterator()}, {@link #listIterator()},
 * {@link #listIterator(long)} and {@link #subList(long,long)}.
 *
 *
Besides polymorphic methods, this interfaces specifies methods to copy into an array or remove contiguous
 * sublists. Although the abstract implementation of this interface provides simple, one-by-one implementations
 * of these methods, it is expected that concrete implementation override them with optimized versions.
 *
 * @see List
 */
public interface DoubleBigList extends BigList<Double>, DoubleCollection , Comparable<BigList<? extends Double>> {
 /** Returns a type-specific big-list iterator on this type-specific big list.
	 *
	 * @see List#iterator()
	 */
 DoubleBigListIterator iterator();
 /** Returns a type-specific big-list iterator on this type-specific big list.
	 *
	 * @see List#listIterator()
	 */
 DoubleBigListIterator listIterator();
 /** Returns a type-specific list iterator on this type-specific big list starting at a given index.
	 *
	 * @see BigList#listIterator(long)
	 */
 DoubleBigListIterator listIterator( long index );

 /** Returns a type-specific view of the portion of this type-specific big list from the index from, inclusive, to the index to, exclusive.
	 *
	 *
Note that this specification strengthens the one given in {@link BigList#subList(long,long)}.
	 *
	 * @see BigList#subList(long,long)
	 */
 DoubleBigList subList( long from, long to );

 /** Copies (hopefully quickly) elements of this type-specific big list into the given big array.
	 *
	 * @param from the start index (inclusive).
	 * @param a the destination big array.
	 * @param offset the offset into the destination big array where to store the first element copied.
	 * @param length the number of elements to be copied.
	 */
 void getElements( long from, double a[][], long offset, long length );

 /** Removes (hopefully quickly) elements of this type-specific big list.
	 *
	 * @param from the start index (inclusive).
	 * @param to the end index (exclusive).
	 */
 void removeElements( long from, long to );

 /** Add (hopefully quickly) elements to this type-specific big list.
	 *
	 * @param index the index at which to add elements.
	 * @param a the big array containing the elements.
	 */
 void addElements( long index, double a[][] );

 /** Add (hopefully quickly) elements to this type-specific big list.
	 *
	 * @param index the index at which to add elements.
	 * @param a the big array containing the elements.
	 * @param offset the offset of the first element to add.
	 * @param length the number of elements to add.
	 */
 void addElements( long index, double a[][], long offset, long length );

 /**
	 * @see List#add(int,Object)
	 */
 void add( long index, double key );

 /**
	 * @see List#addAll(int,java.util.Collection)
	 */
 boolean addAll( long index, DoubleCollection c );

 /**
	 * @see List#addAll(int,java.util.Collection)
	 */
 boolean addAll( long index, DoubleBigList c );

 /**
	 * @see List#addAll(int,java.util.Collection)
	 */
 boolean addAll( DoubleBigList c );

 /**
	 * @see BigList#get(long)
	 */
 double getDouble( long index );

 /**
	 * @see BigList#indexOf(Object)
	 */
 long indexOf( double k );

 /**
	 * @see BigList#lastIndexOf(Object)
	 */
 long lastIndexOf( double k );

 /**
	 * @see BigList#remove(long)
	 */
 double removeDouble( long index );

 /**
	 * @see BigList#set(long,Object)
	 */
 double set( long index, double k );

}


text:
struct __locale_map {
    const void *map;
    size_t map_size;
    char name[LOCALE_NAME_MAX+1];
    struct __locale_map *next;
};

int __setlocalecat(locale_t, int, const char *);
const char *__mo_lookup(const void *, size_t, const char *);
const char *__lctrans(const char *, const struct __locale_map *);
const char *__lctrans_cur(const char *);

#define LCTRANS(msg, lc, loc) __lctrans(msg, (loc)->cat[(lc)-2])
#define LCTRANS_CUR(msg) __lctrans_cur(msg)

// @@@
//#define CURRENT_LOCALE \
//    (libc.uselocale_cnt ? __pthread_self()->locale : &libc.global_locale)
#ifdef _MSC_VER
#define CURRENT_LOCALE \
    (&libc.global_locale)
#else
#define CURRENT_LOCALE \
    (libc.uselocale_cnt ? __pthread_self()->locale : &libc.global_locale)
#endif
// @@@

#define CURRENT_UTF8 \
    (libc.bytelocale_cnt_minus_1<0 || __pthread_self()->locale->ctype_utf8)

#undef MB_CUR_MAX
#define MB_CUR_MAX (CURRENT_UTF8 ? 4 : 1)


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.VR.WSA.Input;
using UnityEngine.VR.WSA.Persistence;
using UnityEngine.VR.WSA;
using HoloToolkit.Unity.InputModule;
using UnityEngine.Events;
using System;
using HoloToolkit.Unity;

public class PostEffect : MonoBehaviour
{
    Camera AttachedCamera;
    public Shader Post_Outline;
    public Shader DrawSimple;
    Camera TempCam;
    Material Post_Mat;
    // public RenderTexture TempRT;

    void Start()
    {
        AttachedCamera = GetComponent<Camera>();
        TempCam = new GameObject().AddComponent<Camera>();
        TempCam.enabled = false;
        Post_Mat = new Material(Post_Outline);
    }

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        //set up a temporary camera
        TempCam.CopyFrom(AttachedCamera);
        TempCam.clearFlags = CameraClearFlags.Color;
        TempCam.backgroundColor = Color.black;

        //cull any layer that isn't the outline
        TempCam.cullingMask = 1 << LayerMask.NameToLayer("Outline");

        //make the temporary rendertexture
        RenderTexture TempRT = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.R8);

        //put it to video memory
        TempRT.Create();

        //set the camera's target texture when rendering
        TempCam.targetTexture = TempRT;

        //render all objects this camera can render, but with our custom shader.
        TempCam.RenderWithShader(DrawSimple, "");

        //copy the temporary RT to the final image
        Graphics.Blit(TempRT, destination, Post_Mat);

        //release the temporary RT
        TempRT.Release();
    }

}


text:
#ifndef BACKENDS_BMV2_COMMON_BACKEND_H_
#define BACKENDS_BMV2_COMMON_BACKEND_H_

#include "controlFlowGraph.h"
#include "expression.h"
#include "frontends/common/model.h"
#include "frontends/p4/coreLibrary.h"
#include "helpers.h"
#include "ir/ir.h"
#include "lib/error.h"
#include "lib/exceptions.h"
#include "lib/gc.h"
#include "lib/json.h"
#include "lib/log.h"
#include "lib/nullstream.h"
#include "JsonObjects.h"
#include "metermap.h"
#include "midend/convertEnums.h"
#include "midend/actionSynthesis.h"
#include "midend/removeLeftSlices.h"
#include "sharedActionSelectorCheck.h"
#include "options.h"

namespace BMV2 {

enum gress_t { INGRESS, EGRESS };
enum block_t { PARSER, PIPELINE, DEPARSER, V1_PARSER, V1_DEPARSER,
               V1_INGRESS, V1_EGRESS, V1_VERIFY, V1_COMPUTE};

class ExpressionConverter;

// Backend is a the base class for SimpleSwitchBackend and PortableSwitchBackend.
class Backend {
 public:
    BMV2Options&                     options;
    P4::ReferenceMap*                refMap;
    P4::TypeMap*                     typeMap;
    P4::ConvertEnums::EnumMapping*   enumMap;
    P4::P4CoreLibrary&               corelib;
    BMV2::JsonObjects*               json;
    ExpressionConverter*             conv;
    const IR::ToplevelBlock*         toplevel;

 public:
    Backend(BMV2Options& options, P4::ReferenceMap* refMap, P4::TypeMap* typeMap,
            P4::ConvertEnums::EnumMapping* enumMap) :
        options(options),
        refMap(refMap), typeMap(typeMap), enumMap(enumMap),
        corelib(P4::P4CoreLibrary::instance), json(new BMV2::JsonObjects()) {
        refMap->setIsV1(options.isv1());
        }
    void serialize(std::ostream& out) const { json->toplevel->serialize(out); }
    virtual void convert(const IR::ToplevelBlock* block) = 0;
};

/**
This class implements a policy suitable for the SynthesizeActions pass.
The policy is: do not synthesize actions for the controls whose names
are in the specified set.
For example, we expect that the code in the deparser will not use any
tables or actions.
*/
class SkipControls : public P4::ActionSynthesisPolicy {
    // set of controls where actions are not synthesized
    const std::set<cstring> *skip;

 public:
    explicit SkipControls(const std::set<cstring> *skip) : skip(skip) { CHECK_NULL(skip); }
    bool convert(const Visitor::Context *, const IR::P4Control* control) override {
        if (skip->find(control->name) != skip->end())
            return false;
        return true;
    }
};

/**
This class implements a policy suitable for the RemoveComplexExpression pass.
The policy is: only remove complex expression for the controls whose names
are in the specified set.
For example, we expect that the code in ingress and egress will have complex
expression removed.
*/
class ProcessControls : public BMV2::RemoveComplexExpressionsPolicy {
    const std::set<cstring> *process;

 public:
    explicit ProcessControls(const std::set<cstring> *process) : process(process) {
        CHECK_NULL(process);
    }
    bool convert(const IR::P4Control* control) const {
        if (process->find(control->name) != process->end())
            return true;
        return false;
    }
};

/**
This pass adds @name annotations to all fields of the user metadata
structure so that they do not clash with fields of the headers
structure.  This is necessary because both of them become global
objects in the output json.
*/
class RenameUserMetadata : public Transform {
    P4::ReferenceMap* refMap;
    const IR::Type_Struct* userMetaType;
    // Used as a prefix for the fields of the userMetadata structure
    // and also as a name for the userMetadata type clone.
    cstring namePrefix;

 public:
    RenameUserMetadata(P4::ReferenceMap* refMap,
                       const IR::Type_Struct* userMetaType, cstring namePrefix):
        refMap(refMap), userMetaType(userMetaType), namePrefix(namePrefix)
    { setName("RenameUserMetadata"); CHECK_NULL(refMap); }

    const IR::Node* postorder(IR::Type_Struct* type) override {
        // Clone the user metadata type
        if (userMetaType != getOriginal())
            return type;

        auto vec = new IR::IndexedVector<IR::Node>();
        LOG2("Creating clone" << getOriginal());
        auto clone = type->clone();
        clone->name = namePrefix;
        vec->push_back(clone);

        // Rename all fields
        IR::IndexedVector<IR::StructField> fields;
        for (auto f : type->fields) {
            auto anno = f->getAnnotation(IR::Annotation::nameAnnotation);
            cstring suffix = "";
            if (anno != nullptr)
                suffix = anno->getName();
            if (suffix.startsWith(".")) {
                // We can't change the name of this field.
                // Hopefully the user knows what they are doing.
                fields.push_back(f->clone());
                continue;
            }

            if (!suffix.isNullOrEmpty())
                suffix = cstring(".") + suffix;
            else
                suffix = cstring(".") + f->name;
            cstring newName = namePrefix + suffix;
            auto stringLit = new IR::StringLiteral(newName);
            LOG2("Renaming " << f << " to " << newName);
            auto annos = f->annotations->addOrReplace(IR::Annotation::nameAnnotation, stringLit);
            auto field = new IR::StructField(f->srcInfo, f->name, annos, f->type);
            fields.push_back(field);
        }

        auto annotated = new IR::Type_Struct(
            type->srcInfo, type->name, type->annotations, std::move(fields));
        vec->push_back(annotated);
        return vec;
    }

    const IR::Node* preorder(IR::Type_Name* type) override {
        // Find any reference to the user metadata type that is used and replace them
        auto decl = refMap->getDeclaration(type->path);
        if (decl == userMetaType)
            type->path = new IR::Path(type->path->srcInfo, IR::ID(type->path->srcInfo, namePrefix));
        LOG2("Replacing reference with " << type);
        return type;
    }
};

}  // namespace BMV2

#endif /* BACKENDS_BMV2_COMMON_BACKEND_H_ */


text:
/*jslint node: true, unparam: false*/
/*
Copyright © 2013 by Sebastien Dolard (sdolard@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation file (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*/

var
fs = require('fs'),
util = require('util'),
path = require('path'),
trash = require('./trash');

exports.create = (function () {
        /**
        * @class
        * @public
        * @params [{Booleab}] config.debug. Defautl false
        * @event deleted ({ Error | undefined }, )
        * @event erased
        * @event error({Error} err)
        */
        function Trash(config) {
            trash.AbstractTrash.call(this);
            config = config || {};
            this._debug = config.debug;
        }
        util.inherits(Trash, trash.AbstractTrash);

        /*
        * @param file {String} file or directory
        * @
        */
        Trash.prototype.delete = function(file, cb) {
            file = path.resolve(file);
            this.once('deleted', cb);

            fs.stat(file, function(err, stats){
                var e;
                if (err) {
                    return this.emit('deleted', err);
                }

                if (!stats.isFile() && !stats.isDirectory()) {
                    e = new Error('Invalid file: ' + file);
                    e.code = 'EINVALIDFILE';
                    return this.emit('deleted', err);
                }

                this._moveToTrash(file);

            }.bind(this));
        };

        Trash.prototype._moveToTrash = function(file) {
            this._getTrash(file, function(err, trash){

            }.bind(this));
        }

        Trash.prototype._getTrash = function(file, cb, event) {

        }

        return function(config) {
            return new Trash(config);
        };
}());


text:
import os

from mock import Mock, MagicMock, patch, mock_open
import pexpect

from trove.common.exception import GuestError, ProcessExecutionError
from trove.common import utils
from trove.guestagent import volume
from trove.tests.unittests import trove_testtools

def _setUp_fake_spawn(return_val=0):
    fake_spawn = pexpect.spawn('echo')
    fake_spawn.expect = Mock(return_value=return_val)
    pexpect.spawn = Mock(return_value=fake_spawn)
    return fake_spawn

class VolumeDeviceTest(trove_testtools.TestCase):

    def setUp(self):
        super(VolumeDeviceTest, self).setUp()
        self.volumeDevice = volume.VolumeDevice('/dev/vdb')

    def tearDown(self):
        super(VolumeDeviceTest, self).tearDown()

    @patch.object(pexpect, 'spawn', Mock())
    def test_migrate_data(self):
        origin_execute = utils.execute
        utils.execute = Mock()
        origin_os_path_exists = os.path.exists
        os.path.exists = Mock()
        fake_spawn = _setUp_fake_spawn()

        origin_unmount = self.volumeDevice.unmount
        self.volumeDevice.unmount = MagicMock()
        self.volumeDevice.migrate_data('/')
        self.assertEqual(1, fake_spawn.expect.call_count)
        self.assertEqual(1, utils.execute.call_count)
        self.assertEqual(1, self.volumeDevice.unmount.call_count)
        utils.execute = origin_execute
        self.volumeDevice.unmount = origin_unmount
        os.path.exists = origin_os_path_exists

    def test__check_device_exists(self):
        origin_execute = utils.execute
        utils.execute = Mock()
        self.volumeDevice._check_device_exists()
        self.assertEqual(1, utils.execute.call_count)
        utils.execute = origin_execute

    @patch('trove.guestagent.volume.LOG')
    def test_fail__check_device_exists(self, mock_logging):
        with patch.object(utils, 'execute', side_effect=ProcessExecutionError):
            self.assertRaises(GuestError,
                              self.volumeDevice._check_device_exists)

    @patch.object(pexpect, 'spawn', Mock())
    def test__check_format(self):
        fake_spawn = _setUp_fake_spawn()

        self.volumeDevice._check_format()
        self.assertEqual(1, fake_spawn.expect.call_count)

    @patch.object(pexpect, 'spawn', Mock())
    def test__check_format_2(self):
        fake_spawn = _setUp_fake_spawn(return_val=1)

        self.assertEqual(0, fake_spawn.expect.call_count)
        self.assertRaises(IOError, self.volumeDevice._check_format)

    @patch.object(pexpect, 'spawn', Mock())
    def test__format(self):
        fake_spawn = _setUp_fake_spawn()

        self.volumeDevice._format()

        self.assertEqual(1, fake_spawn.expect.call_count)
        self.assertEqual(1, pexpect.spawn.call_count)

    def test_format(self):
        origin_check_device_exists = self.volumeDevice._check_device_exists
        origin_format = self.volumeDevice._format
        origin_check_format = self.volumeDevice._check_format
        self.volumeDevice._check_device_exists = MagicMock()
        self.volumeDevice._check_format = MagicMock()
        self.volumeDevice._format = MagicMock()

        self.volumeDevice.format()
        self.assertEqual(1, self.volumeDevice._check_device_exists.call_count)
        self.assertEqual(1, self.volumeDevice._format.call_count)
        self.assertEqual(1, self.volumeDevice._check_format.call_count)

        self.volumeDevice._check_device_exists = origin_check_device_exists
        self.volumeDevice._format = origin_format
        self.volumeDevice._check_format = origin_check_format

    def test_mount(self):
        origin_ = volume.VolumeMountPoint.mount
        volume.VolumeMountPoint.mount = Mock()
        origin_os_path_exists = os.path.exists
        os.path.exists = Mock()
        origin_write_to_fstab = volume.VolumeMountPoint.write_to_fstab
        volume.VolumeMountPoint.write_to_fstab = Mock()

        self.volumeDevice.mount(Mock)
        self.assertEqual(1, volume.VolumeMountPoint.mount.call_count)
        self.assertEqual(1, volume.VolumeMountPoint.write_to_fstab.call_count)
        volume.VolumeMountPoint.mount = origin_
        volume.VolumeMountPoint.write_to_fstab = origin_write_to_fstab
        os.path.exists = origin_os_path_exists

    def test_resize_fs(self):
        origin_check_device_exists = self.volumeDevice._check_device_exists
        origin_execute = utils.execute
        utils.execute = Mock()
        self.volumeDevice._check_device_exists = MagicMock()
        origin_os_path_exists = os.path.exists
        os.path.exists = Mock()

        self.volumeDevice.resize_fs('/mnt/volume')

        self.assertEqual(1, self.volumeDevice._check_device_exists.call_count)
        self.assertEqual(2, utils.execute.call_count)
        self.volumeDevice._check_device_exists = origin_check_device_exists
        os.path.exists = origin_os_path_exists
        utils.execute = origin_execute

    @patch.object(utils, 'execute', side_effect=ProcessExecutionError)
    @patch('trove.guestagent.volume.LOG')
    def test_fail_resize_fs(self, mock_logging, mock_execute):
        with patch.object(self.volumeDevice, '_check_device_exists'):
            self.assertRaises(GuestError,
                              self.volumeDevice.resize_fs, '/mnt/volume')
            self.assertEqual(1,
                             self.volumeDevice._check_device_exists.call_count)

    def test_unmount_positive(self):
        self._test_unmount()

    def test_unmount_negative(self):
        self._test_unmount(False)

    @patch.object(pexpect, 'spawn', Mock())
    def _test_unmount(self, positive=True):
        origin_ = os.path.exists
        os.path.exists = MagicMock(return_value=positive)
        fake_spawn = _setUp_fake_spawn()

        self.volumeDevice.unmount('/mnt/volume')
        COUNT = 1
        if not positive:
            COUNT = 0
        self.assertEqual(COUNT, fake_spawn.expect.call_count)
        os.path.exists = origin_

    @patch.object(utils, 'execute', return_value=('/var/lib/mysql', ''))
    def test_mount_points(self, mock_execute):
        mount_point = self.volumeDevice.mount_points('/dev/vdb')
        self.assertEqual(['/var/lib/mysql'], mount_point)

    @patch.object(utils, 'execute', side_effect=ProcessExecutionError)
    @patch('trove.guestagent.volume.LOG')
    def test_fail_mount_points(self, mock_logging, mock_execute):
        self.assertRaises(GuestError, self.volumeDevice.mount_points,
                          '/mnt/volume')

    def test_set_readahead_size(self):
        origin_check_device_exists = self.volumeDevice._check_device_exists
        self.volumeDevice._check_device_exists = MagicMock()
        mock_execute = MagicMock(return_value=None)
        readahead_size = 2048
        self.volumeDevice.set_readahead_size(readahead_size,
                                             execute_function=mock_execute)
        blockdev = mock_execute.call_args_list[0]

        blockdev.assert_called_with("sudo", "blockdev", "--setra",
                                    readahead_size, "/dev/vdb")
        self.volumeDevice._check_device_exists = origin_check_device_exists

    @patch('trove.guestagent.volume.LOG')
    def test_fail_set_readahead_size(self, mock_logging):
        mock_execute = MagicMock(side_effect=ProcessExecutionError)
        readahead_size = 2048
        with patch.object(self.volumeDevice, '_check_device_exists'):
            self.assertRaises(GuestError, self.volumeDevice.set_readahead_size,
                              readahead_size, execute_function=mock_execute)
            self.volumeDevice._check_device_exists.assert_any_call()

class VolumeMountPointTest(trove_testtools.TestCase):

    def setUp(self):
        super(VolumeMountPointTest, self).setUp()
        self.volumeMountPoint = volume.VolumeMountPoint('/mnt/device',
                                                        '/dev/vdb')

    def tearDown(self):
        super(VolumeMountPointTest, self).tearDown()

    @patch.object(pexpect, 'spawn', Mock())
    def test_mount(self):
        origin_ = os.path.exists
        os.path.exists = MagicMock(return_value=False)
        fake_spawn = _setUp_fake_spawn()

        with patch.object(utils, 'execute_with_timeout',
                          return_value=('0', '')):
            self.volumeMountPoint.mount()

            self.assertEqual(1, os.path.exists.call_count)
            self.assertEqual(1, utils.execute_with_timeout.call_count)
            self.assertEqual(1, fake_spawn.expect.call_count)

        os.path.exists = origin_

    def test_write_to_fstab(self):
        origin_execute = utils.execute
        utils.execute = Mock()
        m = mock_open()
        with patch('%s.open' % volume.__name__, m, create=True):
            self.volumeMountPoint.write_to_fstab()

        self.assertEqual(1, utils.execute.call_count)
        utils.execute = origin_execute


text:
import { Template } from 'meteor/templating';
import { Semesters } from '../../../api/databet_collections/Semesters';
import { Curricula } from '../../../api/databet_collections/Curricula';
import { Meteor } from 'meteor/meteor';
import { _ } from 'meteor/underscore';

Template.AddSemester.onRendered(
  function() {
  }
);

Template.AddSemester.onCreated( function() {

  this.missing_year = new ReactiveVar();
  this.missing_session = new ReactiveVar();
  this.missing_curriculum = new ReactiveVar();
  this.already_exists = new ReactiveVar();

  Template.instance().missing_year.set(false);
  Template.instance().missing_session.set(false);
  Template.instance().missing_curriculum.set(false);
  Template.instance().already_exists.set(false);

});

Template.AddSemester.events({

  'click .cancel': function(e) {
    e.preventDefault();
    Template.currentData().set_to_false_when_done.set(false);
    return false;
  },

  'change #year': function(e) {
    Template.instance().missing_year.set(false);
    Template.instance().already_exists.set(false);
  },

  'change #session': function(e) {
    Template.instance().missing_session.set(false);
    Template.instance().already_exists.set(false);
  },

  'change #curriculum': function(e) {
    Template.instance().missing_curriculum.set(false);
    Template.instance().already_exists.set(false);
  },

  'click .submit': function(e) {
    e.preventDefault();

    var year = $('#year').val();
    var session = $('#session').val();
    var curriculum = $('#curriculum').val();

    //console.log("YEAR=", year);
    //console.log("SESSION=", session);
    //console.log("CURRICULM=", curriculum);

    if (!year) {
      Template.instance().missing_year.set(true);
    }
    if (!session) {
      Template.instance().missing_session.set(true);
    }
    if (!curriculum) {
      Template.instance().missing_curriculum.set(true);
    }

    if (!year || !session || !curriculum) {
      return false;
    }

    if (Semesters.findOne({"year": Number(year), "session": session})) {
      Template.instance().already_exists.set(true);
      return false;
    }

    var order = 10 * Number(year);
    if (session == "Spring") {
      order += 1;
    } else if (session == "Summer") {
      order += 2;
    } else {
      order += 3;
    }

    var semester = {
      "year": Number(year),
      "session": session,
      "curriculum": curriculum,
      "locked": false,
      "order": order
    };

    Semesters.insert_document(semester);

    Template.currentData().set_to_false_when_done.set(false);

    return false;
  }

});

Template.AddSemester.helpers({

  missing_year: function() {
    return Template.instance().missing_year.get();
  },

  missing_session: function() {
    return Template.instance().missing_session.get();
  },

  missing_curriculum: function() {
    return Template.instance().missing_curriculum.get();
  },

  already_exists: function() {
    return Template.instance().already_exists.get();
  },

  year_range: function() {
    return _.range(2016, 2040);
  },

  curricula_not_empty: function() {
    return (Curricula.find({}).count() > 0);
  },

  curricula: function() {
    return Curricula.find({}).fetch();
  }

});


text:
/*
 * 文件名称:          CustomUserDetails.java
 * 版权所有@ 2014-2016 无锡爱微信息科技有限公司,保留所有权利
 * 编译器:           JDK1.8
 * 时间:             下午9:11:22
 */
package com.wxiwei.manage.service.security;

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

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.wxiwei.manage.db.model.User;

/**
 * TODO: 文件注释
 *

 *

 * Version:        V2.0
 *

 * 作者:           liangjinjing
 *

 * 日期:           2015年11月2日
 *

 * 负责人:         liangjinjing
 *

 *

 */
public class ERUserDetails implements UserDetails
{
    /**
     *
     */
    private static final long serialVersionUID = 5107967774286382074L;

    private User user;

    List<SimpleGrantedAuthority> authoritys = new ArrayList<SimpleGrantedAuthority>();

    public ERUserDetails(User user)
    {
        this.user = user;
        authoritys.add(createAuthority(user));
    }

    @ Override
    public Collection< ? extends GrantedAuthority> getAuthorities()
    {
        return authoritys;
    }

    @ Override
    public String getPassword()
    {
        return user.getPassword();
    }

    @ Override
    public String getUsername()
    {

        return user.getName();
    }

    public String getRealName()
    {
        return user.getName();
    }

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

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

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

    @ Override
    public boolean isEnabled()
    {
        return true;//user.getStatus() == DigitalDictionary.instance().getUSER_STATUS_VALID_VALUE();
    }

    public User getUser()
    {
        return user;
    }

    public void setUser(User user)
    {
        this.user = user;
    }

    /**
     *
     * @param newUser
     */
    public void update(User newUser)
    {
        this.user.setId(newUser.getId());
        this.user.setRole(newUser.getRole());
        this.user.setStatus(newUser.getStatus());
        this.user.setName(newUser.getName());
        this.user.setPassword(newUser.getPassword());
        this.user.setCreateTime(newUser.getCreateTime());
        this.user.setLogoutTime(newUser.getLogoutTime());
        this.authoritys.clear();
        authoritys.add(createAuthority(user));
    }

    private SimpleGrantedAuthority createAuthority(User user)
    {
        return new SimpleGrantedAuthority("1");
    }
}


text:
"""Tests for the file system implementation using the CPIOArchiveFile."""

import unittest

from dfvfs.path import cpio_path_spec
from dfvfs.path import os_path_spec
from dfvfs.resolver import context
from dfvfs.vfs import cpio_file_system

from tests import test_lib as shared_test_lib

@shared_test_lib.skipUnlessHasTestFile([u'syslog.bin.cpio'])
class CPIOFileSystemTest(shared_test_lib.BaseTestCase):
  """The unit test for the CPIO file system object."""

  def setUp(self):
    """Sets up the needed objects used throughout the test."""
    self._resolver_context = context.Context()
    test_file = self._GetTestFilePath([u'syslog.bin.cpio'])
    self._os_path_spec = os_path_spec.OSPathSpec(location=test_file)
    self._cpio_path_spec = cpio_path_spec.CPIOPathSpec(
        location=u'/syslog', parent=self._os_path_spec)

  def testOpenAndClose(self):
    """Test the open and close functionality."""
    file_system = cpio_file_system.CPIOFileSystem(self._resolver_context)
    self.assertIsNotNone(file_system)

    file_system.Open(self._cpio_path_spec)

    file_system.Close()

  def testFileEntryExistsByPathSpec(self):
    """Test the file entry exists by path specification functionality."""
    file_system = cpio_file_system.CPIOFileSystem(self._resolver_context)
    self.assertIsNotNone(file_system)

    file_system.Open(self._cpio_path_spec)

    path_spec = cpio_path_spec.CPIOPathSpec(
        location=u'/syslog', parent=self._os_path_spec)
    self.assertTrue(file_system.FileEntryExistsByPathSpec(path_spec))

    path_spec = cpio_path_spec.CPIOPathSpec(
        location=u'/bogus', parent=self._os_path_spec)
    self.assertFalse(file_system.FileEntryExistsByPathSpec(path_spec))

    file_system.Close()

  def testGetFileEntryByPathSpec(self):
    """Tests the GetFileEntryByPathSpec function."""
    file_system = cpio_file_system.CPIOFileSystem(self._resolver_context)
    self.assertIsNotNone(file_system)

    file_system.Open(self._cpio_path_spec)

    path_spec = cpio_path_spec.CPIOPathSpec(
        location=u'/syslog', parent=self._os_path_spec)
    file_entry = file_system.GetFileEntryByPathSpec(path_spec)

    self.assertIsNotNone(file_entry)
    self.assertEqual(file_entry.name, u'syslog')

    path_spec = cpio_path_spec.CPIOPathSpec(
        location=u'/bogus', parent=self._os_path_spec)
    file_entry = file_system.GetFileEntryByPathSpec(path_spec)

    self.assertIsNone(file_entry)

    file_system.Close()

  def testGetRootFileEntry(self):
    """Test the get root file entry functionality."""
    file_system = cpio_file_system.CPIOFileSystem(self._resolver_context)
    self.assertIsNotNone(file_system)

    file_system.Open(self._cpio_path_spec)

    file_entry = file_system.GetRootFileEntry()

    self.assertIsNotNone(file_entry)
    self.assertEqual(file_entry.name, u'')

    file_system.Close()

if __name__ == '__main__':
  unittest.main()


text:
title: 'Thing Explainer: Complicated Stuff in Simple Words'
written_by:
isbn: '9780544668256'
binding: Hardcover
link_to_buy_page:
image_path: 'https://images.booksense.com/images/256/668/9780544668256.jpg'
---


text:
package org.gradle.api.internal.tasks;

import org.gradle.api.Action;
import org.gradle.api.Task;
import org.gradle.api.internal.PolymorphicDomainObjectContainerInternal;
import org.gradle.api.internal.TaskInternal;
import org.gradle.api.tasks.TaskContainer;
import org.gradle.internal.metaobject.DynamicObject;
import org.gradle.model.internal.core.ModelPath;
import org.gradle.model.internal.type.ModelType;

public interface TaskContainerInternal extends TaskContainer, TaskResolver, PolymorphicDomainObjectContainerInternal<Task> {

    // The path to the project's task container in the model registry
    ModelPath MODEL_PATH = ModelPath.path("tasks");
    ModelType<TaskContainerInternal> MODEL_TYPE = ModelType.of(TaskContainerInternal.class);

    DynamicObject getTasksAsDynamicObject();

    <T extends TaskInternal> void addPlaceholderAction(String placeholderName, Class<T> type, Action<? super T> configure);

    /**
     * Force the task graph to come into existence.
     *
     * As part of this, all placeholder actions are materialized to show up in 'tasks' and 'tasks --all' overview.
     */
    void realize();

    /**
     * Performs work to discover more tasks.
     *
     * This method differs from {@link #realize} in that it does not realize the whole subtree.
     */
    void discoverTasks();

    /**
     * Ensures that all configuration has been applied to the given task, and the task is ready to be added to the task graph.
     */
    void prepareForExecution(Task task);
}


text:
layout: framework
sidebar: category-list
---

<div class="articles">
  {% if page.banner == nil %}
    {% assign banner = page.title %}
  {% endif %}

  {{ content }}

  {% include views/pagination.html %}
</div>


text:
<?php

/**
 * dummy group backend, does not keep state, only for testing use
 */
class OC_Group_Dummy extends OC_Group_Backend {
	private $groups=array();
	/**
	 * @brief Try to create a new group
	 * @param $gid The name of the group to create
	 * @returns true/false
	 *
	 * Trys to create a new group. If the group name already exists, false will
	 * be returned.
	 */
	public function createGroup($gid) {
		if(!isset($this->groups[$gid])) {
			$this->groups[$gid]=array();
			return true;
		}else{
			return false;
		}
	}

	/**
	 * @brief delete a group
	 * @param $gid gid of the group to delete
	 * @returns true/false
	 *
	 * Deletes a group and removes it from the group_user-table
	 */
	public function deleteGroup($gid) {
		if(isset($this->groups[$gid])) {
			unset($this->groups[$gid]);
			return true;
		}else{
			return false;
		}
	}

	/**
	 * @brief is user in group?
	 * @param $uid uid of the user
	 * @param $gid gid of the group
	 * @returns true/false
	 *
	 * Checks whether the user is member of a group or not.
	 */
	public function inGroup($uid, $gid) {
		if(isset($this->groups[$gid])) {
			return (array_search($uid, $this->groups[$gid])!==false);
		}else{
			return false;
		}
	}

	/**
	 * @brief Add a user to a group
	 * @param $uid Name of the user to add to group
	 * @param $gid Name of the group in which add the user
	 * @returns true/false
	 *
	 * Adds a user to a group.
	 */
	public function addToGroup($uid, $gid) {
		if(isset($this->groups[$gid])) {
			if(array_search($uid, $this->groups[$gid])===false) {
				$this->groups[$gid][]=$uid;
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

	/**
	 * @brief Removes a user from a group
	 * @param $uid NameUSER of the user to remove from group
	 * @param $gid Name of the group from which remove the user
	 * @returns true/false
	 *
	 * removes the user from a group.
	 */
	public function removeFromGroup($uid, $gid) {
		if(isset($this->groups[$gid])) {
			if(($index=array_search($uid, $this->groups[$gid]))!==false) {
				unset($this->groups[$gid][$index]);
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

	/**
	 * @brief Get all groups a user belongs to
	 * @param $uid Name of the user
	 * @returns array with group names
	 *
	 * This function fetches all groups a user belongs to. It does not check
	 * if the user exists at all.
	 */
	public function getUserGroups($uid) {
		$groups=array();
		$allGroups=array_keys($this->groups);
		foreach($allGroups as $group) {
			if($this->inGroup($uid, $group)) {
				$groups[]=$group;
			}
		}
		return $groups;
	}

	/**
	 * @brief get a list of all groups
	 * @returns array with group names
	 *
	 * Returns a list with all groups
	 */
	public function getGroups($search = '', $limit = -1, $offset = 0) {
		return array_keys($this->groups);
	}

	/**
	 * @brief get a list of all users in a group
	 * @returns array with user ids
	 */
	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
		if(isset($this->groups[$gid])) {
			return $this->groups[$gid];
		}else{
			return array();
		}
	}

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/panel_slider"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/playerPauseResume"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:foreground="?android:attr/selectableItemBackground"
        android:clickable="true"
        android:paddingBottom="10dp"
        android:paddingEnd="15dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingStart="15dp"
        android:paddingTop="10dp"
        android:src="@drawable/ic_play_pause_white_24dp"
        tools:ignore="ContentDescription" />

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="2dp">

        <TextView
            android:id="@+id/playerElapsed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:scrollHorizontally="false"
            android:textColor="@color/icon"
            android:textSize="19sp" />

        <TextView
            android:id="@+id/playerConnection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:scrollHorizontally="false"
            android:textColor="@color/icon"
            android:textSize="14sp" />

    </LinearLayout>

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <ImageView
        android:id="@+id/playerStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:foreground="?android:attr/selectableItemBackground"
        android:clickable="true"
        android:paddingBottom="10dp"
        android:paddingEnd="15dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingStart="15dp"
        android:paddingTop="10dp"
        android:src="@drawable/ic_stop_white_24dp"
        tools:ignore="ContentDescription" />

</LinearLayout>


text:
package br.com.projetoHaras.dao;

import br.com.projetoHaras.factory.ConnectionFactory;
import br.com.projetoHaras.model.competidor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class CompetidorDao {
        public void salvar(competidor d) throws ClassNotFoundException, SQLException{
        String sql = "INSERT INTO competidor(nome, posicao, cod_animais, modalidade) VALUES(?, ?, ?, ?)";

        Connection connection = ConnectionFactory.getConnection();

        PreparedStatement stmt = connection.prepareStatement(sql);
        stmt.setString(1, d.getNome());
        stmt.setInt(2, d.getPosicao());
        stmt.setInt(3, d.getId_animais());
        stmt.setString(4, d.getModalidade());
        stmt.execute();
        stmt.close();

    }
        public void excluir(competidor d) throws ClassNotFoundException, SQLException{
        String sql = "DELETE FROM competidor WHERE id_competidor = ?";

        Connection connection = ConnectionFactory.getConnection();

        PreparedStatement stmt = connection.prepareStatement(sql);
        stmt.setInt(1, d.getId_competidor());
        stmt.execute();
        stmt.close();
    }
         public void editar(competidor d)throws ClassNotFoundException,SQLException{
        String sql= "UPDATE competidor SET nome = ?, posicao =?, cod_animais =?, modalidade =? WHERE id_competidor = ?";

        Connection connection = ConnectionFactory.getConnection();

        PreparedStatement stmt = connection.prepareStatement(sql);
        stmt.setString (1, d.getNome());
        stmt.setInt(2, d.getPosicao());;
         stmt.setInt(3, d.getId_animais());
         stmt.setString (4, d.getModalidade());
         stmt.setInt(5, d.getId_competidor());
        stmt.execute();
        stmt.close();
}
         public competidor pesquisar(competidor d)throws ClassNotFoundException, SQLException{
        String sql = "SELECT * FROM competidor WHERE id_competidor = ?";

        Connection connection = ConnectionFactory.getConnection();

        PreparedStatement stmt = connection.prepareStatement(sql);

        stmt.setInt(1, d.getId_competidor());

        ResultSet rs = stmt.executeQuery();
        competidor retorno = null;
           if(rs.next()){
            retorno = new competidor();
            retorno.setId_competidor(rs.getInt("id_competidor"));
            retorno.setNome(rs.getString("nome"));
            retorno.setPosicao(rs.getInt("posicao"));
            retorno.setId_animais(rs.getInt("cod_animais"));
            retorno.setModalidade(rs.getString("modalidade"));
        }
        return retorno;

}
        public ArrayList<competidor> lista()throws SQLException, ClassNotFoundException{
        String sql = "select competidor.id_competidor, competidor.nome, competidor.posicao, competidor.modalidade,  animais.nome from competidor "
                + "inner join animais on animais.id_animais = competidor.cod_animais ";

        Connection connection = ConnectionFactory.getConnection();

        PreparedStatement stmt = connection.prepareStatement(sql);

        ResultSet rs = stmt.executeQuery();

        ArrayList<competidor> lista = new ArrayList<competidor>();

        while(rs.next()){
            competidor e = new competidor();
            e.setId_competidor(rs.getInt("id_competidor"));
            e.setNome(rs.getString("nome"));
            e.setPosicao(rs.getInt("posicao"));
            e.setModalidade(rs.getString("modalidade"));
            e.setNomeA(rs.getString("cod_animais"));

            lista.add(e);
        }
        return lista;
    }

}