text:
var gulp = require('gulp'),
  inject = require('gulp-inject');
	gutil = require('gulp-util'),
  bower = require('bower'),
  sass = require('gulp-sass'),
  minifyCss = require('gulp-minify-css'),
  rename = require('gulp-rename'),
  sh = require('shelljs'),
  angularFilesort = require('gulp-angular-filesort'),
	jsoncombine = require("gulp-jsoncombine");

var paths = {
  sass: ['./scss/**/*.scss'],
  scripts: ['./www/scripts/**/*.js']
};

var env = process.env.NODE_ENV || 'development';

gulp.task('sass', function(done) {
  gulp.src('./scss/ionic.app.scss')
    .pipe(sass({errLogToConsole: true}))
    .pipe(gulp.dest('./www/assets/css/'))
    // .pipe(minifyCss({
    //   keepSpecialComments: 0
    // }))
    // .pipe(rename({ extname: '.min.css' }))
    // .pipe(gulp.dest('./www/assets/css/'))
    .on('end', done);
});

gulp.task('scripts', function() {
  var sources = gulp.src(paths.scripts, {
      read: true
    })
    .pipe(angularFilesort());

  gulp.src('./www/index.html')
    .pipe(inject(sources, {
      relative: true
    }))
    .pipe(gulp.dest('./www'));

});

gulp.task('cards', function() {
	gulp.src("./data/cards/*.json")
    .pipe(jsoncombine("cards.json",function (data) {
			return new Buffer(JSON.stringify(data));
		}))
    .pipe(gulp.dest("./www/data/"));
});

gulp.task('install', ['git-check'], function() {
  return bower.commands.install()
    .on('log', function(data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

gulp.task('git-check', function(done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});

gulp.task('watch', function() {
  gulp.watch(paths.sass, ['sass']);
  gulp.watch(paths.scripts, ['scripts']);
});

gulp.task('default', [
  "sass",
  "scripts"
]);


text:
package structures;

/**
 * This class is responsible for administrative tasks that are
 * common to all collection-type data structures
 *
 * @author lilott8
 * @version 0.1
 * @since 2015-02-09
 */
public abstract class JCollection<T> {

    public final String TAG = getClass().getSimpleName();

    // Total maximum size
    public final int MAX_SIZE = 1000;

    // Class instantiated size
    protected int mMaxSize;

    // Constructor
    public JCollection() {
        mMaxSize = MAX_SIZE;
    }

    // Constructor
    public JCollection(int m) {
        if(m <= MAX_SIZE) {
            mMaxSize = m;
        } else {
            mMaxSize = MAX_SIZE;
        }
    }

    /**
     * Allows the user to request more space, if they haven't exceeded the global max
     * @param m additional size asked for
     * @throws OutOfMemoryError
     */
    protected void requestMoreSpace(int m) throws OutOfMemoryError {
        if((m + mMaxSize) > MAX_SIZE) {
            throw new OutOfMemoryError("Asking for more than allowed space");
        }
        mMaxSize += m;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Copyright 2002-2018 the original author or authors.
 *
 * 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 com.linecorp.armeria.spring.web.reactive;

import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLSession;

import org.springframework.http.server.reactive.SslInfo;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Default implementation of {@link SslInfo}.
 *
 * @author Rossen Stoyanchev
 * @since 5.0.2
 */
final class DefaultSslInfo implements SslInfo {

    // Forked from spring-web-5.1.5.RELEASE at 1e4a3a2370b9ded44a62155aea59c0d81c36149f

    @Nullable
    private final String sessionId;

    @Nullable
    private final X509Certificate[] peerCertificates;

    DefaultSslInfo(@Nullable String sessionId, X509Certificate[] peerCertificates) {
        Assert.notNull(peerCertificates, "No SSL certificates");
        this.sessionId = sessionId;
        this.peerCertificates = peerCertificates;
    }

    DefaultSslInfo(SSLSession session) {
        Assert.notNull(session, "SSLSession is required");
        this.sessionId = initSessionId(session);
        this.peerCertificates = initCertificates(session);
    }

    @Override
    @Nullable
    public String getSessionId() {
        return this.sessionId;
    }

    @Override
    @Nullable
    public X509Certificate[] getPeerCertificates() {
        return this.peerCertificates;
    }

    @Nullable
    private static String initSessionId(SSLSession session) {
        byte[] bytes = session.getId();
        if (bytes == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String digit = Integer.toHexString(b);
            if (digit.length() < 2) {
                sb.append('0');
            }
            if (digit.length() > 2) {
                digit = digit.substring(digit.length() - 2);
            }
            sb.append(digit);
        }
        return sb.toString();
    }

    @Nullable
    private static X509Certificate[] initCertificates(SSLSession session) {
        Certificate[] certificates;
        try {
            certificates = session.getPeerCertificates();
        } catch (Throwable ex) {
            return null;
        }

        List<X509Certificate> result = new ArrayList<>(certificates.length);
        for (Certificate certificate : certificates) {
            if (certificate instanceof X509Certificate) {
                result.add((X509Certificate) certificate);
            }
        }
        return (!result.isEmpty() ? result.toArray(new X509Certificate[0]) : null);
    }
}


text:
require 'spec_helper'
describe TaxGenerator::FileCreator do
  let(:default_processor) {TaxGenerator::Processor.new}
  let(:output_folder) {"some_other_path" }
  let(:destinations_file_path) {  "some_path" }
  let(:destination_xml) { "some_xml" }

  let(:first_destination) { "some destination" }

  let(:fake_node) { mock }

  let(:atlas_id_value) { 'some atlas id value' }
  let(:atlas_id) { mock }
  let(:fake_tilt) {mock}

  let(:job) { { atlas_id: atlas_id_value, taxonomy: fake_node, destination: first_destination, output_folder: output_folder } }

  before(:each) do
    destination_xml.stubs(:at_xpath).returns(fake_node)
    destination_xml.stubs(:xpath).returns([fake_node])
    subject.stubs(:start_work).returns(true)
    subject.stubs(:log_message).returns(true)
    default_processor.stubs(:register_worker_for_job).returns(true)
    File.stubs(:open).returns(true)
    Tilt.stubs(:new).returns(fake_tilt)
    fake_tilt.stubs(:render).returns(true)
    subject.stubs(:mark_job_completed).returns(true)
    default_processor.stubs(:all_workers_finished).returns(false)
    default_processor.stubs(:register_worker_for_job).returns(true)
  end
    let(:subject) {
      default_processor.stubs(:register_worker_for_job).returns(true)
      TaxGenerator::FileCreator.new(*[job, default_processor]) }

  context 'checks the job keys' do

    specify { expect(subject.job).to eq job.stringify_keys }
    specify { expect(subject.processor).to eq default_processor }
  end

  context 'processes the job' do
    before(:each) do
      subject.process_job(job)
    end

    specify { expect(subject.job_id).to eq atlas_id_value }
    specify { expect(subject.destination).to eq first_destination }
    specify { expect(subject.output_folder).to eq(output_folder) }
    specify { expect(subject.taxonomy).to eq(fake_node) }
  end

  it 'gets the template name' do
    File.expects(:join).with(root, 'templates', 'template.html.erb')
    subject.template_name
  end

  context "job related " do

    it 'gets start work' do
      details = {details: fake_node, root: root}
      subject.stubs(:fetch_atlas_details).returns(details)
      fake_tilt.stubs(:render).with(subject,details).returns(true)
      subject.start_work
    end

    it 'mark_job_completed' do
      default_processor.register_jobs(job)
      subject.mark_job_completed
      expect(subject.processor.jobs[subject.job_id]).to eq(job.stringify_keys)
    end

    it 'fetch_atlas_details' do
      subject.stubs(:atlas_node).returns(fake_node)
      TaxGenerator::Destination.expects(:new).with(first_destination).returns(first_destination)
      first_destination.stubs(:to_hash).returns({})
      actual = subject.fetch_atlas_details
      expect(actual).to eq({details: fake_node})
    end
  end

end


text:
package org.apache.velocity.test;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.velocity.runtime.parser.node.MathUtils;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * Test arithmetic operations. Introduced after extending from Integer-only
 * to Number-handling.
 *
 * @author Peter Romianowski
 */
public class ArithmeticTestCase extends TestCase
{

    public ArithmeticTestCase(String testName)
    {
        super(testName);
    }

    public static Test suite()
    {
       return new TestSuite(ArithmeticTestCase.class);
    }

    public void testAdd()
    {
        addHelper (10, (short) 20, 30, Integer.class);
        addHelper ((byte) 10, (short) 20, 30, Short.class);
        addHelper (10f, (short) 20, 30, Float.class);
        addHelper ((byte) 10, 20d, 30, Double.class);
        addHelper (BigInteger.valueOf(10), 20, 30, BigInteger.class);
        addHelper (20, BigDecimal.valueOf(10),  30, BigDecimal.class);

        // Test overflow
        addHelper (Integer.MAX_VALUE, (short) 20, (double)Integer.MAX_VALUE+20, Long.class);
        addHelper (20, Long.MAX_VALUE, (double)Long.MAX_VALUE+20, BigInteger.class);
        addHelper (-20, Long.MIN_VALUE, (double)Long.MIN_VALUE-20, BigInteger.class);
    }

    private void addHelper (Number n1, Number n2, double expectedResult, Class expectedResultType)
    {
        Number result = MathUtils.add( n1, n2);
        assertEquals("The arithmetic operation produced an unexpected result.", expectedResult, result.doubleValue(), 0.01);
        assertEquals("ResultType does not match.", expectedResultType, result.getClass());
    }

    public void testSubtract()
    {
        subtractHelper (100, (short) 20, 80, Integer.class);
        subtractHelper ((byte) 100, (short) 20, 80, Short.class);
        subtractHelper (100f, (short) 20, 80, Float.class);
        subtractHelper ((byte) 100, 20d, 80, Double.class);
        subtractHelper (BigInteger.valueOf(100), 20, 80, BigInteger.class);
        subtractHelper (100, BigDecimal.valueOf(20),  80, BigDecimal.class);

        // Test overflow
        subtractHelper (Integer.MIN_VALUE, (short) 20, (double)Integer.MIN_VALUE-20, Long.class);
        subtractHelper(-20, Long.MAX_VALUE, -20d - (double) Long.MAX_VALUE, BigInteger.class);
        subtractHelper(Integer.MAX_VALUE, Long.MIN_VALUE, (double) Long.MAX_VALUE + (double) Integer.MAX_VALUE, BigInteger.class);
    }

    private void subtractHelper (Number n1, Number n2, double expectedResult, Class expectedResultType)
    {
        Number result = MathUtils.subtract( n1, n2);
        assertEquals("The arithmetic operation produced an unexpected result.", expectedResult, result.doubleValue(), 0.01);
        assertEquals("ResultType does not match.", expectedResultType, result.getClass());
    }

    public void testMultiply()
    {
        multiplyHelper (10, (short) 20, 200, Integer.class);
        multiplyHelper ((byte) 100, (short) 20, 2000, Short.class);
        multiplyHelper ((byte) 100, (short) 2000, 200000, Integer.class);
        multiplyHelper (100f, (short) 20, 2000, Float.class);
        multiplyHelper ((byte) 100, 20d, 2000, Double.class);
        multiplyHelper (BigInteger.valueOf(100), 20, 2000, BigInteger.class);
        multiplyHelper (100, BigDecimal.valueOf(20),  2000, BigDecimal.class);

        // Test overflow
        multiplyHelper (Integer.MAX_VALUE, (short) 10, (double)Integer.MAX_VALUE*10d, Long.class);
        multiplyHelper(Integer.MAX_VALUE, (short) -10, (double) Integer.MAX_VALUE * -10d, Long.class);
        multiplyHelper(20, Long.MAX_VALUE, 20d * (double) Long.MAX_VALUE, BigInteger.class);
    }

    private void multiplyHelper (Number n1, Number n2, double expectedResult, Class expectedResultType)
    {
        Number result = MathUtils.multiply( n1, n2);
        assertEquals("The arithmetic operation produced an unexpected result.", expectedResult, result.doubleValue(), 0.01);
        assertEquals("ResultType does not match.", expectedResultType, result.getClass());
    }

    public void testDivide()
    {
        divideHelper (10, (short) 2, 5, Integer.class);
        divideHelper ((byte) 10, (short) 2, 5, Short.class);
        divideHelper (BigInteger.valueOf(10), (short) 2, 5, BigInteger.class);
        divideHelper (10, (short) 4, 2, Integer.class);
        divideHelper (10, 2.5f, 4, Float.class);
        divideHelper(10, 2.5, 4, Double.class);
        divideHelper(10, new BigDecimal(2.5), 4, BigDecimal.class);
    }

    private void divideHelper (Number n1, Number n2, double expectedResult, Class expectedResultType)
    {
        Number result = MathUtils.divide( n1, n2);
        assertEquals("The arithmetic operation produced an unexpected result.", expectedResult, result.doubleValue(), 0.01);
        assertEquals("ResultType does not match.", expectedResultType, result.getClass());
    }

    public void testModulo()
    {
        moduloHelper (10, (short) 2, 0, Integer.class);
        moduloHelper ((byte) 10, (short) 3, 1, Short.class);
        moduloHelper(BigInteger.valueOf(10), (short) 4, 2, BigInteger.class);
        moduloHelper(10, 5.5f, 4.5, Float.class);

        try
        {
            moduloHelper (10, new BigDecimal( 2.5), 4, BigDecimal.class);
            fail ("Modulo with BigDecimal is not allowed! Should have thrown an ArithmeticException.");
        }
        catch( ArithmeticException e)
        {
            // do nothing
        }
    }

    private void moduloHelper (Number n1, Number n2, double expectedResult, Class expectedResultType)
    {
        Number result = MathUtils.modulo( n1, n2);
        assertEquals("The arithmetic operation produced an unexpected result.", expectedResult, result.doubleValue(), 0.01);
        assertEquals("ResultType does not match.", expectedResultType, result.getClass());
    }

    public void testCompare()
    {
        compareHelper (10, (short) 10, 0);
        compareHelper (10, (short) 11, -1);
        compareHelper (BigInteger.valueOf(10), (short) 11, -1);
        compareHelper ((byte) 10, (short) 3, 1);
        compareHelper(10f, (short) 11, -1);
        compareHelper(10d, (short) 11, -1);
    }

    private void compareHelper (Number n1, Number n2, int expectedResult)
    {
        int result = MathUtils.compare( n1, n2 );
        assertEquals("The arithmetic operation produced an unexpected result.", expectedResult, result);
    }

    public void testNegate()
    {
        negateHelper((byte) 1, -1, Byte.class);
        negateHelper((short) 1, -1, Short.class);
        negateHelper(1, -1, Integer.class);
        negateHelper(1L, -1, Long.class);
        negateHelper(BigInteger.valueOf(1), -1, BigInteger.class);
        negateHelper(BigDecimal.valueOf(1), -1, BigDecimal.class);
        negateHelper(Long.MIN_VALUE, BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(1)).doubleValue(), BigInteger.class);
    }

    private void negateHelper(Number n, double expectedResult, Class expectedResultType)
    {
        Number result = MathUtils.negate(n);
        assertEquals ("The arithmetic operation produced an unexpected result.", expectedResult, result.doubleValue(), 0.01);
        assertEquals ("ResultType does not match.", expectedResultType, result.getClass());
    }

/*
 *
 *    COMMENT OUT FOR PERFORMANCE-MEASSUREMENTS
 *
 *    public void testProfile()
 *    {
 *
 *        long start = System.currentTimeMillis();
 *
 *        Number v1 = new Long (1000);
 *        Number v2 = new Double (10.23);
 *        Number result = null;
 *        for (int a = 0; a < 10000; a++)
 *        {
 *
 *            result = MathUtils.typeConvert (
 *                new BigDecimal (v1.doubleValue()).add (
 *                new BigDecimal (v2.doubleValue())), v1, v2, false);
 *
 *        }
 *
 *        System.out.println ("took: "+(System.currentTimeMillis()-start));
 *
 *        start = System.currentTimeMillis();
 *        for (int a = 0; a < 10000; a++)
 *        {
 *
 *            result = MathUtils.divide( v1, v2);
 *        }
 *
 *        Number result2 = result;
 *        System.out.println ("took: "+(System.currentTimeMillis()-start));
 *    }
 *
 */

    /**
     * Test additional functions
     */
    public void testIsZero()
    {
        assertTrue (MathUtils.isZero (0));
        assertTrue (!MathUtils.isZero (1));
        assertTrue (!MathUtils.isZero (-1));

        assertTrue (MathUtils.isZero (0f));
        assertTrue (!MathUtils.isZero (0.00001f));
        assertTrue (!MathUtils.isZero (-0.00001f));

    }

}


text:
<?php
/*
 * Account/Approve.php
 * LHS Math Club Website
 *
 * When a user has completed registration, this page prompts them to print
 * out an information page and give it to a captain to approve their
 * account.
 */

require_once '../.lib/functions.php';
restrict_access('P');

show_page();

function show_page() {
	$query = 'SELECT * FROM users WHERE id="' . $_SESSION['user_id'] . '" LIMIT 1';
	$result = DB::queryRaw($query);
	$row = mysqli_fetch_assoc($result);

	$cell = format_phone_number($row['cell']);
	if ($cell == '')
		$cell = 'None';

	page_title('Approve');
?>

Account Approval

Your account has been verified, but it must be approved by a captain. Please print this page and bring it to practice.

	ID: <?=$row['id']?>

	Name: <?=$row['name']?>

	Cell: <?=$cell?>

	Email: <?=$row['email']?>

	YOG: <?=$row['yog']?>

	Account Type: <?=$row['permissions']?>

<?php
}

?>


text:
<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/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.all.client.model</groupId>
	<artifactId>model</artifactId>
	<packaging>jar</packaging>
	<version>${snapshot.version}</version>
	<name>model</name>

	<parent>
		<groupId>com.all.maven</groupId>
		<artifactId>parent</artifactId>
		<version>1.0.0-SNAPSHOT</version>
	</parent>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<properties>
		<project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org</groupId>
			<artifactId>jaudiotagger</artifactId>
			<version>2.0.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>jna</artifactId>
			<version>3.2.7</version>
		</dependency>
		<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>platform</artifactId>
			<version>3.2.7</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
			<version>2.3.1</version>
		</dependency>

		<!-- ALL.COM DEPENDENCIES -->
		<dependency>
			<groupId>com.all.shared</groupId>
			<artifactId>shared</artifactId>
			<version>${snapshot.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>com.all</groupId>
			<artifactId>appControl</artifactId>
			<version>${snapshot.version}</version>
		</dependency>
		<dependency>
			<groupId>com.all</groupId>
			<artifactId>downloader</artifactId>
			<version>${snapshot.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>com.all</groupId>
			<artifactId>twitter</artifactId>
			<version>${snapshot.version}</version>
		</dependency>
	</dependencies>

</project>


text:
<!-- Polymer -->
<link rel="import" href="../../../../bower_components/polymer/polymer-element.html">

<!-- Polymer Elements -->
<link rel="import" href="../../../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../../../bower_components/app-storage/app-indexeddb-mirror/app-indexeddb-mirror.html">

<!-- BS4 Polymer -->
<link rel="import" href="../../../../node_modules/bs4-polymer/dist/shared-styles/bs4-grid/bs4-grid.html">

<!-- Elements -->
<link rel="import" href="../../elements/rmc-text-view.html">

<!-- Mixins -->
<link rel="import" href="../../mixins/rmc-loading-mixin.html">

<!-- Shared Styles -->
<link rel="import" href="../../shared-styles/rmc-shared-styles-views.html">

<!--
`<view-admin-about>` is the view for the admin about page.

In typical use, add the element to an `<iron-pages>` element:

    <iron-pages
        selected="[[page]]"
        attr-for-selected="id"
        role="main">

        <view-admin-about id="about"></view-admin-about>
        ...
    </iron-pages>
-->
<dom-module id="view-admin-about">
  <template>
    <style include="bs4-shared-styles-grid"></style>
    <style include="rmc-shared-styles-views">
    .container {
      margin-top: 0;
    }
    </style>

    <!-- container -->
    <div class="container">
        <!-- About Text -->
        <rmc-text-view view="about" title="About" loading="{{loading}}" editable></rmc-text-view>
    </div>
    <!-- /container -->

  </template>

  <script>
    /* eslint new-cap: [2, {"capIsNewExceptions": ["RMCLoadingMixin"]}] */
    /* global RMCLoadingMixin */

    /**
     * Class representing admin about view.
     * @appliesMixin RMCLoadingMixin
     */
    class ViewAdminAbout extends RMCLoadingMixin(Polymer.Element) {
      /** HTML tag name. */
      static get is() {
        return 'view-admin-about';
      }
    }
    window.customElements.define(ViewAdminAbout.is, ViewAdminAbout);
  </script>
</dom-module>


text:
<?php

namespace Yandex\Metrica\Management\Models;

use Yandex\Metrica\Management\Models\Goals;
use Yandex\Common\Model;

class GetGoalsResponse extends Model
{

    protected $goals = null;

    protected $mappingClasses = [
        'goals' => 'Yandex\Metrica\Management\Models\Goals'
    ];

    protected $propNameMap = [];

    /**
     * Retrieve the goals property
     *
     * @return Goals|null
     */
    public function getGoals()
    {
        return $this->goals;
    }

    /**
     * Set the goals property
     *
     * @param Goals $goals
     * @return $this
     */
    public function setGoals($goals)
    {
        $this->goals = $goals;
        return $this;
    }
}


text:
This will become an automated CI service for [Inch](https://github.com/rrrene/inch).

## Installation

`Inch CI` is a basic [Rails](https://github.com/rails/rails) app that requires [Sidekiq](https://github.com/mperham/sidekiq) for its background-workers.

Fork the project, clone it and then execute:

    $ bundle install

### Configuration

As in every Rails app, you have to configure your database via `config/database.yml`. Optionally, you can add a valid GitHub access token to `config/access_tokens.yml` (sample files are present in `config/`).

### Seeding

After configuring the above, you can seed the database using `rake db:seed`. This will download the [_projects.yml](https://github.com/rrrene/inch-pages/blob/master/_projects.yml) file from the old Inch Pages project and seed the first 5 projects into your database (if you want to add more projects, use `COUNT=X rake db:seed`, where `X` is the desired number)

## Contributing

1. [Fork it!](http://github.com/inch-ci/inch_ci-web/fork)
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Author

René Föhring (@rrrene)

## Credits

Inch CI takes a lot of inspiration from the existing CI services, most notably Travis and Code Climate, which helped me improve my code long before I had the idea for Inch.

## License

Inch is released under the MIT License. See the LICENSE.txt file for further
details.


text:
package org.apache.hadoop.hive.ql;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.hive.ql.QTestMiniClusters.FsType;
import org.apache.hadoop.hive.ql.qoption.QTestReplaceHandler;

/**
 * QOutProcessor: produces the final q.out from original q.out by postprocessing (e.g. masks)
 *
 */
public class QOutProcessor {
  public static final String PATH_HDFS_REGEX = "(hdfs://)([a-zA-Z0-9:/_\\-\\.=])+";
  public static final String PATH_HDFS_WITH_DATE_USER_GROUP_REGEX =
      "([a-z]+) ([a-z]+)([ ]+)([0-9]+) ([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}) "
          + PATH_HDFS_REGEX;

  public static final String HDFS_MASK = "### HDFS PATH ###";
  public static final String HDFS_DATE_MASK = "### HDFS DATE ###";
  public static final String HDFS_USER_MASK = "### USER ###";
  public static final String HDFS_GROUP_MASK = "### GROUP ###";

  public static final String MASK_PATTERN = "#### A masked pattern was here ####";
  public static final String PARTIAL_MASK_PATTERN = "#### A PARTIAL masked pattern was here ####";

  private final Set<String> qMaskStatsQuerySet = new HashSet<String>();
  private final Set<String> qMaskDataSizeQuerySet = new HashSet<String>();
  private final Set<String> qMaskLineageQuerySet = new HashSet<String>();

  private static final PatternReplacementPair MASK_STATS = new PatternReplacementPair(
      Pattern.compile(" Num rows: [1-9][0-9]* Data size: [1-9][0-9]*"),
      " Num rows: ###Masked### Data size: ###Masked###");
  private static final PatternReplacementPair MASK_DATA_SIZE = new PatternReplacementPair(
      Pattern.compile(" Data size: [1-9][0-9]*"),
      " Data size: ###Masked###");
  private static final PatternReplacementPair MASK_LINEAGE = new PatternReplacementPair(
      Pattern.compile("POSTHOOK: Lineage: .*"),
      "POSTHOOK: Lineage: ###Masked###");

  private static final Pattern PATTERN_MASK_STATS = Pattern.compile("-- MASK_STATS");
  private static final Pattern PATTERN_MASK_DATA_SIZE = Pattern.compile("-- MASK_DATA_SIZE");
  private static final Pattern PATTERN_MASK_LINEAGE = Pattern.compile("-- MASK_LINEAGE");

  private FsType fsType = FsType.LOCAL;

  public static class LineProcessingResult {
    private String line;
    private boolean partialMaskWasMatched = false;

    public LineProcessingResult(String line) {
      this.line = line;
    }

    public String get() {
      return line;
    }
  }

  private final Pattern[] planMask = toPattern(new String[] {
      ".*[.][.][.] [0-9]* more.*",
      "pk_-?[0-9]*_[0-9]*_[0-9]*",
      "fk_-?[0-9]*_[0-9]*_[0-9]*",
      "uk_-?[0-9]*_[0-9]*_[0-9]*",
      "nn_-?[0-9]*_[0-9]*_[0-9]*", // not null constraint name
      "dc_-?[0-9]*_[0-9]*_[0-9]*", // default constraint name
      "org\\.apache\\.hadoop\\.hive\\.metastore\\.model\\.MConstraint@([0-9]|[a-z])*",
  });

  // Using patterns for matching the whole line can take a long time, therefore we should try to avoid it
  // in case of really long lines trying to match a .*some string.* may take up to 4 seconds each!

  // Using String.startsWith instead of pattern, as it is much faster
  private final String[] maskIfStartsWith = new String[] {
      "Deleted",
      "Repair: Added partition to metastore",
      "latestOffsets",
      "minimumLag"
  };

  // Using String.contains instead of pattern, as it is much faster
  private final String[] maskIfContains = new String[] {
      "file:",
      "pfile:",
      "/tmp/",
      "invalidscheme:",
      "lastUpdateTime",
      "lastAccessTime",
      "lastModifiedTim",
      "Owner",
      "owner",
      "CreateTime",
      "LastAccessTime",
      "Location",
      "LOCATION '",
      "transient_lastDdlTime",
      "last_modified_",
      "at org",
      "at sun",
      "at java",
      "at junit",
      "Caused by:",
      "LOCK_QUERYID:",
      "LOCK_TIME:",
      "grantTime",
      "job_",
      "USING 'java -cp",
      "DagName:",
      "DagId:",
      "total number of created files now is",
      "hive-staging",
      "at com.sun.proxy",
      "at com.jolbox",
      "at com.zaxxer"
  };

  // Using String.contains instead of pattern, as it is much faster
  private final String[][] maskIfContainsMultiple = new String[][] {
    {"Input:", "/data/files/"},
    {"Output:", "/data/files/"}
  };

  private final QTestReplaceHandler replaceHandler;

  public QOutProcessor(FsType fsType, QTestReplaceHandler replaceHandler) {
    this.fsType = fsType;
    this.replaceHandler = replaceHandler;
  }

  private Pattern[] toPattern(String[] patternStrs) {
    Pattern[] patterns = new Pattern[patternStrs.length];
    for (int i = 0; i < patternStrs.length; i++) {
      patterns[i] = Pattern.compile(patternStrs[i]);
    }
    return patterns;
  }

  public void maskPatterns(String fname, String tname) throws Exception {

    String line;
    BufferedReader in;
    BufferedWriter out;

    File file = new File(fname);
    File fileOrig = new File(fname + ".orig");
    FileUtils.copyFile(file, fileOrig);

    in = new BufferedReader(new InputStreamReader(new FileInputStream(fileOrig), "UTF-8"));
    out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));

    boolean lastWasMasked = false;

    while (null != (line = in.readLine())) {
      LineProcessingResult result = processLine(line, tname);

      if (result.line.equals(MASK_PATTERN)) {
        // We're folding multiple masked lines into one.
        if (!lastWasMasked) {
          out.write(result.line);
          out.write("\n");
          lastWasMasked = true;
          result.partialMaskWasMatched = false;
        }
      } else {
        out.write(result.line);
        out.write("\n");
        lastWasMasked = false;
        result.partialMaskWasMatched = false;
      }
    }

    in.close();
    out.close();
  }

  public LineProcessingResult processLine(String line, String tname) {
    LineProcessingResult result = new LineProcessingResult(line);

    Matcher matcher = null;

    if (fsType == FsType.ENCRYPTED_HDFS) {
      for (Pattern pattern : partialReservedPlanMask) {
        matcher = pattern.matcher(result.line);
        if (matcher.find()) {
          result.line = PARTIAL_MASK_PATTERN + " " + matcher.group(0);
          result.partialMaskWasMatched = true;
          break;
        }
      }
    }
    else {
      for (PatternReplacementPair prp : partialPlanMask) {
        matcher = prp.pattern.matcher(result.line);
        if (matcher.find()) {
          result.line = result.line.replaceAll(prp.pattern.pattern(), prp.replacement);
          result.partialMaskWasMatched = true;
        }
      }
    }

    if (!result.partialMaskWasMatched) {
      for (Pair<Pattern, String> pair : patternsWithMaskComments) {
        Pattern pattern = pair.getLeft();
        String maskComment = pair.getRight();

        matcher = pattern.matcher(result.line);
        if (matcher.find()) {
          result.line = matcher.replaceAll(maskComment);
          result.partialMaskWasMatched = true;
          break;
        }
      }

      if (!result.partialMaskWasMatched && qMaskStatsQuerySet.contains(tname)) {
        matcher = MASK_STATS.pattern.matcher(result.line);
        if (matcher.find()) {
          result.line = result.line.replaceAll(MASK_STATS.pattern.pattern(), MASK_STATS.replacement);
          result.partialMaskWasMatched = true;
        }
      }

      if (!result.partialMaskWasMatched && qMaskDataSizeQuerySet.contains(tname)) {
        matcher = MASK_DATA_SIZE.pattern.matcher(result.line);
        if (matcher.find()) {
          result.line = result.line.replaceAll(MASK_DATA_SIZE.pattern.pattern(), MASK_DATA_SIZE.replacement);
          result.partialMaskWasMatched = true;
        }
      }

      if (!result.partialMaskWasMatched && qMaskLineageQuerySet.contains(tname)) {
        matcher = MASK_LINEAGE.pattern.matcher(result.line);
        if (matcher.find()) {
          result.line = result.line.replaceAll(MASK_LINEAGE.pattern.pattern(), MASK_LINEAGE.replacement);
          result.partialMaskWasMatched = true;
        }
      }

      for (String prefix : maskIfStartsWith) {
        if (result.line.startsWith(prefix)) {
          result.line = MASK_PATTERN;
        }
      }

      for (String word : maskIfContains) {
        if (result.line.contains(word)) {
          result.line = MASK_PATTERN;
        }
      }

      for (String[] words : maskIfContainsMultiple) {
        int pos = 0;
        boolean containsAllInOrder = true;
        for (String word : words) {
          int wordPos = result.line.substring(pos).indexOf(word);
          if (wordPos == -1) {
            containsAllInOrder = false;
            break;
          } else {
            pos += wordPos + word.length();
          }
        }
        if (containsAllInOrder) {
          result.line = MASK_PATTERN;
        }
      }

      for (Pattern pattern : planMask) {
        result.line = pattern.matcher(result.line).replaceAll(MASK_PATTERN);
      }
    }

    result.line = replaceHandler.processLine(result.line);

    return result;
  }

  private final Pattern[] partialReservedPlanMask = toPattern(new String[] {
      "data/warehouse/(.*?/)+\\.hive-staging"  // the directory might be db/table/partition
      //TODO: add more expected test result here
  });
  /**
   * Pattern to match and (partial) replacement text.
   * For example, {"transaction":76,"bucketid":8249877}.  We just want to mask 76 but a regex that
   * matches just 76 will match a lot of other things.
   */
  private final static class PatternReplacementPair {
    private final Pattern pattern;
    private final String replacement;
    PatternReplacementPair(Pattern p, String r) {
      pattern = p;
      replacement = r;
    }
  }
  private final PatternReplacementPair[] partialPlanMask;
  {
    ArrayList<PatternReplacementPair> ppm = new ArrayList<>();
    ppm.add(new PatternReplacementPair(Pattern.compile("\\{\"writeid\":[1-9][0-9]*,\"bucketid\":"),
        "{\"writeid\":### Masked writeid ###,\"bucketid\":"));

    ppm.add(new PatternReplacementPair(Pattern.compile("attempt_[0-9_]+"), "attempt_#ID#"));
    ppm.add(new PatternReplacementPair(Pattern.compile("vertex_[0-9_]+"), "vertex_#ID#"));
    ppm.add(new PatternReplacementPair(Pattern.compile("task_[0-9_]+"), "task_#ID#"));
    ppm.add(new PatternReplacementPair(Pattern.compile("for Spark session.*?:"),
            "#SPARK_SESSION_ID#:"));

    ppm.add(new PatternReplacementPair(Pattern.compile("rowcount = [0-9]+(\\.[0-9]+(E[0-9]+)?)?, cumulative cost = \\{.*\\}, id = [0-9]*"),
        "rowcount = ###Masked###, cumulative cost = ###Masked###, id = ###Masked###"));

    partialPlanMask = ppm.toArray(new PatternReplacementPair[ppm.size()]);
  }

  @SuppressWarnings("serial")
  private ArrayList<Pair<Pattern, String>> initPatternWithMaskComments() {
    return new ArrayList<Pair<Pattern, String>>() {
      {
        add(toPatternPair("(pblob|s3.?|swift|wasb.?).*hive-staging.*",
            "### BLOBSTORE_STAGING_PATH ###"));
        add(toPatternPair(PATH_HDFS_WITH_DATE_USER_GROUP_REGEX, String.format("%s %s$3$4 %s $6%s",
            HDFS_USER_MASK, HDFS_GROUP_MASK, HDFS_DATE_MASK, HDFS_MASK)));
        add(toPatternPair(PATH_HDFS_REGEX, String.format("$1%s", HDFS_MASK)));
      }
    };
  }

  /* This list may be modified by specific cli drivers to mask strings that change on every test */
  private List<Pair<Pattern, String>> patternsWithMaskComments = initPatternWithMaskComments();

  private Pair<Pattern, String> toPatternPair(String patternStr, String maskComment) {
    return ImmutablePair.of(Pattern.compile(patternStr), maskComment);
  }

  public void addPatternWithMaskComment(String patternStr, String maskComment) {
    patternsWithMaskComments.add(toPatternPair(patternStr, maskComment));
  }

  public void initMasks(File qf, String query) {
    if (matches(PATTERN_MASK_STATS, query)) {
      qMaskStatsQuerySet.add(qf.getName());
    }
    if (matches(PATTERN_MASK_DATA_SIZE, query)) {
      qMaskDataSizeQuerySet.add(qf.getName());
    }
    if (matches(PATTERN_MASK_LINEAGE, query)) {
      qMaskLineageQuerySet.add(qf.getName());
    }
  }

  private boolean matches(Pattern pattern, String query) {
    Matcher matcher = pattern.matcher(query);
    if (matcher.find()) {
      return true;
    }
    return false;
  }

  public void resetPatternwithMaskComments() {
    patternsWithMaskComments = initPatternWithMaskComments();
  }

}


text:
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Model;
using MongoDB.Driver;
using Spark.Engine.Core;

namespace Spark.Store.Mongo
{
    public static class SparkBsonHelper
    {
        public static BsonDocument CreateDocument(Resource resource)
        {
            if (resource != null)
            {
                FhirJsonSerializer serializer = new FhirJsonSerializer();
                return BsonDocument.Parse(serializer.SerializeToString(resource));
            }
            else
            {
                return new BsonDocument();
            }
        }

        public static BsonValue ToBsonReferenceKey(this IKey key)
        {
            return new BsonString(key.TypeName + "/" + key.ResourceId);
        }

        public static BsonDocument ToBsonDocument(this Entry entry)
        {
            BsonDocument document = CreateDocument(entry.Resource);
            AddMetaData(document, entry);
            return document;
        }

        public static Resource ParseResource(BsonDocument document)
        {
            RemoveMetadata(document);
            string json = document.ToJson();
            FhirJsonParser parser = new FhirJsonParser();
            return parser.Parse<Resource>(json);
        }

        public static Entry ExtractMetadata(BsonDocument document)
        {
            DateTime when = GetVersionDate(document);
            IKey key = GetKey(document);
            Bundle.HTTPVerb method = (Bundle.HTTPVerb)(int)document[Field.METHOD];

            RemoveMetadata(document);
            return  Entry.Create(method, key, when);
        }

        public static Entry ToEntry(this BsonDocument document)
        {
            if (document == null) return null;

            try
            {
                Entry entry = ExtractMetadata(document);
                if (entry.IsPresent)
                {
                    entry.Resource = ParseResource(document);
                }
                return entry;
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Mongo document contains invalid BSON to parse.", e);
            }
        }

        public static IEnumerable<Entry> ToEntries(this MongoCursor<BsonDocument> cursor)
        {
            foreach (BsonDocument document in cursor)
            {
                Entry entry = SparkBsonHelper.ToEntry(document);
                yield return entry;
            }
        }

        public static DateTime GetVersionDate(BsonDocument document)
        {
            BsonValue value = document[Field.WHEN];
            return value.ToUniversalTime();
        }

        private static void ensureMeta(Resource resource)
        {
            if (resource.Meta == null)
                resource.Meta = new Meta();
        }

        public static void AddVersionDate(Entry entry, DateTime when)
        {
            entry.When = when;
            if (entry.Resource != null)
            {
                ensureMeta(entry.Resource);
                entry.Resource.Meta.LastUpdated = when;
            }
        }

        public static void RemoveMetadata(BsonDocument document)
        {
            document.Remove(Field.PRIMARYKEY);
            document.Remove(Field.REFERENCE);
            document.Remove(Field.WHEN);
            document.Remove(Field.STATE);
            document.Remove(Field.VERSIONID);
            document.Remove(Field.TYPENAME);
            document.Remove(Field.METHOD);
            document.Remove(Field.TRANSACTION);
        }

        public static void AddMetaData(BsonDocument document, Entry entry)
        {
            document[Field.METHOD] = entry.Method;
            document[Field.PRIMARYKEY] = entry.Key.ToOperationPath();
            document[Field.REFERENCE] = entry.Key.ToBsonReferenceKey();
            AddMetaData(document, entry.Key, entry.Resource);
        }

        private static void AssertKeyIsValid(IKey key)
        {
            bool valid = (key.Base == null) && (key.TypeName != null) && (key.ResourceId != null) && (key.VersionId != null);
            if (!valid)
            {
                throw new Exception("This key is not valid for storage: " + key.ToString());
            }
        }

        public static void AddMetaData(BsonDocument document, IKey key, Resource resource)
        {
            AssertKeyIsValid(key);
            document[Field.TYPENAME] = key.TypeName;
            document[Field.RESOURCEID] = key.ResourceId;
            document[Field.VERSIONID] = key.VersionId;

            document[Field.WHEN] = (resource!= null && resource.Meta!= null && resource.Meta.LastUpdated.HasValue)?
                resource.Meta.LastUpdated.Value.UtcDateTime : DateTime.UtcNow;
            document[Field.STATE] = Value.CURRENT;
        }

        public static IKey GetKey(BsonDocument document)
        {
            Key key = new Key();
            key.TypeName = (string)document[Field.TYPENAME];
            key.ResourceId = (string)document[Field.RESOURCEID];
            key.VersionId = (string)document[Field.VERSIONID];

            return key;
        }

        public static void TransferMetadata(BsonDocument from, BsonDocument to)
        {
            to[Field.TYPENAME] = from[Field.TYPENAME];
            to[Field.RESOURCEID] = from[Field.RESOURCEID];
            to[Field.VERSIONID] = from[Field.VERSIONID];
            to[Field.WHEN] = from[Field.WHEN];
            to[Field.METHOD] = from[Field.METHOD];
            to[Field.STATE] = from[Field.STATE];
        }

    }
}


text:
\hypertarget{structmg__rpc__error}{}\section{mg\+\_\+rpc\+\_\+error Struct Reference}
\label{structmg__rpc__error}\index{mg\+\_\+rpc\+\_\+error@{mg\+\_\+rpc\+\_\+error}}
\subsection*{Public Attributes}
\begin{DoxyCompactItemize}
\item
struct \hyperlink{structjson__token}{json\+\_\+token} $\ast$ {\bfseries message}\hypertarget{structmg__rpc__error_a26d69a75e899c104f8e72b5964e7bebd}{}\label{structmg__rpc__error_a26d69a75e899c104f8e72b5964e7bebd}

\item
struct \hyperlink{structjson__token}{json\+\_\+token} $\ast$ {\bfseries id}\hypertarget{structmg__rpc__error_a1d656c7b0f345c6b4dabdcdbc731c9a8}{}\label{structmg__rpc__error_a1d656c7b0f345c6b4dabdcdbc731c9a8}

\item
struct \hyperlink{structjson__token}{json\+\_\+token} $\ast$ {\bfseries error\+\_\+code}\hypertarget{structmg__rpc__error_abc71688a1a85dee9d31cd0077228d3b7}{}\label{structmg__rpc__error_abc71688a1a85dee9d31cd0077228d3b7}

\item
struct \hyperlink{structjson__token}{json\+\_\+token} $\ast$ {\bfseries error\+\_\+message}\hypertarget{structmg__rpc__error_a48b5c825149b7ed257e80be9d7930bf1}{}\label{structmg__rpc__error_a48b5c825149b7ed257e80be9d7930bf1}

\item
struct \hyperlink{structjson__token}{json\+\_\+token} $\ast$ {\bfseries error\+\_\+data}\hypertarget{structmg__rpc__error_ac776ef39ac336b5f92b9976c8432db6b}{}\label{structmg__rpc__error_ac776ef39ac336b5f92b9976c8432db6b}

\end{DoxyCompactItemize}

The documentation for this struct was generated from the following file\+:\begin{DoxyCompactItemize}
\item
Appserver/src/external/mongoose/mongoose.\+h\end{DoxyCompactItemize}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.PublicationDAO;
import dao.ReportDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Publication;
import model.Report;

/**
 *
 * @author Mac
 */
@WebServlet(name = "studentReportController", urlPatterns = {"/student-report"})
public class studentReportController extends HttpServlet {

    ReportDAO reportDAO = ReportDAO.getInstance();
    PublicationDAO publicationDAO = PublicationDAO.getInstance();

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // do nothing
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ArrayList<Publication> publications = PublicationDAO.getInstance().getUnlistedPublicationList((int) request.getSession().getAttribute("user"));
        request.setAttribute("publications", publications);
        request.getRequestDispatcher("View/studentReport.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ArrayList<Publication> publications = publicationDAO.getUnlistedPublicationList((int) request.getSession().getAttribute("user"));

        Report report = new Report((int) request.getSession().getAttribute("user"), request.getParameter("content"));

        reportDAO.saveToDb(report);

        report.setId(reportDAO.getLastReportId((int) request.getSession().getAttribute("user")));

        for (Publication p : publications){
            p.setReport(report);
            publicationDAO.setReport(p);
        }

        response.sendRedirect("student-report");

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


text:
struct participant {
    participant *next;
    std::atomic<size_t> active;
    local_config conf;

    inline void enter(GCClassBase *p);
    inline void exit();
};

void participant::enter(GCClassBase *p) {
    size_t cur = active.load(std::memory_order_relaxed);
    active.store(cur + 1, std::memory_order_relaxed);
    std::atomic_signal_fence(std::memory_order_seq_cst);
    if (cur == 0 && p->needs_fence()) {
        std::atomic_thread_fence(std::memory_order_seq_cst);
    }
}

void participant::exit() {
    size_t cur = active.load(std::memory_order_relaxed);
    active.store(cur - 1, std::memory_order_release);
}

participant *get_active_participants();
void add_active_participant(participant *p);

inline participant *get_current_participant() {
    thread_local participant *p = nullptr;
    if (p == nullptr) {
        p = new participant;
        add_active_participant(p);
    }
    return p;
}


text:
var module = angular.module('add', ['index', 'duScroll', 'ngFileUpload']);

module.controller('TabCtrl', function($scope, $rootScope) {
	$rootScope.objectClass = 'active';
	$rootScope.placeClass = '';
	$rootScope.typeClass = '';
	$rootScope.subtypeClass = '';
	$rootScope.brandClass = '';

	$scope.selectDiv = function(div) {
		if(div == 'object') {
			$rootScope.objectClass = 'active';
		} else {
			$rootScope.barcode = {
                		'id'  : null,
                		'loc' : null,
                		'tip' : null,
                		'stp' : null,
                		'mar' : null
        		};
			$rootScope.objectClass = '';
		}
		if(div == 'place') {
                        $rootScope.placeClass = 'active';
                } else {
                        $rootScope.placeClass = '';
                }
		if(div == 'type') {
                        $rootScope.typeClass = 'active';
                } else {
                        $rootScope.typeClass = '';
                }
		if(div == 'subtype') {
                        $rootScope.subtypeClass = 'active';
                } else {
                        $rootScope.subtypeClass = '';
                }
		if(div == 'brand') {
                        $rootScope.brandClass = 'active';
                } else {
                        $rootScope.brandClass = '';
                }
	};
});

module.controller('AddObjectCtrl', function($rootScope, $scope, $http, $timeout, $document, Upload) {
	$scope.selectedPlace = null;
	$rootScope.places = [];

	$http.get('api/locais').success(function (result) {
		$rootScope.places = result;
	});

	$scope.selectedType = null;
	$rootScope.types = [];

	$http.get('api/tipos').success(function (result) {
                $rootScope.types = result;
        });

	$scope.selectedSubtype = null;
	$rootScope.subtypes = [];

	$scope.updateSubtype = function() {
		$http.get('api/tipos/'+$scope.selectedType).success(function (result) {
			$rootScope.subtypes = result;
		});
	};

	$scope.selectedBrand = null;
	$rootScope.brands = [];

	$http.get('api/marcas').success(function (result) {
		$rootScope.brands = result;
	});

	$scope.resetForm = function() {
		$scope.selectedPlace = null;
		$scope.selectedType = null;
		$scope.selectedSubtype = null;
		$rootScope.subtypes = [];
		$scope.selectedBrand = null;
		$scope.extra = {};
	};

	$scope.fileSelected = function(files, type) {
                if(files && files.length) {
                        $scope[type] = files[0];
                        console.log($scope[type]);
                }
        };

	$scope.recordObject = function() {
		$http.post('api/objecto', {
			'LOC' : parseInt($scope.selectedPlace),
			'TIP' : parseInt($scope.selectedType),
			'STP' : parseInt($scope.selectedSubtype),
			'MAR' : parseInt($scope.selectedBrand),
			'INF' : $scope.extra
		}).success(function (result) {
			var success = true;

			var uploadFunc = function(path, type, id) {
                                Upload.upload({
                                        url  : '/upload/' + path + '/' + id,
                                        data : { file : $scope[type] }
                                }).then(function(resp) {
                        		return true;
			        }, function(resp) {
					return false;
                                });
                                $scope[type] = null;
                        };

                        if($scope.Picture) {
                                success = sucess && uploadFunc('imagem', 'Picture', result);
                        }
                        if($scope.Invoice) {
                                success = success && uploadFunc('fatura', 'Invoice', result);
                        }
			if(success) {
				$rootScope.messages.push({
                                	'text' : 'Object added with success',
                                	'type' : 'alert-success',
					'id'   : $rootScope.messageID++
                        	});
			} else {
				$rootScope.messages.push({
                                        'text' : 'Object added with success but there were errors uploading the files',
                                        'type' : 'alert-warning',
                                        'id'   : $rootScope.messageID++
                                });
			}
			$document.scrollTopAnimated(0, 500);
			$scope.resetForm();
		});
	};
});

module.controller('AddPlaceCtrl', function($rootScope, $scope, $http, $document) {
	$scope.resetForm = function() {
		$scope.newPlace = '';
	};

	$scope.recordPlace = function() {
		$http.post('/api/local', {
			'LOC' : $scope.newPlace
		}).success(function (result) {
			var nP = {
				'ID'   : parseInt(result),
				'Nome' : $scope.newPlace
			};
                        $rootScope.places.push(nP);
			$rootScope.messages.push({
                                'text' : 'Place added with success',
                                'type' : 'alert-success',
				'id'   : $rootScope.messageID++
                        });
			$document.scrollTopAnimated(0, 500);
			$scope.resetForm();
		});
	};
});

module.controller('AddTypeCtrl', function($rootScope, $scope, $http, $document) {
	$scope.resetForm = function() {
		$scope.newType = '';
	};

	$scope.recordType = function() {
                $http.post('/api/tipo', {
                        'TIP' : $scope.newType
                }).success(function (result) {
			var nT = {
				'ID'   : parseInt(result),
				'Nome' : $scope.newType
			};
                        $rootScope.types.push(nT);
			$rootScope.messages.push({
                                'text' : 'Type added with success',
                                'type' : 'alert-success',
				'id'   : $rootScope.messageID++
                        });
			$document.scrollTopAnimated(0, 500);
			$scope.resetForm();
                });
        };
});

module.controller('AddSubtypeCtrl', function($rootScope, $scope, $http, $document) {
	$scope.selectedType = null;

	$scope.resetForm = function() {
		$scope.selectedType = null;
		$scope.newSubtype = '';
	};

	$scope.recordSubtype = function() {
                $http.post('/api/tipo/'+$scope.selectedType, {
                        'STP' : $scope.newSubtype
                }).success(function (result) {
			$rootScope.messages.push({
                                'text' : 'Subtype added with success',
                                'type' : 'alert-success',
				'id'   : $rootScope.messageID++
                        });
			$document.scrollTopAnimated(0, 500);
			$scope.resetForm();
                });
        };
});

module.controller('AddBrandCtrl', function($rootScope, $scope, $http, $document) {
	$scope.resetForm = function() {
		$scope.newBrand = '';
	};

	$scope.recordBrand = function() {
                $http.post('/api/marca', {
                        'MAR' : $scope.newBrand
                }).success(function (result) {
			var nB = {
				'ID'   : parseInt(result),
				'Nome' : $scope.newBrand
			};
			$rootScope.brands.push(nB);
			$rootScope.messages.push({
				'text' : 'Brand added with success',
				'type' : 'alert-success',
				'id'   : $rootScope.messageID++
			});
			$document.scrollTopAnimated(0, 500);
			$scope.resetForm();
                });
        };
});

module.controller('MessageCtrl', function($rootScope, $scope) {
	$rootScope.messages = [];
	$rootScope.messageID = 0;

	$scope.closeMessage = function(messageID) {
		var message = null;

		$rootScope.messages.forEach(function (item) {
			if(item.id == messageID) {
				message = item;
			}
		});

		var index = $rootScope.messages.indexOf(message);

		if(index > -1) {
			$rootScope.messages.splice(index, 1);
		}
	};
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Class Hierarchy</title>
<meta name="date" content="2012-05-08">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

org.eclipse.wb.swt

Class Hierarchy

java.lang.Object

BrowsePath

Hooks

LoadFile

Main (implements org.eclipse.swt.events.SelectionListener)

ReportObject

SaveObject

StopWatch

org.eclipse.wb.swt.SWTResourceManager

TableListener

TaskObject

TextListener

Tools

WriteFile

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
namespace DataSpec::DNAMP3 {
using PATH = DNAPATH::PATH<PAKBridge>;
} // namespace DataSpec::DNAMP3


text:
import { Component, OnInit } from '@angular/core';
// https://github.com/PillowPillow/ng2-webstorage
import {LocalStorageService} from 'ngx-webstorage';
import * as _ from 'lodash';
declare var DltdojoCertLib: any;
// https://github.com/bitpay/bitcore-lib
const bitcorelib = DltdojoCertLib.bitcorelib;
const PrivateKey = bitcorelib.PrivateKey;
// https://github.com/ConsenSys/eth-lightwallet
const lightwallet = DltdojoCertLib.lightwallet;

@Component({
  selector: 'app-bitcore',
  templateUrl: './bitcore.component.html',
  styleUrls: ['./bitcore.component.css']
})
export class BitcoreComponent implements OnInit {

  address = '0x0006';
  raddress = '0x0006';
  key = '0x0002';
  revokeKey = '0x0002';
  ran = 10;
  seed= '';
  certificateAdminJson = {};
  localSeed = '';
  constructor(private storage:LocalStorageService) { }

  ngOnInit() {
    var pkey = new PrivateKey();
    var rkey = new PrivateKey();
    this.address = pkey.toAddress().toString();
    this.raddress = rkey.toAddress().toString();
    this.key = pkey.toWIF();
    this.revokeKey = rkey.toWIF();
    this.ran = _.random(12, 86);
    this.seed = lightwallet.keystore.generateRandomSeed();
    this.certificateAdminJson = {seed:this.seed, issueKey: this.key, issueAddress:this.address, revokeAddress: this.raddress,revokeKey: this.revokeKey}
    this.localSeed = this.storage.retrieve('seed')
    this.storage.store('seed', this.seed);
  }

  ckDownload(event) {
    this.download("certificate-admin.json", JSON.stringify(this.certificateAdminJson, null, ' '), "application/json")
  }

  download(fileName: string, content: string, mimeType: string) {
    // for Excel, we need \ufeff at the start
    // http://stackoverflow.com/questions/17879198/adding-utf-8-bom-to-string-blob
    var blobObject = new Blob(["\ufeff", content], {
      type: mimeType
    });
    // Internet Explorer
    if (window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blobObject, fileName);
    } else {
      // Chrome
      var downloadLink = document.createElement("a");
      downloadLink.href = (<any>window).URL.createObjectURL(blobObject);
      (<any>downloadLink).download = fileName;

      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    }
  }
}


text:
package com.ctrip.framework.cs.threading;

import com.ctrip.framework.cs.Permission;
import com.ctrip.framework.cs.ViFunctionHandler;
import org.slf4j.Logger;

import java.util.Map;

/**
 * Created by jiang.j on 2016/6/13.
 */
public class ThreadingHandler implements ViFunctionHandler {
    private  String startPath ="/threading/";
    @Override
    public Object execute(String path, String user, int permission, Logger logger, Map<String, Object> params) throws Exception{
        Object rtn=null;
        int maxDepth = 3;
        String key="maxdepth";

        if(params!=null && params.containsKey(key)){
            try {
                maxDepth = Integer.parseInt( String.valueOf(params.get(key)));
            }catch (Throwable e){
                logger.warn("cast maxDepth failed, maxDepth "+params.get(key)+" is not number.",e);
            }
        }
        if(path.equals(startPath+"all")){
            rtn = ThreadingManager.getAllThreadInfo();
        }
        else if(path.equals(startPath+"stats")){
            rtn = ThreadingManager.getThreadStats();
        }
        else if(path.equals(startPath+"dump")){
            String key1 = "onlydeadlock";
            Boolean onlyDeadLock =false;
            if(params!=null && params.containsKey(key1)){
                try {
                    onlyDeadLock = Boolean.parseBoolean( String.valueOf(params.get(key1)));
                }catch (Throwable e){
                    logger.warn("cast maxDepth failed, onlydeadlock "+params.get(key1)+" is not bool.",e);
                }
            }
            rtn = ThreadingManager.dump(maxDepth,onlyDeadLock);
        }
        else if(path.startsWith(startPath+"detail/")){
            rtn = ThreadingManager.getThreadInfo(Long.parseLong(path.substring(18)),maxDepth);
        }
        else{
            rtn = path + " not found";
        }
        return rtn;
    }

    @Override
    public String getStartPath() {
        return startPath;
    }

    @Override
    public Permission getPermission(String user) {
        return Permission.ALL;
    }
}


text:
/*
# harness
This file can be used to very quickly set up a mocha-based browser testing
environment, and is compatible with `grunt-mocha`. You'll just need to set the path
for three files in `requirejs`:

```
paths: {
  'thehelp-test': '<your path>',
  'thehelp-test-coverage': '<required for code coverage>',
  'grunt-mocha-bridge': '<required if using with grunt-mocha'
}
```
*/

define(['thehelp-test'], function(test) {
  /*jshint maxcomplexity: 9 */

  'use strict';

  // Because PhantomJS doesn't support function.bind we polyfill it
  // <https://groups.google.com/forum/#!msg/phantomjs/r0hPOmnCUpc/uxusqsl2LNoJ>
  // <https://github.com/ariya/phantomjs/issues/10522>
  Function.prototype.bind = Function.prototype.bind || function(target) {
    var _this = this;
    return function() {
      return _this.apply(target, arguments);
    };
  };

  // `setupMocha` prepares `mocha` for tests to be loaded. It must be run before
  // we run test-defining code. If we don't, `describe` and `it` will not yet be defined.
  test.mocha.setup('bdd');

  // Prepare and verify settings, put defaults in place.
  var thehelp = window.thehelp || {};
  var settings = thehelp.test || {};
  if (typeof settings.coverage === 'undefined') {
    settings.coverage = true;
  }
  if (typeof settings.blanket === 'undefined') {
    settings.blanket = {
      filter: '/src/',
      antifilter: '["/bower_components/", "node_modules", "/test/","/lib/"]'
    };
  }

  if (typeof settings.files === 'undefined') {
    throw new Error('Specify test files with an array at window.thehelp.test.files');
  }
  if (typeof settings.mochaCss === 'undefined') {
    throw new Error(
      'Provide the path to the mocha.css file window.thehelp.test.mochaCss'
    );
  }

  // `loadTests` actually pulls in your test files, then installs `window.runTests()`,
  // which adds the mocha div to your page and runs the tests.
  var loadTests = function loadTests(settings, mocha) {
    require(settings.files, function() {
      window.runTests = function() {
        if (!document.getElementById('mocha')) {
          //Doing this without jquery to reduce dependencies :0)
          var body = document.getElementsByTagName('body')[0];
          var div = document.createElement('div');
          div.setAttribute('id', 'mocha');
          body.appendChild(div);

          var head = document.getElementsByTagName('head')[0];
          var link = document.createElement('link');
          link.setAttribute('rel', 'stylesheet');
          link.setAttribute('href', settings.mochaCss);
          head.appendChild(link);
        }

        mocha.run();
        return true;
      };

      if (window.PHANTOMJS) {
        require(['grunt-mocha-bridge'], function() {
          mocha.run();
        });
      }
      else if (!settings.waitToRun) {
        window.runTests();
      }
    });
  };

  // Sets up code coverage if configured. No code coverage under phantomjs since we're not
  // using a grunt plugin that understands code coverage.
  if (settings.coverage && !window.PHANTOMJS) {
    require(['thehelp-test-coverage'], function(blanket) {

      if (settings.blanket) {
        //Doing this without lodash to reduce dependencies :0)
        var keys = Object.keys(settings.blanket);

        for (var i = 0, max = keys.length; i < max; i += 1) {
          var key = keys[i];
          blanket.options(key, settings.blanket[key]);
        }
      }

      loadTests(settings, test.mocha);
    });
  }
  else {
    loadTests(settings, test.mocha);
  }

});


text:
package com.rrajath.transittracker.presenter;

public class NearbyPresenter {

}


text:
<template name="Header">

botaniary

      Profile
      Botanodex
      Plant Locations
      {{#if currentUser}}
        Add Stuff
        List Stuff
      {{/if}}
      {{> loginButtons }}

</template>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ProxyDiagnostics (Apache Ant API)</title>
<meta name="date" content="2012-05-22">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.tools.ant.util.java15

Class ProxyDiagnostics

java.lang.Object

org.apache.tools.ant.util.java15.ProxyDiagnostics

public class ProxyDiagnostics
extends java.lang.Object

This class exists to create a string that tells diagnostics about the current
 state of proxy diagnostics.
 It does this in its toString operator.
 Java1.5+ is needed to compile this class; its interface is classic typeless
 Java.

Since:

Ant 1.7

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
DEFAULT_DESTINATION

"http://ant.apache.org/"

Constructor Summary

Constructors

Constructor and Description

ProxyDiagnostics()

create a proxy diagnostics tool bound to
 DEFAULT_DESTINATION

ProxyDiagnostics(java.lang.String destination)

create a diagnostics binding for a specific URI

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
toString()

Get the diagnostics for proxy information.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

DEFAULT_DESTINATION

public static final java.lang.String DEFAULT_DESTINATION

"http://ant.apache.org/"

See Also:

Constant Field Values

Constructor Detail

ProxyDiagnostics

public ProxyDiagnostics(java.lang.String destination)

create a diagnostics binding for a specific URI

Parameters:

destination - dest to bind to

Throws:

BuildException - if the URI is malformed.

ProxyDiagnostics

public ProxyDiagnostics()

create a proxy diagnostics tool bound to
 DEFAULT_DESTINATION

Method Detail

toString

public java.lang.String toString()

Get the diagnostics for proxy information.

Overrides:

toString in class java.lang.Object

Returns:

the information.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
This is how you fix a bug or add a feature:

* fork us on GitHub.
* Checkout your fork.
* Hack hack hack, test test test, commit commit commit, test again.
* Push to your fork.
* Open a pull request.


text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <sys/types.h>
#include <sys/wait.h>

#include <mutex>
#include <thread>
#include <chrono>

#include <boost/test/unit_test.hpp>

#include "mldb/arch/exception.h"
#include "mldb/arch/wait_on_address.h"
#include "mldb/base/exc_assert.h"
#include "mldb/utils/string_functions.h"
#include "mldb/utils/testing/watchdog.h"
#include "mldb/io/message_loop.h"
#include "mldb/utils/runner.h"
#include "mldb/utils/sink.h"
#include "mldb/types/date.h"

#include <iostream>

#include "signals.h"

using namespace std;
using namespace MLDB;

// #define BOOST_CHECK_EQUAL(x,y)  { ExcCheckEqual((x), (y), ""); }

struct _Init {
    _Init() {
        signal(SIGPIPE, SIG_IGN);
    }
} myInit;

struct HelperCommands : vector<string>
{
    HelperCommands()
        : vector<string>(),
          active_(0)
    {}

    void reset() { active_ = 0; }

    string nextCommand()
    {
        if (active_ < size()) {
            int active = active_;
            active_++;
            return at(active);
        }
        else {
            return "";
        }
    }

    void sendOutput(bool isStdOut, const string & data)
    {
        char cmdBuffer[1024];
        int len = data.size();
        int totalLen = len + 3 + sizeof(int);
        sprintf(cmdBuffer, (isStdOut ? "out" : "err"));
        memcpy(cmdBuffer + 3, &len, sizeof(int));
        memcpy(cmdBuffer + 3 + sizeof(int), data.c_str(), len);
        push_back(string(cmdBuffer, totalLen));
    }

    void sendExit(int code)
    {
        char cmdBuffer[1024];
        int totalLen = 3 + sizeof(int);
        sprintf(cmdBuffer, "xit");
        memcpy(cmdBuffer + 3, &code, sizeof(int));
        push_back(string(cmdBuffer, totalLen));
    };

    void sendAbort()
    {
        push_back("abt");
    }

    int active_;
};

#if 1
/* stress test that runs 20 threads in parallel, where each thread:
- invoke "execute", with 10000 messages to stderr and stdout (each)
  received from the stdin sink
- compare those messages with a fixture
and
- the parent thread that outputs messages on stderr and on stdout until all
  threads are done
- wait for the termination of all threads
- ensures that all child process have properly exited
*/
BOOST_AUTO_TEST_CASE( test_stress_runner )
{
    MLDB::Watchdog wd(120);
    vector<thread> threads;
    int nThreads(20);
    vector<pid_t> childPids(nThreads);
    int msgsToSend(10000);
    atomic<int> nRunning(0);

    std::atomic<int> activeThreads(nThreads);

    auto onTerminate = [&] (const RunResult &) {
    };

    auto runThread = [&] (int threadNum) {
        /* preparation */
        HelperCommands commands;
        string receivedStdOut, expectedStdOut;
        string receivedStdErr, expectedStdErr;
        size_t stdInBytes(0);

        receivedStdOut.reserve(msgsToSend * 80);
        expectedStdOut.reserve(msgsToSend * 80);
        receivedStdErr.reserve(msgsToSend * 80);
        expectedStdErr.reserve(msgsToSend * 80);

        expectedStdOut = "helper: ready\n";
        for (int i = 0; i < msgsToSend; i++) {
            string stdOutData = (to_string(threadNum)
                                 + ":" + to_string(i)
                                 + ": this is a message to stdout\n\t"
                                 + "and a tabbed line");
            commands.sendOutput(true, stdOutData);
            expectedStdOut += stdOutData + "\n";
            string stdErrData = (to_string(threadNum)
                                 + ":" + to_string(i)
                                 + ": this is a message to stderr\n\t"
                                 + "and a tabbed line");
            commands.sendOutput(false, stdErrData);
            expectedStdErr += stdErrData + "\n";
        }
        commands.sendExit(0);

        expectedStdOut += "helper: exit with code 0\n";

        /* execution */
        MessageLoop loop;
        Runner runner;

        loop.addSource("runner", runner);
        loop.start();

        auto onStdOut = [&] (string && message) {
            receivedStdOut += message;
        };
        auto stdOutSink = make_shared<CallbackInputSink>(onStdOut);
        auto onStdErr = [&] (string && message) {
            receivedStdErr += message;
        };
        auto stdErrSink = make_shared<CallbackInputSink>(onStdErr);

        auto & stdInSink = runner.getStdInSink();
        runner.run({"build/x86_64/bin/runner_test_helper"},
                   onTerminate, stdOutSink, stdErrSink);

        for (const string & command: commands) {
            while (!stdInSink.write(string(command))) {
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
            stdInBytes += command.size();
        }

        runner.waitStart();
        pid_t pid = runner.childPid();
        nRunning++;
        // cerr << "running with pid: " + to_string(pid) + "\n";

        childPids[threadNum] = pid;

        // cerr << "sleeping\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));

        /* before closing stdinsink, wait until all bytes are correctly
           sent */
        {
            AsyncFdOutputSink & sinkPtr = (AsyncFdOutputSink &) stdInSink;
            while (sinkPtr.bytesSent() != stdInBytes) {
                std::this_thread::sleep_for(std::chrono::milliseconds(200));
            }
            if (sinkPtr.queueEnabled()) {
                stdInSink.requestClose();
            }
        }

        // cerr << "waiting termination...\n";
        runner.waitTermination();
        // cerr << "terminated\n";

        loop.shutdown();

        BOOST_CHECK_EQUAL(receivedStdOut, expectedStdOut);
        BOOST_CHECK_EQUAL(receivedStdErr, expectedStdErr);

        --activeThreads;
        // cerr << "activeThreads now: " + to_string(activeThreads) + "\n";
        if (activeThreads == 0) {
            MLDB::wake_by_address(activeThreads);
        }
        cerr << "thread shutting down\n";
    };

    /* initialize childPids with a non-random bad value, so that we can know
     * later whether the pids were correctly initialized from the workers */
    for (int i = 0; i < nThreads; i++) {
        childPids[i] = 0xdeadface;
    }

    std::atomic_thread_fence(std::memory_order_seq_cst);

    for (int i = 0; i < nThreads; i++) {
        threads.emplace_back(runThread, i);
    }

    std::atomic_thread_fence(std::memory_order_seq_cst);

    /* attempting to interfere with stdout/stderr as long as all thread have
     * not redirected their output channels yet (are not running) */
    while (nRunning < nThreads) {
        cout << "performing interference on stdout\n";
        cerr << "performing interference on stderr\n";
        // int n = activeThreads;
        // MLDB::wait_on_address(activeThreads, n);
    }

    for (thread & current: threads) {
        current.join();
    }

    /* ensure children have all exited... */
    BOOST_CHECK_EQUAL(childPids.size(), threads.size());
    for (const int & pid: childPids) {
        if (pid != 0xdeadface) {
            /* the child may already be done when childPid was invoked */
            if (pid > 0) {
                waitpid(pid, NULL, WNOHANG);
                int errno_ = errno;
                BOOST_CHECK_EQUAL(errno_, ECHILD);
            }
        }
        else {
            throw MLDB::Exception("pid was never set");
        }
    }
}

#endif


text:
/**
 * Currently in beta stage. Changes can and will be made to the core mechanic
 * making this not backwards compatible.
 *
 * Github: https://github.com/Need4Speed402/tessellator
 */

Tessellator.Model.prototype.setUniform = function (key, value){
    return this.add(new Tessellator.Model.UniformSetter(key, value));
};

Tessellator.Model.UniformSetter = function (key, value){
    this.key = key;
    this.value = value;
};

Tessellator.Model.UniformSetter.prototype.init = function (init){
    init.flush();
};

Tessellator.Model.UniformSetter.prototype.apply = function (matrix){
    matrix.set(this.key, this.value);
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  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. See accompanying LICENSE file.
-->
<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.apache.hadoop</groupId>
    <artifactId>hadoop-project</artifactId>
    <version>2.4.1</version>
    <relativePath>../../../../../hadoop-project</relativePath>
  </parent>

  <groupId>org.apache.hadoop.contrib</groupId>
  <artifactId>hadoop-hdfs-bkjournal</artifactId>
  <version>2.4.1</version>
  <description>Apache Hadoop HDFS BookKeeper Journal</description>
  <name>Apache Hadoop HDFS BookKeeper Journal</name>
  <packaging>jar</packaging>

  <properties>
    <hadoop.component>hdfs</hadoop.component>
    <hadoop.common.build.dir>${basedir}/../../../../../hadoop-common-project/hadoop-common/target</hadoop.common.build.dir>
  </properties>

  <dependencyManagement>
    <dependencies>
      <!-- This is a really old version of netty, that gets privatized
           via shading and hence it is not managed via a parent pom -->
      <dependency>
        <groupId>org.jboss.netty</groupId>
        <artifactId>netty</artifactId>
        <version>3.2.4.Final</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.jboss.netty</groupId>
      <artifactId>netty</artifactId>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-common</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-hdfs</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-hdfs</artifactId>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-common</artifactId>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.bookkeeper</groupId>
      <artifactId>bookkeeper-server</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-maven-plugins</artifactId>
        <executions>
          <execution>
            <id>compile-protoc</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>protoc</goal>
            </goals>
            <configuration>
              <protocVersion>${protobuf.version}</protocVersion>
              <protocCommand>${protoc.path}</protocCommand>
              <imports>
                <param>${basedir}/../../../../../hadoop-common-project/hadoop-common/src/main/proto</param>
                <param>${basedir}/../../../../../hadoop-hdfs-project/hadoop-hdfs/src/main/proto</param>
                <param>${basedir}/src/main/proto</param>
              </imports>
              <source>
                <directory>${basedir}/src/main/proto</directory>
                <includes>
                  <include>bkjournal.proto</include>
                </includes>
              </source>
              <output>${project.build.directory}/generated-sources/java</output>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <configuration>
          <excludeFilterFile>${basedir}/dev-support/findbugsExcludeFile.xml</excludeFilterFile>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>dev-support/findbugsExcludeFile.xml</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <profiles>
    <profile>
      <id>dist</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>1.5</version>
            <executions>
              <execution>
                <phase>package</phase>
                <goals>
                  <goal>shade</goal>
                </goals>
                <configuration>
                  <createDependencyReducedPom>false</createDependencyReducedPom>
                  <artifactSet>
                    <includes>
                      <include>org.apache.bookkeeper:bookkeeper-server</include>
                      <include>org.apache.zookeeper:zookeeper</include>
                      <include>org.jboss.netty:netty</include>
                    </includes>
                  </artifactSet>
                <relocations>
                  <relocation>
                    <pattern>org.apache.bookkeeper</pattern>
                    <shadedPattern>hidden.bkjournal.org.apache.bookkeeper</shadedPattern>
                  </relocation>
                  <relocation>
                    <pattern>org.apache.zookeeper</pattern>
                    <shadedPattern>hidden.bkjournal.org.apache.zookeeper</shadedPattern>
                  </relocation>
                  <relocation>
                    <pattern>org.jboss.netty</pattern>
                    <shadedPattern>hidden.bkjournal.org.jboss.netty</shadedPattern>
                  </relocation>
                </relocations>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


text:
// Copyright 2022 Google LLC
//
// 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
//
//     https://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.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

function main(name, documentSchema) {
  // [START contentwarehouse_v1_generated_DocumentSchemaService_UpdateDocumentSchema_async]
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. The name of the document schema to update.
   *  Format:
   *  projects/{project_number}/locations/{location}/documentSchemas/{document_schema_id}.
   */
  // const name = 'abc123'
  /**
   *  Required. The document schema to update with.
   */
  // const documentSchema = {}

  // Imports the Contentwarehouse library
  const {DocumentSchemaServiceClient} = require('@google-cloud/contentwarehouse').v1;

  // Instantiates a client
  const contentwarehouseClient = new DocumentSchemaServiceClient();

  async function callUpdateDocumentSchema() {
    // Construct request
    const request = {
      name,
      documentSchema,
    };

    // Run request
    const response = await contentwarehouseClient.updateDocumentSchema(request);
    console.log(response);
  }

  callUpdateDocumentSchema();
  // [END contentwarehouse_v1_generated_DocumentSchemaService_UpdateDocumentSchema_async]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
const path = require('path');
const spawn = require('../utils/spawn');

module.exports = program => program.command('build [options]')
  .description('Build the application.')
  .option('-p, --production', 'Perform the build in production mode.')
  .action((env, opts) => {
    const webpackPath = path.resolve(process.cwd(), 'node_modules/.bin/webpack');
    const webpackConfigPath = path.resolve(process.cwd(), 'webpack.config.js');

    spawn(webpackPath, [
      opts.production ? '--env=prod' : null,
      '--config',
      webpackConfigPath
    ], {
      NODE_ENV: opts.production ? 'production' : 'development'
    }).catch(code => {
      console.log(`Could not build Aurora application (error code: ${code}).`);
    });
  });


text:
#2. Exercise 2

## Let's do this.
Your server.js currently contains more stuff than it should. Let's move anything related to the burgers into its own router.

1. Create a folder called `routes` to hold all of our routes.
1. Inside `routes`, touch a file called `burgers.js`
1. Again, require express and create a `Router()`
1. Move all of the burger routes into this file (_remember to use module.exports!_).
1. From server.js, `app.use` this new file, referencing it as `/burgers`

Your application should now run exactly as it did in step #1. If it doesn't, **stop here and fix it**.

As of now, we've only tested our routes to see if they function properly. Now, let's make it do something. _Your server should NOT be serving any HTML at this point, only json_

##Get some data
Currently, your server is only able to read `GET` requests. Let's make it able to read other HTTP methods with body-parser and method-override. Body-parser allows us to read the body of `POST` requests, and method-override allows us to simulate the remainder of the methods not supported in HTML (e.g. `PUT`,`DELETE`)

1. `npm install body-parser method-override --save`
1. Inside `server.js`, require these two packages.
1. Add the following block to activate them each:
```javascript
// parse incoming forms
/* we'll be reading the form body,
but not accepting files, or anything more than text*/
app.use( bodyParser.urlencoded({ extended: false }));
/* we'll convert everything we receive into json,
for our convenience */
app.use( bodyParser.json());

// override with POST having ?_method=XXXX
/* e.g. If we need to make a PUT,
we'll POST to a url appended with ?_method=put */
app.use(methodOverride('_method'))
```

## Use This Data
Inside `burgers.js`, initialize a new array called `burgerData`. This will be our (semi-)persistent storage while we're developing. _**Note**: this data will be destroyed each time the server is restarted— we'll fix that in exercise 4._

###Create
1. Update your routes such that a `POST` to `/burgers` takes some data and pushes it into `burgerData`
	1. Use Postman's POST:body feature to create a data body to post to the server.
1. use `res.redirect(_some route_)` to send the user to the newly created burger (`/burgers/{newid}`)

###Read
1. `GET`: `/burgers` should show the entire array of burgers.
1. `GET`: `/burgers/:id` should show a single burger at that position.
	1. Trying to access a burger's ID that doesn't exist should return a 404 and nothing else.

###Update
1. `PUT` should ONLY be allowed on a single burgerID. This should update the burger at that position, or throw a 404 if the number is invalid.
	1. Redirect to `/burgers/:id` when done.

###Delete
1. `DELETE` should delete a single burger when issued on `/burgers/:id`. If a burger isn't found to delete, fail silently
	1. Redirect to `/burgers` when done.


text:
package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/format"
	"go/parser"
	"go/token"
	"io/ioutil"
	"os"
	"sort"
	"text/template"

	"github.com/ikkerens/disgo/generate"
	"github.com/slf4go/logger"
)

type internalField struct {
	Name    string
	TypeStr string
}

type internalType struct {
	Name      string
	Exported  string
	StateType bool
	Fields    []internalField

	RegisteredFields      []string
	RegisteredArrayFields []string
}

func main() {
	file, err := parser.ParseFile(token.NewFileSet(), "model.go", nil, 0)
	if err != nil {
		logger.ErrorE(err)
		return
	}

	var types = make([]internalType, 0)
	for name, object := range file.Scope.Objects {
		if object.Kind == ast.Typ {
			typ := object.Decl.(*ast.TypeSpec)

			if len(typ.Name.Name) < 8 || typ.Name.Name[:8] != "internal" {
				continue
			}

			structDef, ok := typ.Type.(*ast.StructType)

			if ok {
				typeDef := internalType{name, name[8:], generate.IsRegisteredType(name[8:]), make([]internalField, 0), make([]string, 0), make([]string, 0)}
				logger.Infof("Creating API struct for %s with name %s.", typeDef.Name, typeDef.Exported)
				for _, field := range structDef.Fields.List {
					typeStr, err := determineType(field.Type)
					if err != nil {
						logger.ErrorE(err)
						continue
					}

					iField := internalField{field.Names[0].Name, typeStr}
					typeDef.Fields = append(typeDef.Fields, iField)
					logger.Infof("Adding func %s() with return type %s to %s.", iField.Name, iField.TypeStr, typeDef.Exported)

					switch f := field.Type.(type) {
					case *ast.StarExpr:
						if name := f.X.(*ast.Ident).Name; generate.IsRegisteredType(name) {
							typeDef.RegisteredFields = append(typeDef.RegisteredFields, field.Names[0].Name)
						}
					case *ast.ArrayType:
						switch a := f.Elt.(type) {
						case *ast.StarExpr:
							if name := a.X.(*ast.Ident).Name; generate.IsRegisteredType(name) {
								typeDef.RegisteredArrayFields = append(typeDef.RegisteredArrayFields, field.Names[0].Name)
							}
						case *ast.SelectorExpr:
							if name := a.X.(*ast.Ident).Name; generate.IsRegisteredType(name) {
								typeDef.RegisteredArrayFields = append(typeDef.RegisteredArrayFields, field.Names[0].Name)
							}
						}
					}
				}

				types = append(types, typeDef)
			}
		}
	}

	sort.SliceStable(types, func(i, j int) bool {
		return types[i].Name < types[j].Name
	})

	logger.Infof("Generating GO file")
	var tpl = template.Must(template.New("apimodel").Parse(`package disgo

		// Warning: This file has been automatically generated by generate/apimodel/main.go
		// Do NOT make changes here, instead adapt model.go and run go generate

		import (
			"encoding/json"
			"sync"
		)

		{{range .}}
			// {{.Exported}} is based on the Discord object with the same name.
			// Any fields can be obtained by calling the respective getters.
			type {{.Exported}} struct {
				session *Session
				internal *{{.Name}} {{if .StateType}}

				lock *sync.RWMutex {{end}}
			}

			// MarshalJSON is used to convert this object into its json representation for Discord
			func (s *{{.Exported}}) MarshalJSON() ([]byte, error) {
				return json.Marshal(s.internal)
			}

			// UnmarshalJSON is used to convert json discord objects back into their respective structs
			func (s *{{.Exported}}) UnmarshalJSON(b []byte) error { {{if .StateType}}
				id := IDObject{}
				if err := json.Unmarshal(b, &id); err != nil {
					return err
				}

				registered := objects.register{{.Exported}}(&id)
				registered.lock.Lock()
				defer registered.lock.Unlock()

				s.lock = registered.lock
				s.internal = registered.internal {{else}}
					s.internal = &{{.Name}}{} {{end}}
				return json.Unmarshal(b, &s.internal)
			}

			{{if .StateType}}
			func (s *{{.Exported}}) setSession(session *Session) {
				s.lock.Lock()
				defer s.lock.Unlock()

				s.session = session {{range .RegisteredFields}}
				if s.internal.{{.}} != nil {
					s.internal.{{.}}.session = session
				} {{end}} {{range .RegisteredArrayFields}}
				if s.internal.{{.}} != nil {
					for _, sub := range s.internal.{{.}} {
						sub.session = session
					}
				}{{end}}
			}{{end}}

			{{$p := .}}
			{{range .Fields}}
				// {{ .Name}} is used to export the {{.Name}} from this struct.
				func (s *{{$p.Exported}}) {{.Name}}() {{.TypeStr}} { {{if $p.StateType}}
					s.lock.RLock()
					defer s.lock.RUnlock()
					{{end}}
					return s.internal.{{.Name}}
				}
			{{end}}
		{{end}}
	`))

	var result []byte
	var buf bytes.Buffer
	err = tpl.Execute(&buf, types)

	if err == nil {
		var formatted []byte
		logger.Infof("Formatting GO file")
		formatted, err = format.Source(buf.Bytes())
		result = formatted
	}

	if err != nil {
		logger.ErrorE(err)
		os.Exit(1)
	}

	ioutil.WriteFile("model_generated.go", result, 0644)
}

func determineType(field ast.Expr) (typeStr string, err error) {
	switch v := field.(type) {
	case *ast.Ident:
		typeStr = v.Name
	case *ast.StarExpr:
		subType, err := determineType(v.X)
		if err != nil {
			return "", err
		}
		typeStr = "*" + subType
	case *ast.SelectorExpr:
		subType, err := determineType(v.X)
		if err != nil {
			return "", err
		}
		typeStr = subType + "." + v.Sel.Name
	case *ast.ArrayType:
		subType, err := determineType(v.Elt)
		if err != nil {
			return "", err
		}
		typeStr = "[]" + subType
	default:
		err = fmt.Errorf("Unknown field type (%T): %+v", v, v)
	}

	return
}


text:
<?php
/**
 * Table Definition for ADMIN_PACKAGE_PERMISSION
 */
require_once 'DB/DataObject.php';

class DataObject_ADMIN_PACKAGE_PERMISSION extends DB_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'ADMIN_PACKAGE_PERMISSION';    // table name
    public $_database = 'extremeframework-git';    // database name (used with database_{*} config)
    public $ID;                              // int(4)  primary_key not_null
    public $NAME;                            // varchar(128)
    public $REFID;                           // varchar(16)
    public $ID_ADMIN_PACKAGE;                // varchar(32)  unique_key
    public $ID_PERMISSION_SET;               // int(4)  unique_key
    public $GUID;                            // int(4)
    public $JSON;                            // text
    public $WFID;                            // varchar(24)
    public $UDID;                            // int(4)
    public $UUID;                            // char(36)

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE
}