text:
package skylinequeries.demo;

import skylinequeries.algs.bbs.BBS;
import skylinequeries.tools.Drawer;
import skylinequeries.tools.Utilities;
import skylinequeries.rtree.Entry;
import skylinequeries.rtree.RTree;
import skylinequeries.rtree.geometry.Point;

import javax.swing.*;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Vinh Nguyen
 */
public class BBSWorker extends SwingWorker<List<Entry<Object, Point>>, Entry<Object, Point>> {
    private RTree<Object, Point> rTree = RTree.star().create();
    private List<Entry<Object, Point>> skylineEntries;
    private final String dataset;
    private List<Point> points, skylinePoints;
    private final JTextArea viewer, logger;
    private long executionTime;

    public BBSWorker(String dataset, JTextArea viewer, JTextArea logger) {
        this.dataset = dataset;
        this.viewer = viewer;
        this.logger = logger;
    }

    @Override
    protected List<Entry<Object, Point>> doInBackground() throws Exception {
        rTree = Utilities.constructRTree(rTree, dataset);
        final BBS bbs = new BBS(rTree);

        Instant before = Instant.now();
        skylineEntries = bbs.execute();
        Instant after = Instant.now();
        executionTime = Duration.between(before, after).toMillis();

        points = Utilities.constructRTree(dataset);
        skylinePoints = Utilities.entriesToPoints(skylineEntries);

        for (Entry<Object, Point> entry : skylineEntries) {
            publish(entry);
        }

        return skylineEntries;
    }

    @Override
    protected void process(List<Entry<Object, Point>> foundEntries) {
        int count = 1;
        for (Entry<Object, Point> entry : foundEntries) {
            viewer.append(String.format("%3d - %s", count, entry.geometry().toString()) + "\n\n");
            count++;
        }
    }

    @Override
    protected void done() {
        logger.append(Utilities.console(skylineEntries, points.size(), executionTime, BBS.NODE_ACCESSES));
        ExecutorService executor = Executors.newFixedThreadPool(1);
        executor.submit(new Drawer(points, skylinePoints, 0.0, 0.0, 10000.0, 10000.0));
        executor.shutdown();
        System.gc();
    }
}


text:
/*using System;
using System.Collections.Generic;

namespace TTree
{
	/// <summary>
	/// Implemented by TTreeNodes and the TTreeRoot
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public interface ITTreeNode<T> : ICollection<T>
		where T : IComparable
	{
		/// <summary>
		/// Adds the specified item.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <returns>True if the item was added or false if it already existed and was not </returns>
		bool AddItem( T item );

		/// <summary>
		/// Search for an item using a custom comparison function
		/// </summary>
		/// <typeparam name="TSearch">The type of the search.</typeparam>
		/// <param name="item">The item.</param>
		/// <param name="comparer">The comparer.</param>
		/// <returns></returns>
		T Search<TSearch>( TSearch item, Func<TSearch, T, int> comparer );

		/// <summary>
		/// Search for an item using a custom comparison function
		/// </summary>
		/// <typeparam name="TSearch">The type of the search.</typeparam>
		/// <param name="item">The item.</param>
		/// <param name="comparer">The comparer.</param>
		/// <returns></returns>
		SearchResult<T> SearchFor<TSearch>( TSearch item, Func<TSearch, T, int> comparer );

		/// <summary>
		/// Searches for the specified item.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <returns></returns>
		SearchResult<T> SearchFor( T item );

		/// <summary>
		/// Searches for the specified item.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <returns></returns>
		T Search( T item );

		/// <summary>
		/// Copies the items from the current node only
		/// </summary>
		/// <param name="destinationArray">The destination array.</param>
		/// <param name="index">The index.</param>
		void CopyItems( T[] destinationArray, int index );

		/// <summary>
		/// Gets number of items in this node
		/// </summary>
		/// <value>The item count.</value>
		int ItemCount { get; }

		string ToDot( Func<T, string> toString );
		string ToDot();

		int Height { get; }
		bool IsLeaf { get; }
		bool IsHalfLeaf { get; }
		bool IsInternal { get; }
		int MaxItems { get; }
		TTreeRoot<T> Root { get; }
		TTreeNode<T> Left { get; }
		TTreeNode<T> Right { get; }
		TTreeNode<T> Parent { get;  }
		int BalanceFactor { get; }
	}
}
*/

redpajama_set_name: RedPajamaGithub


text:
"""System information utilities."""
from __future__ import absolute_import, unicode_literals
import os
from math import ceil
from kombu.utils.objects import cached_property

__all__ = ['load_average', 'df']

if hasattr(os, 'getloadavg'):

    def _load_average():
        return tuple(ceil(l * 1e2) / 1e2 for l in os.getloadavg())

else:  # pragma: no cover
    # Windows doesn't have getloadavg
    def _load_average():  # noqa
        return (0.0, 0.0, 0.0)

def load_average():
    """Return system load average as a triple."""
    return _load_average()

class df(object):
    """Disk information."""

    def __init__(self, path):
        self.path = path

    @property
    def total_blocks(self):
        return self.stat.f_blocks * self.stat.f_frsize / 1024

    @property
    def available(self):
        return self.stat.f_bavail * self.stat.f_frsize / 1024

    @property
    def capacity(self):
        avail = self.stat.f_bavail
        used = self.stat.f_blocks - self.stat.f_bfree
        return int(ceil(used * 100.0 / (used + avail) + 0.5))

    @cached_property
    def stat(self):
        return os.statvfs(os.path.abspath(self.path))


text:
/**
 * Run from the root of the vsts-tasks repo.
 * Usage: `node generate-third-party-notice.js <task name>`
 */

'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

let verboseLogging = false;

const log = {
    info(message) {
        if (verboseLogging) {
            console.log(`[INFO] ${message}`);
        }
    },
    warning(message) {
        console.log(`[WARNING] ${message}`);
    },
    error(message) {
        console.error(`[ERROR] ${message}`)
    }
};

/** Log `label: ${value}` and pass the value through. */
function trace(label, value) {
    log.info(`${label}: ${value}`);
    return value;
}

/**
 * Read `packagePath`'s package.json and deserialize it.
 * @param packagePath Absolute path to the NPM package
 * @returns Package manifest information parsed from the package's package.json
 */
function readPackageJson(packagePath) {
    log.info(`Reading the package.json for ${packagePath} ...`);
    const contents = fs.readFileSync(path.join(packagePath, 'package.json'), { encoding: 'utf-8' });
    return JSON.parse(contents);
}

/**
 * Get the name of the file containing the license for `packagePath`.
 * @param packagePath Absolute path to the NPM package
 * @returns Absolute path to the license file, or `null` if the license file can't be found
 */
function findLicense(packagePath) {
    log.info(`Finding the license for ${packagePath}`);
    const children = fs.readdirSync(packagePath);
    const licenseNames = [
        'LICENSE',
        'LICENSE.md',
        'LICENSE.txt'
    ].map(x => x.toLowerCase());

    const candidates = children.filter(x => licenseNames.includes(x.toLowerCase()));
    if (candidates.length === 0) {
        return null;
    } else {
        if (candidates.length > 1) {
            log.warning(`Found multiple license files for ${packagePath}: ${candidates.join(', ')}`);
        }
        return trace('Found license', path.join(packagePath, candidates[0]));
    }
}

/**
 * Scan the contents of the 'node_modules' directory for license information.
 * @param modulesRoot NPM package installation directory to scan
 * @returns Iterable of objects: `name` x `url` x `licenseText`
 */
function* collectLicenseInfo(modulesRoot) {
    const packagePaths = fs.readdirSync(modulesRoot).map(x => path.join(modulesRoot, x));
    for (const absolutePath of packagePaths) {
        log.info(`Collecting license information from ${absolutePath} ...`);

        const basename = path.basename(absolutePath);
        if (basename.startsWith('@')) {
            // This is a scoped package: recurse into children
            yield* collectLicenseInfo(absolutePath);
            continue;
        }

        const parentDir = path.basename(path.dirname(absolutePath));
        const isScopedPackage = parentDir.startsWith('@');

        const name = (() => {
            if (isScopedPackage) {
                // "scoped package" -- parent directory is part of name (e.g. @types/node, @sinonjs/formatio)
                return `${parentDir}/${basename}`;
            } else {
                return basename;
            }
        })();

        if (name === '.bin') {
            continue;
        }

        const manifest = readPackageJson(absolutePath);
        const url = manifest.repository ? manifest.repository.url : null;
        if (!url) {
            log.warning(`Could not find a repository URL for ${absolutePath}`);
        }

        const license = findLicense(absolutePath);
        const licenseText = license ? fs.readFileSync(license, { encoding: 'utf-8' }) : null;
        if (!licenseText) {
            log.warning(`Could not find a license for ${absolutePath}`);
        }

        yield {
            name: name,
            url: url || 'NO URL FOUND',
            licenseText: licenseText || 'NO LICENSE FOUND'
        };

        // See if this package has its own `node_modules` directory
        const child_packages = path.join(absolutePath, 'node_modules');
        if (fs.existsSync(child_packages)) {
            yield* collectLicenseInfo(child_packages);
        }
    }
}

/** Generate the third party notice line-by-line. */
function* thirdPartyNotice(taskName, licenseInfo) {
    // Preamble
    yield '';
    yield 'THIRD-PARTY SOFTWARE NOTICES AND INFORMATION';
    yield 'Do Not Translate or Localize';
    yield '';
    yield `This Visual Studio Team Services extension (${taskName}) is based on or incorporates material from the projects listed below (Third Party IP). The original copyright notice and the license under which Microsoft received such Third Party IP, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft licenses the Third Party IP to you under the licensing terms for the Visual Studio Team Services extension. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise.`;
    yield '';

    // Enumerated modules
    let num = 1;
    for (const item of licenseInfo) {
        if (item.url) {
            yield `${num}.\t${item.name} (${item.url})`;
        } else {
            yield `${num}.\t${item.name}`;
        }
        num += 1;
    }

    yield '';
    yield '';

    // Module licenses
    for (const item of licenseInfo) {
        yield `%% ${item.name} NOTICES, INFORMATION, AND LICENSE BEGIN HERE`;
        yield '=========================================';
        yield item.licenseText.trim();
        yield '=========================================';
        yield `END OF ${item.name} NOTICES, INFORMATION, AND LICENSE`;
        yield '';
    }
}

function writeLines(writeStream, lines) {
    const writeLine = (line) => {
        writeStream.write(line);
        writeStream.write(os.EOL);
    };

    for (const line of lines) {
        writeLine(line);
    }
}

/** Join zero or more iterables into a single iterable. */
function* chain(...iterables) {
    for (const it of iterables) {
        yield* it;
    }
}

function main(args) {
    try {
        if (!args || args.length < 2) {
            throw new Error(`Usage: node generate-third-party-notice.js <task name> [--verbose]`);
        }

        if (args.includes('--verbose')) {
            verboseLogging = true;
        }

        const taskName = args[2];
        const taskPath = path.join(__dirname, 'Tasks', taskName);
        trace('task path', taskPath);

        const nodeModuleDir = path.join(taskPath, 'node_modules');
        const testsNodeModuleDir = path.join(taskPath, 'Tests', 'node_modules');
        const licenseInfo = chain(
            collectLicenseInfo(nodeModuleDir),
            fs.existsSync(testsNodeModuleDir) ? collectLicenseInfo(testsNodeModuleDir) : []);

        function compareStrings(a, b) {
            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            } else {
                return 0;
            }
        }

        const sortedLicenseInfo = Array.from(licenseInfo).sort((x, y) => compareStrings(x.name, y.name));

        const writeStream = fs.createWriteStream(path.join(taskPath, 'ThirdPartyNotice.txt'));
        writeLines(writeStream, thirdPartyNotice(taskName, sortedLicenseInfo));
        writeStream.end();
    } catch (e) {
        log.error(e.message);
    }
}

main(process.argv);


text:
package com.zhuohua.teacher.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 * Department entity. @author MyEclipse Persistence Tools
 */
@Entity(name="teacherDepartment")
@Table(name="department"
    ,catalog="newstudentmis"
)
public class Department  implements java.io.Serializable {
     private Integer departmentId;
     private String name;

    public Department() {
    }
    @Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="DepartmentId", unique=true, nullable=false)
    public Integer getDepartmentId() {
        return this.departmentId;
    }
    public void setDepartmentId(Integer departmentId) {
        this.departmentId = departmentId;
    }
    @Column(name="Name", length=50)
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>DGLW</title>
    <description></description>
    <link>http://www.dglw.nethttp://www.dglw.net/</link>
    <atom:link href="http://www.dglw.nethttp://www.dglw.net/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Wed, 08 Jul 2015 14:36:48 -0400</pubDate>
    <lastBuildDate>Wed, 08 Jul 2015 14:36:48 -0400</lastBuildDate>
    <generator>Jekyll v2.5.3</generator>

      <item>
        <title>Welcome!</title>
        <description>
This site has been updated to utilize Jekyll, node.js, Poole and the Lanyon theme.

This website will serve as a comprehensive place for my thoughts on all things professional to leisure.  Topics of professional interest include application development, business intelligence (BI), and digital project management.  Personal interests include snowboarding, bass playing, beer making, and following the Philadelphia sports teams.

_David Wolf

</description>
        <pubDate>Sun, 05 Jul 2015 00:00:00 -0400</pubDate>
        <link>http://www.dglw.nethttp://www.dglw.net/2015/07/05/welcome/</link>
        <guid isPermaLink="true">http://www.dglw.nethttp://www.dglw.net/2015/07/05/welcome/</guid>

      </item>

      <item>
        <title>Ransomware and the case for backups</title>
        <description>
As a lot of my friends, I have become the resident IT expert for my family.  This means I may get called upon to handle all technical requests, from accessing email to deciphering the dreaded Windows blue-screen-of-death.  However, in my latest attempt to address my Mother's concern that something was "very wrong with the computer this time," remoting into the machine wasn't an option.  So I took a drive to visit my parents and see what the problem was, and on the desktop background was a glaring message that read something of the following:

My parents had become victims of Ransomware.

  This can happen by generally (a) downloading a malicious package via an untrusted but well-disguised email, or (b) through an Adobe Flash vulnerability.  The later is not suprising to most techies, as flash has been known to have vulnerabilities, the latest being a huge vulnerability that may lead to remote root access to your machine.

When first run, the ransomware payload installs itself in the user profile folder, and adds a key to the registry that causes it to run on startup. It then attempts to contact one of several designated command and control servers; once connected, the server generates a 2048-bit RSA key pair, and sends the public key back to the infected computer.The payload then encrypts files across local hard drives and mapped network drives with the public key, and logs each file encrypted to a registry key.

Now, I pride myself in trying to find the optimum solution for whatever the problem is, but this was a whole new ballgame.  Quickly checking their documents folder, all of my parents files had been encrypted.  Every. single. one.  Scrubbing the registry had no effect, and I was unaware of the steps that were being taken in Operation Tovar to disrupt the botnet that controlled the flavor of Ransomware that had infected my parent's computer.  For once, I was defeated.

As there was no way I was going to pay the ransom, the only thing that saved my parent's personal files was the auto-backup that I enabled when I first provisioned their Windows machine.  Re-installing the OS with a clean backup was the only option that allowed me to save my parents personal documents.

So, there are two morals to this story:

Don't open any email attachment in which you are not 100% sure of the sender identity.

Setup an auto-backup service to protect your files in the case of cataclysmic failure.

</description>
        <pubDate>Sun, 28 Jun 2015 00:00:00 -0400</pubDate>
        <link>http://www.dglw.nethttp://www.dglw.net/2015/06/28/ransomware/</link>
        <guid isPermaLink="true">http://www.dglw.nethttp://www.dglw.net/2015/06/28/ransomware/</guid>

      </item>

      <item>
        <title>Success, 7UP style</title>
        <description>
Article Roundup #1 today comes from the very popular financial journal, Forbes. I personally found the seven steps outlined in the article to be enlightening. Although I would be weary of the #1 step, "Marry a June Baby", since emotional conflicts and mis-management can arise from doing business with friends and family, I love step #2, "Think Small". For the same reasons I try to abide by the process followed by 37 Signals, as outlined in a previous blog post on their book Getting Real.

Check it out at Forbes: Seven Steps to Entrepreneurial Success.

</description>
        <pubDate>Thu, 12 Feb 2015 00:00:00 -0500</pubDate>
        <link>http://www.dglw.nethttp://www.dglw.net/2015/02/12/success-7up-style/</link>
        <guid isPermaLink="true">http://www.dglw.nethttp://www.dglw.net/2015/02/12/success-7up-style/</guid>

      </item>

      <item>
        <title>Application Roundup&colon; Trello</title>
        <description>
Kanban Board: Trello

There are numerous task management applications out there to assist you in managing, executing, and completing your . They range from desktop to web-based applications, with many being open-source, standalone applications that you can deploy on your own server. I've had my share of experiences with deploying LAMP (read: PHP) project/task management applications with good results, including Trac, Project Pier, and Project HQ. The installs were relatively straight forward and should have you up and running in an hour or two. However, the downside is, you have to maintain this type of environment yourself.

Although there's something to be said about understanding the server install and deployment process for these open-sourced task management software, having an out-of-the-box, quick web solution is great for task management. Enter Trello. A web-based kanban board style interface, it allows the user quick access to task status. The drag and drop feature, although not new, is great when moving tasks from the que to "in action". You can also color code your "epics", which is nice for quick view on an updated task when being pressed on the conference call.

See if it works for you. You can find the free task management software here.

</description>
        <pubDate>Thu, 05 Feb 2015 00:00:00 -0500</pubDate>
        <link>http://www.dglw.nethttp://www.dglw.net/2015/02/05/application-roundup-trello/</link>
        <guid isPermaLink="true">http://www.dglw.nethttp://www.dglw.net/2015/02/05/application-roundup-trello/</guid>

      </item>

      <item>
        <title>Revisiting Getting Real</title>
        <description>
Every year I revisit one of my favorite application and project management bibles, 37 Signal's Getting Real. If you are interested in building successful web applications, new to the process, or just bettering yourself and your work, this is a great read for you. I can't recommend enough how much I work on focusing on building more by building less, concentrating on those components that actually matter to the build process and disregarding those that don't.

You can read "37 Signals: Getting Real" for free via one of their products, Basecamp.

I have also begun reading "Rework" by 37 Signals, A book on better managing a business in our present, hectic, and sometimes inefficient workplaces.

</description>
        <pubDate>Tue, 20 Jan 2015 00:00:00 -0500</pubDate>
        <link>http://www.dglw.nethttp://www.dglw.net/2015/01/20/getting-real/</link>
        <guid isPermaLink="true">http://www.dglw.nethttp://www.dglw.net/2015/01/20/getting-real/</guid>

      </item>

  </channel>
</rss>


text:
/*
 * =============================================================================
 *
 *       Filename:  log.h
 *
 *    Description:  log utility.
 *
 *        Created:  10/20/2012 10:06:52 PM
 *
 *         Author:  Fu Haiping (forhappy), haipingf@gmail.com
 *        Company:  ICT ( Institute Of Computing Technology, CAS )
 *
 * =============================================================================
 */

#ifndef LLDB_LOG_H
#define LLDB_LOG_H

#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <time.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/time.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef enum _log_level_e log_level_t;

enum _log_level_e {
	// LLDB_LOG_LEVEL_QUIET = 0,
	LLDB_LOG_LEVEL_ERROR = 1,
	LLDB_LOG_LEVEL_WARN  = 2,
	LLDB_LOG_LEVEL_INFO  = 3,
	LLDB_LOG_LEVEL_DEBUG = 4
};

extern log_level_t log_level;

#define LOGSTREAM log_get_stream()

#define LOG_ERROR(x) if (log_level >= LLDB_LOG_LEVEL_ERROR) \
    log_message(LLDB_LOG_LEVEL_ERROR, __LINE__, __func__, log_format_message x)
#define LOG_WARN(x) if(log_level >= LLDB_LOG_LEVEL_WARN) \
    log_message(LLDB_LOG_LEVEL_WARN, __LINE__, __func__, log_format_message x)
#define LOG_INFO(x) if(log_level >= LLDB_LOG_LEVEL_INFO) \
    log_message(LLDB_LOG_LEVEL_INFO, __LINE__, __func__, log_format_message x)
#define LOG_DEBUG(x) if(log_level == LLDB_LOG_LEVEL_DEBUG) \
    log_message(LLDB_LOG_LEVEL_DEBUG, __LINE__, __func__, log_format_message x)

extern void log_message(
		log_level_t level, int line,
		const char* funcname,
		const char* message);
extern const char * log_format_message(const char* format, ...);
extern FILE * log_get_stream(void);
extern void log_set_stream(FILE *stream);
extern void log_set_debug_level(log_level_t level);

#ifdef __cplusplus
}
#endif

#endif /*LLDB_LOG_H*/


text:
/**
 * @ngdoc controller
 * @name $dashboardController
 * @requires $scope
 *
 * @description
 * This controller handle with all application data
 */

(function () {
  "use strict";
  app.controller("dashboardController", ["$scope", "dashboardService", function($scope, dashboardService) {

    /**
     * @ngdoc method
     * @name init
     * @methodOf $dashboardController
     * @description
     * This method initialize the page of dashboard which contains
     * graphics and status board.
     */
    $scope.init = function(){
      $scope.getAppList();
    };

    /**
     * @ngdoc method
     * @name getAppList
     * @methodOf $dashboardController
     * @description
     * Consult the service to get list of app
     * @returns {object} list of apps
     */
    $scope.getAppList = function(){
      $scope.appList = [];
      dashboardService.getAppList().then(function(result){
        for (var i = result.data.length - 1; i >= 0; i--) {
          if(result.data[i].isActive === true){
            $scope.appList.push(result.data[i]);
          }
        }
      },function(doh){
        console.log(doh);
      });
    };

    /**
     * @ngdoc method
     * @name getCloneUrl
     * @methodOf $dashboardController
     * @description
     * Consult the service to get the clone URL, but it will return error
     * @returns {object} ERROR 500
     */
    $scope.getCloneUrl = function(){
      dashboardService.getCloneUrl().then(function(result){
        console.info("RESULT: ",result);
      },function(doh){
        if(doh.status !== 200){
          alert(doh.data.msg);
        }

      });
    };

    /**
     * @ngdoc method
     * @name getCloneUrl
     * @methodOf $dashboardController
     * @description
     * Grab server's data from service
     * @param {string} serverName Servers name
     * @returns {object} Data of server
     */
    $scope.getServerInfo = function(serverName){
      dashboardService.getServerInfo(serverName).then(function(result){
        console.info("RESULT: ",result);
        if(serverName === "web1app"){
          $scope.web1App = [];
          $scope.web1App.push(result.data[0].stats[0].value+"%");
          $scope.web1App.push(result.data[1].stats[0].value+"%");
        }else{
          $scope.db1lucy = [];
          $scope.db1lucy.push(result.data[0].stats[0].value+"%");
          $scope.db1lucy.push(result.data[1].stats[0].value+"%");
        }
      },function(doh){
        console.log(doh);
      });
    };

  }]);
}());


text:
/**
 * Created by king on 15-5-13.
 *
 * ch09.querystring_parse.js
 */
console.info("------   querystring parse()   ------");
console.info();
var url = require('url');// TODO: 引入路径处理模块
var querystring = require('querystring');// TODO: 引入路径处理模块
/**
 * 测试 url.parse() 函数方法
 * @type {string}
 */
var queryUrl = "http://localhost:6666/index?name=king&gender=male&level=high";
console.info('typeof queryUrl is : ' + typeof url.parse(queryUrl));
console.info();
console.info('querystring.parse("queryUrl") is : ');
var url_parse = url.parse(queryUrl).query;
/**
 * 测试 querystring.parse() 函数方法
 * @type {*}
 */
var querystring_parse = querystring.parse(url_parse);
console.info(querystring_parse);
console.info();


text:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% from "macros.html" import form_field %}

{% block title %}Registrera{% endblock %}

{% block page_content %}

Registrera

    <form class="form" action="" method="post" role="form">
      {{ form.hidden_tag() }}

      {{ form_field(form.email) }}
      {{ form_field(form.password) }}
      {{ form_field(form.first_name) }}
      {{ form_field(form.last_name) }}

Om personuppgifter

          {% include 'gdpr.html' %}

              {{ form.gdpr_consent() }} {{form.gdpr_consent.label.text }}

        {{ form.submit(class="btn btn-success") }}

    </form>

{#
    {{ wtf.quick_form(form, button_map={'submit':'success'}) }}
#}

{% endblock %}


text:
// Part of SourceAFIS for Java: https://sourceafis.machinezoo.com/java
package com.machinezoo.sourceafis.engine.images;

import com.machinezoo.sourceafis.engine.configuration.*;

/*
 * This decoder uses Android's Bitmap class to decode templates.
 * Note that Bitmap class will not work in unit tests. It only works inside a full-blown emulator.
 *
 * Since direct references of Android libraries would not compile,
 * we will reference BitmapFactory and Bitmap via reflection.
 */
class AndroidImageDecoder extends ImageDecoder {
	@Override
	public boolean available() {
		return PlatformCheck.hasClass("android.graphics.BitmapFactory");
	}
	@Override
	public String name() {
		return "Android";
	}
	@Override
	public DecodedImage decode(byte[] image) {
		AndroidBitmap bitmap = AndroidBitmapFactory.decodeByteArray(image, 0, image.length);
		if (bitmap.instance == null)
			throw new IllegalArgumentException("Unsupported image format.");
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int[] pixels = new int[width * height];
		bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
		return new DecodedImage(width, height, pixels);
	}
}


text:
[![Go Report Card](https://goreportcard.com/badge/github.com/buger/jsonparser)](https://goreportcard.com/report/github.com/buger/jsonparser) ![License](https://img.shields.io/dub/l/vibe-d.svg)
# Alternative JSON parser for Go (so far fastest)

It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **10 times faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.

## Rationale
Originally I made this for a project that relies on a lot of 3rd party APIs that can be unpredictable and complex.
I love simplicity and prefer to avoid external dependecies. `encoding/json` requires you to know exactly your data structures, or if you prefer to use `map[string]interface{}` instead, it will be very slow and hard to manage.
I investigated what's on the market and found that most libraries are just wrappers around `encoding/json`, there is few options with own parsers (`ffjson`, `easyjson`), but they still requires you to create data structures.

Goal of this project is to push JSON parser to the performance limits and not sucrifice with compliance and developer user experience.

## Example
For the given JSON our goal is to extract the user's full name, number of github followers and avatar.

```go
import "github.com/buger/jsonparser"

...

data := []byte(`{
  "person": {
    "name": {
      "first": "Leonid",
      "last": "Bugaev",
      "fullName": "Leonid Bugaev"
    },
    "github": {
      "handle": "buger",
      "followers": 109
    },
    "avatars": [
      { "url": "https://avatars1.githubusercontent.com/u/14009?v=3&s=460", "type": "thumbnail" }
    ]
  },
  "company": {
    "name": "Acme"
  }
}`)

// You can specify key path by providing arguments to Get function
jsonparser.Get(data, "person", "name", "fullName")

// There is `GetInt` and `GetBoolean` helpers if you exactly know key data type
jsonparser.GetInt(data, "person", "github", "followers")

// When you try to get object, it will return you []byte slice pointer to data containing it
// In `company` it will be `{"name": "Acme"}`
jsonparser.Get(data, "company")

// If the key doesn't exist it will throw an error
var size int64
if value, _, err := jsonparser.GetInt(data, "company", "size"); err == nil {
  size = value
}

// You can use `ArrayEach` helper to iterate items [item1, item2 .... itemN]
jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
	fmt.Println(jsonparser.Get(value, "url"))
}, "person", "avatars")

// You can use `ObjectEach` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN }
jsonparser.ObjectEach(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
        fmt.Printf("Key: '%s'\n Value: '%s'\n Type: %s\n", string(key), string(value), dataType)
	return nil
}, "person", "name")
```

## Need to speedup your app?

I'm available for consulting and can help you push your app performance to the limits. Ping me at: leonsbox@gmail.com.

## Reference

Library API is really simple. You just need the `Get` method to perform any operation. The rest is just helpers around it.

You also can view API at [godoc.org](https://godoc.org/github.com/buger/jsonparser)

### **`Get`**
```go
func Get(data []byte, keys ...string) (value []byte, dataType jsonparser.ValueType, offset int, err error)
```
Receives data structure, and key path to extract value from.

Returns:
* `value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error
* `dataType` - 	Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null`
* `offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper.
* `err` - If the key is not found or any other parsing issue, it should return error. If key not found it also sets `dataType` to `NotExist`

Accepts multiple keys to specify path to JSON value (in case of quering nested structures).
If no keys are provided it will try to extract the closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation.

### **`GetString`**
```go
func GetString(data []byte, keys ...string) (val string, err error)
```
Returns strings properly handing escaped and unicode characters. Note that this will cause additional memory allocations.

### **`GetUnsafeString`**
If you need string in your app, and ready to sacrifice with support of escaped symbols in favor of speed. It returns string mapped to existing byte slice memory, without any allocations:
```go
s, _, := jsonparser.GetUnsafeString(data, "person", "name", "title")
switch s {
  case 'CEO':
    ...
  case 'Engineer'
    ...
  ...
}
```
Note that `unsafe` here means that your string will exist until GC will free underlying byte slice, for most of cases it means that you can use this string only in current context, and should not pass it anywhere externally: through channels or any other way.

### **`GetBoolean`**, **`GetInt`** and **`GetFloat`**
```go
func GetBoolean(data []byte, keys ...string) (val bool, err error)

func GetFloat(data []byte, keys ...string) (val float64, err error)

func GetInt(data []byte, keys ...string) (val float64, err error)
```
If you know the key type, you can use the helpers above.
If key data type do not match, it will return error.

### **`ArrayEach`**
```go
func ArrayEach(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string)
```
Needed for iterating arrays, accepts a callback function with the same return arguments as `Get`.

### **`ObjectEach`**
```go
func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)
```
Needed for iterating object, accepts a callback function. Example:
```go
var handler func([]byte, []byte, jsonparser.ValueType, int) error
handler = func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
	//do stuff here
}
jsonparser.ObjectEach(myJson, handler)
```

### **`KeyEach`**
```go
func KeyEach(data []byte, cb func(idx int, value []byte, dataType jsonparser.ValueType, err error), paths ...[]string)
```
When you need to read multiple keys, and you do not afraid of low-level API `KeyEach` is your friend. It read payload only single time, and calls callback function once path is found. For example when you call multiple times `Get`, it has to process payload multiple times, each time you call it. Depending on payload `KeyEach` can be multiple times faster than `Get`. Path can use nested keys as well!

```go
paths := [][]string{
	[]string{"uuid"},
	[]string{"tz"},
	[]string{"ua"},
	[]string{"st"},
}
var data SmallPayload

jsonparser.EachKey(smallFixture, func(idx int, value []byte, vt jsonparser.ValueType, err error){
	switch idx {
	case 0:
		data.Uuid, _ = value
	case 1:
		v, _ := jsonparser.ParseInt(value)
		data.Tz = int(v)
	case 2:
		data.Ua, _ = value
	case 3:
		v, _ := jsonparser.ParseInt(value)
		data.St = int(v)
	}
}, paths...)
```

## What makes it so fast?
* It does not rely on `encoding/json`, `reflection` or `interface{}`, the only real package dependency is `bytes`.
* Operates with JSON payload on byte level, providing you pointers to the original data structure: no memory allocation.
* No automatic type conversions, by default everything is a []byte, but it provides you value type, so you can convert by yourself (there is few helpers included).
* Does not parse full record, only keys you specified

## Benchmarks

There are 3 benchmark types, trying to simulate real-life usage for small, medium and large JSON payloads.
For each metric, the lower value is better. Time/op is in nanoseconds. Values better than standard encoding/json marked as bold text.
Benchmarks run on standard Linode 1024 box.

Compared libraries:
* https://golang.org/pkg/encoding/json
* https://github.com/Jeffail/gabs
* https://github.com/bitly/go-simplejson
* https://github.com/antonholmquist/jason
* https://github.com/mreiferson/go-ujson
* https://github.com/ugorji/go/codec
* https://github.com/pquerna/ffjson
* https://github.com/mailru/easyjson
* https://github.com/buger/jsonparser

#### TLDR
If you want to skip next sections we have 2 winner: `jsonparser` and `easyjson`.
`jsonparser` is up to 10 times faster than standard `encoding/json` package (depending on payload size and usage), and almost infinitely (literally) better in memory consumption because it operates with data on byte level, and provide direct slice pointers.
`easyjson` wins in CPU in medium tests and frankly i'm impressed with this package: it is remarkable results considering that it is almost drop-in replacement for `encoding/json` (require some code generation).

It's hard to fully compare `jsonparser` and `easyjson` (or `ffson`), they a true parsers and fully process record, unlike `jsonparser` which parse only keys you specified.

If you searching for replacement of `encoding/json` while keeping structs, `easyjson` is an amazing choise. If you want to process dynamic JSON, have memory constrains, or more control over your data you should try `jsonparser`.

`jsonparser` performance heavily depends on usage, and it works best when you do not need to process full record, only some keys. The more calls you need to make, the slower it will be, in contrast `easyjson` (or `ffjson`, `encoding/json`) parser record only 1 time, and then you can make as many calls as you want.

With great power comes great responsibility! :)

#### Small payload

Each test processes 190 bytes of http log as a JSON record.
It should read multiple fields.
https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payload_test.go

| Library | time/op | bytes/op | allocs/op |
| --- | --- | --- | --- | --- |
| encoding/json struct | 7879 | 880 | 18 |
| encoding/json interface{} | 8946 | 1521 | 38|
| Jeffail/gabs | 10053 | 1649 | 46 |
| bitly/go-simplejson | 10128 | 2241 | 36 |
| antonholmquist/jason | 27152 | 7237 | 101 |
| github.com/ugorji/go/codec | 8806 | 2176 | 31 |
| mreiferson/go-ujson | **7008** | **1409** | 37 |
| pquerna/ffjson | **3769** | **624** | **15** |
| mailru/easyjson | **2002** | **192** | **9** |
| buger/jsonparser | **1367** | **0** | **0** |
| buger/jsonparser (EachKey API) | **809** | **0** | **0** |

Winners are ffjson, easyjson and jsonparser, where jsonparser is up to 9.8x faster than encoding/json and 4.6x faster than ffjson, and slightly faster than easyjson.
If you look at memory allocation, jsonparser has no rivals, as it makes no data copy and operates with raw []byte structures and pointers to it.

#### Medium payload

Each test processes a 2.4kb JSON record (based on Clearbit API).
It should read multiple nested fields and 1 array.

https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_payload_test.go

| Library | time/op | bytes/op | allocs/op |
| --- | --- | --- | --- | --- |
| encoding/json struct | 57749 | 1336 | 29 |
| encoding/json interface{} | 79297 | 10627 | 215 |
| Jeffail/gabs | 83807 | 11202 | 235 |
| bitly/go-simplejson | 88187 | 17187 | 220 |
| antonholmquist/jason | 94099 | 19013 | 247 |
| github.com/ugorji/go/codec | 114719 | 6712 | 152 |
| mreiferson/go-ujson | **56972** | 11547 | 270 |
| pquerna/ffjson | **20298** | **856** | **20** |
| mailru/easyjson | **10512** | **336** | **12** |
| buger/jsonparser | **15955** | **0** | **0** |
| buger/jsonparser (EachKey API) | **8916** | **0** | **0** |

The difference between ffjson and jsonparser in CPU usage is smaller, while the memory consumption difference is growing. On the other hand `easyjson` shows remarkable performance for medium payload.

`gabs`, `go-simplejson` and `jason` are based on encoding/json and map[string]interface{} and actually only helpers for unstructured JSON, their performance correlate with `encoding/json interface{}`, and they will skip next round.
`go-ujson` while have its own parser, shows same performance as `encoding/json`, also skips next round. Same situation with `ugorji/go/codec`, but it showed unexpectedly bad performance for complex payloads.

#### Large payload

Each test processes a 24kb JSON record (based on Discourse API)
It should read 2 arrays, and for each item in array get a few fields.
Basically it means processing a full JSON file.

https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payload_test.go

| Library | time/op | bytes/op | allocs/op |
| --- | --- | --- | --- | --- |
| encoding/json struct | 748336 | 8272 | 307 |
| encoding/json interface{} | 1224271 | 215425 | 3395 |
| pquerna/ffjson | **312271** | **7792** | **298** |
| mailru/easyjson | **154186** | **6992** | **288** |
| buger/jsonparser | **85308** | **0** | **0** |

`jsonparser` now is a winner, but do not forget that it is way more lighweight parser than `ffson` or `easyjson`, and they have to parser all the data, while `jsonparser` parse only what you need. All `ffjson`, `easysjon` and `jsonparser` have their own parsing code, and does not depend on `encoding/json` or `interface{}`, thats one of the reasons why they are so fast. `easyjson` also use a bit of `unsafe` package to reduce memory consuption (in theory it can lead to some unexpected GC issue, but i did not tested enough)

Also last benchmark did not included `EachKey` test, because in this particular case we need to read lot of Array values, and using `ArrayEach` is more efficient.

## Questions and support

All bug-reports and suggestions should go though Github Issues.
If you have some private questions you can send them directly to me: leonsbox@gmail.com

## Contributing

1. Fork it
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Added some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create new Pull Request

## Development

All my development happens using Docker, and repo include some Make tasks to simplify development.

* `make build` - builds docker image, usually can be called only once
* `make test` - run tests
* `make fmt` - run go fmt
* `make bench` - run benchmarks (if you need to run only single benchmark modify `BENCHMARK` variable in make file)
* `make profile` - runs benchmark and generate 3 files-  `cpu.out`, `mem.mprof` and `benchmark.test` binary, which can be used for `go tool pprof`
* `make bash` - enter container (i use it for running `go tool pprof` above)


text:
<?php

namespace Google\Service\FirebaseDynamicLinks;

class AnalyticsInfo extends \Google\Model
{
  protected $googlePlayAnalyticsType = GooglePlayAnalytics::class;
  protected $googlePlayAnalyticsDataType = '';
  protected $itunesConnectAnalyticsType = ITunesConnectAnalytics::class;
  protected $itunesConnectAnalyticsDataType = '';

  /**
   * @param GooglePlayAnalytics
   */
  public function setGooglePlayAnalytics(GooglePlayAnalytics $googlePlayAnalytics)
  {
    $this->googlePlayAnalytics = $googlePlayAnalytics;
  }
  /**
   * @return GooglePlayAnalytics
   */
  public function getGooglePlayAnalytics()
  {
    return $this->googlePlayAnalytics;
  }
  /**
   * @param ITunesConnectAnalytics
   */
  public function setItunesConnectAnalytics(ITunesConnectAnalytics $itunesConnectAnalytics)
  {
    $this->itunesConnectAnalytics = $itunesConnectAnalytics;
  }
  /**
   * @return ITunesConnectAnalytics
   */
  public function getItunesConnectAnalytics()
  {
    return $this->itunesConnectAnalytics;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AnalyticsInfo::class, 'Google_Service_FirebaseDynamicLinks_AnalyticsInfo');


text:
/*
 * ScopeContainer.cpp
 *
 *  Created on: March 17, 2010
 *      Author: lawrence.daniels@gmail.com
 */

#include "ScopeContainer.h"

/**
 * Constructor
 */
ScopeContainer::ScopeContainer( const char* name, Scope* parentScope, ScopeType type, char modifiers ):
Scope( name, parentScope, type, modifiers ) {
	// do nothing
}

/**
 * Destruction
 */
ScopeContainer::~ScopeContainer() {
	methods.clear();
}

/**
 * Compiles the class' methods into byte code
 */
int ScopeContainer::compileMethods( CodeBuffer* cb ) {
	cb->putShort( methods.size() );
	for( STRING_HASH_MAP(Method*)::iterator i = methods.begin(); i != methods.end(); i++ ) {
		Method* method = i->second;
		method->compile( cb );
	}
	return 0;
}

/**
 * Decompiles into byte code into methods and attaches them
 * to the given class
 */
int ScopeContainer::decompileMethods( ScopeContainer* scope, CodeBuffer* cb ) {
	int n_methods = cb->getShort();
	for( int n = 0; n < n_methods; n++ ) {
		Method* method = Method::decompile( scope, cb );
		if( method == NULL ) {
			printf( "Class file is corrupted: (%d) methods could not be retrieved\n", n_methods );
			return NULL;
		}

		// add it to the class
		scope->addMethod( method );
	}
	return 0;
}

/**
 * Adds the given member to the class
 * member - the given member
 */
bool ScopeContainer::addMember( ClassMember *member ) {
	switch( member->getMemberType() ) {
		case CLASS_FIELD: return addField( (Field*)member );
		case CLASS_METHOD: return addMethod( (Method*)member );
	}
	return false;
}

/**
 * Looks up a method by its signature
 */
ClassMember* ScopeContainer::lookupMember( const char* name ) {
	if( methods.count( name ) ) {
		return  methods[name];
	}
	else {
		return fields[name];
	}
}

/**
 * Adds the given method to the class
 * @param method the given method
 */
bool ScopeContainer::addMethod( Method *method ) {
	// if the method already exists...
	if( methods.count( method->getSignature() ) ) {
		return false;
	}

	// add the method
	methods[method->getSignature()] = method;
	return true;
}

/**
 * Returns the methods contained with this scope
 */
vector<Method*> ScopeContainer::getMethods() {
	vector<Method*> methodList;

	for( STRING_HASH_MAP(Method*)::iterator i = methods.begin(); i != methods.end(); i++ ) {
		Method* method = i->second;
		if( method != NULL ) {
			methodList.push_back( method );
		}
	}
	return methodList;
}

/**
 * Looks up a class method by its signature
 */
Method* ScopeContainer::lookupMethod( const char* signature ) {
	return methods[signature];
}


text:
namespace relocation_packer {

TEST(Debug, Log) {
  Logger::Reset();
  std::ostringstream info;
  std::ostringstream error;
  Logger::SetStreams(&info, &error);

  LOG(INFO) << "INFO log message";
  LOG(WARNING) << "WARNING log message";
  LOG(ERROR) << "ERROR log message";

  EXPECT_EQ("INFO: INFO log message\n", info.str());
  EXPECT_EQ("WARNING: WARNING log message\n"
            "ERROR: ERROR log message\n", error.str());
  Logger::Reset();
}

TEST(Debug, LogIf) {
  Logger::Reset();
  std::ostringstream info;
  std::ostringstream error;
  Logger::SetStreams(&info, &error);

  LOG_IF(INFO, true) << "INFO log message";
  LOG_IF(INFO, false) << "INFO log message, SHOULD NOT PRINT";
  LOG_IF(WARNING, true) << "WARNING log message";
  LOG_IF(WARNING, false) << "WARNING log message, SHOULD NOT PRINT";
  LOG_IF(ERROR, true) << "ERROR log message";
  LOG_IF(ERROR, false) << "ERROR log message, SHOULD NOT PRINT";
  LOG_IF(FATAL, false) << "FATAL log message, SHOULD NOT PRINT";

  EXPECT_EQ("INFO: INFO log message\n", info.str());
  EXPECT_EQ("WARNING: WARNING log message\n"
            "ERROR: ERROR log message\n", error.str());
  Logger::Reset();
}

TEST(Debug, Vlog) {
  Logger::Reset();
  std::ostringstream info;
  std::ostringstream error;
  Logger::SetStreams(&info, &error);

  VLOG(0) << "VLOG 0 INFO log message, SHOULD NOT PRINT";
  VLOG(1) << "VLOG 1 INFO log message, SHOULD NOT PRINT";
  VLOG(2) << "VLOG 2 INFO log message, SHOULD NOT PRINT";

  EXPECT_EQ("", info.str());
  EXPECT_EQ("", error.str());

  Logger::SetVerbose(1);

  VLOG(0) << "VLOG 0 INFO log message";
  VLOG(1) << "VLOG 1 INFO log message";
  VLOG(2) << "VLOG 2 INFO log message, SHOULD NOT PRINT";

  EXPECT_EQ("INFO: VLOG 0 INFO log message\n"
            "INFO: VLOG 1 INFO log message\n", info.str());
  EXPECT_EQ("", error.str());
  Logger::Reset();
}

TEST(Debug, VlogIf) {
  Logger::Reset();
  std::ostringstream info;
  std::ostringstream error;
  Logger::SetStreams(&info, &error);

  VLOG_IF(0, true) << "VLOG 0 INFO log message, SHOULD NOT PRINT";
  VLOG_IF(1, true) << "VLOG 1 INFO log message, SHOULD NOT PRINT";
  VLOG_IF(2, true) << "VLOG 2 INFO log message, SHOULD NOT PRINT";

  EXPECT_EQ("", info.str());
  EXPECT_EQ("", error.str());

  Logger::SetVerbose(1);

  VLOG_IF(0, true) << "VLOG 0 INFO log message";
  VLOG_IF(0, false) << "VLOG 0 INFO log message, SHOULD NOT PRINT";
  VLOG_IF(1, true) << "VLOG 1 INFO log message";
  VLOG_IF(1, false) << "VLOG 1 INFO log message, SHOULD NOT PRINT";
  VLOG_IF(2, true) << "VLOG 2 INFO log message, SHOULD NOT PRINT";
  VLOG_IF(2, false) << "VLOG 2 INFO log message, SHOULD NOT PRINT";

  EXPECT_EQ("INFO: VLOG 0 INFO log message\n"
            "INFO: VLOG 1 INFO log message\n", info.str());
  EXPECT_EQ("", error.str());
  Logger::Reset();
}

TEST(DebugDeathTest, Fatal) {
  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
  Logger::Reset();
  EXPECT_DEATH(LOG(FATAL) << "FATAL log message", "FATAL: FATAL log message");
  EXPECT_DEATH(
      LOG_IF(FATAL, true) << "FATAL log message", "FATAL: FATAL log message");
}

TEST(DebugDeathTest, Check) {
  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
  Logger::Reset();
  CHECK(0 == 0);
  EXPECT_DEATH(CHECK(0 == 1), "FATAL: .*:.*: .*: CHECK '0 == 1' failed");
}

TEST(DebugDeathTest, NotReached) {
  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
  Logger::Reset();
  EXPECT_DEATH(NOTREACHED(), "FATAL: .*:.*: .*: NOTREACHED\\(\\) hit");
}

}  // namespace relocation_packer


text:
package com.xeiam.xchange.btce.v3.dto.marketdata;

import java.math.BigDecimal;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Author: brox
 */

public class BTCEPairInfo {

  private final int decimals;
  private final BigDecimal minPrice;
  private final BigDecimal maxPrice;
  private final BigDecimal minAmount;
  private final int hidden;
  private final BigDecimal fee;

  public BTCEPairInfo(@JsonProperty("decimal_places") int decimals, @JsonProperty("min_price") BigDecimal minPrice, @JsonProperty("max_price") BigDecimal maxPrice,
      @JsonProperty("min_amount") BigDecimal minAmount, @JsonProperty("hidden") int hidden, @JsonProperty("fee") BigDecimal fee) {

    this.decimals = decimals;
    this.minPrice = minPrice;
    this.maxPrice = maxPrice;
    this.minAmount = minAmount;
    this.hidden = hidden;
    this.fee = fee;
  }

  public int getDecimals() {

    return decimals;
  }

  public BigDecimal getMinPrice() {

    return minPrice;
  }

  public BigDecimal getMaxPrice() {

    return maxPrice;
  }

  public BigDecimal getMinAmount() {

    return minAmount;
  }

  public int getHidden() {

    return hidden;
  }

  public BigDecimal getFee() {

    return fee;
  }

  @Override
  public String toString() {

    return "BTCEPairInfo [decimals=" + decimals + ", minPrice=" + minPrice + ", maxPrice=" + maxPrice + ", minAmount=" + minAmount + ", hidden=" + hidden + ", fee=" + fee + "]";
  }

}


text:
package io.cattle.platform.resource.pool.impl;

public class StringRangeGenerator extends AbstractStringRangeGenerator {

    public StringRangeGenerator(String min, String max) {
        super(min, max);
    }

    @Override
    protected long fromString(String value) {
        return Long.parseLong(value);
    }

    @Override
    protected String toString(long value) {
        return Long.toString(value);
    }

}


text:
<!--
  ~ Copyright 2015 Jesús Adolfo García Pasquel
  ~
  ~ 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.
  -->

<resources>
    <string name="app_name">My App Portfolio</string>

    <string name="textview_title">My Nanodegree Apps!</string>
    <string name="button_spotify_app">Spotify Streamer</string>
    <string name="button_scores_app">Scores App</string>
    <string name="button_library_app">Library App</string>
    <string name="button_build_it_bigger_app">Build It Bigger</string>
    <string name="button_xyz_reader_app">XYZ Reader</string>
    <string name="button_capstone_app">Capstone: My Own App</string>
    <string name="item_about_author">About the author</string>
    <string name="toast_about_author">More information coming soon!</string>
    <string name="toast_spotify_app">This button will launch my Spotify Streamer app!</string>
    <string name="toast_scores_app">This button will launch my Scores app!</string>
    <string name="toast_library_app">This button will launch my Library app!</string>
    <string name="toast_build_it_bigger_app">This button will launch my Build It Bigger app!</string>
    <string name="toast_xyz_reader_app">This button will launch my XYZ Reader app!</string>
    <string name="toast_capstone_app">This button will launch my capstone app!</string>
</resources>


text:
package br.ufrgs.inf.gar.cwm.dash.data;

import java.util.Collection;
import java.util.Collections;

import br.ufrgs.inf.gar.cwm.dash.domain.DashboardNotification;
import br.ufrgs.inf.gar.cwm.dash.domain.User;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

public class DummyDataProvider {

    private final Collection<DashboardNotification> notifications = DummyDataGenerator
            .randomNotifications();

    public DummyDataProvider() {
    }

    public User authenticate(String userName, String password) {
        User user = new User();
        user.setName("Mauricio Q.G.");
        user.setRole("admin");
        String email = "mauricio@cwm.com";
        user.setEmail(email.replaceAll(" ", ""));
        return user;
    }

    public int getUnreadNotificationsCount() {
        Predicate<DashboardNotification> unreadPredicate = new Predicate<DashboardNotification>() {
            @Override
            public boolean apply(DashboardNotification input) {
                return !input.isRead();
            }
        };
        return Collections2.filter(notifications, unreadPredicate).size();
    }

    public Collection<DashboardNotification> getNotifications() {
        for (DashboardNotification notification : notifications) {
            notification.setRead(true);
        }
        return Collections.unmodifiableCollection(notifications);
    }
}


text:
@interface NSNumber (flxExtensions)
- (BOOL) isLessThanNumber:(NSNumber *)number;
- (BOOL) isGreaterThanNumber:(NSNumber *)number;
- (BOOL) isLessThanEqualToNumber:(NSNumber *)number;
- (BOOL) isGreaterThanEqualToNumber:(NSNumber *)number;
+ (BOOL) number:(NSNumber *)number1 isEqualToNumber:(NSNumber *)number2;
@end


text:
package com.puzzletimer.solvers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

public class Square1Solver {
    public static class State {
        public byte[] permutation;

        public State(byte[] permutation) {
            this.permutation = permutation;
        }

        public boolean isTwistable() {
            return this.permutation[1] != this.permutation[2] &&
                   this.permutation[7] != this.permutation[8] &&
                   this.permutation[13] != this.permutation[14] &&
                   this.permutation[19] != this.permutation[20];
        }

        public State multiply(State move) {
            byte [] permutation = new byte[24];

            for (int i = 0; i < permutation.length; i++) {
                permutation[i] = this.permutation[move.permutation[i]];
            }

            return new State(permutation);
        }

        public int getShapeIndex() {
            byte[] cuts = new byte[24];
            for (int i = 0; i < cuts.length; i++) {
                cuts[i] = 0;
            }

            for (int i = 0; i < 12; i++) {
                int next = (i + 1) % 12;
                if (this.permutation[i] != this.permutation[next]) {
                    cuts[i] = 1;
                }
            }

            for (int i = 0; i < 12; i++) {
                int next = (i + 1) % 12;
                if (this.permutation[12 + i] != this.permutation[12 + next]) {
                    cuts[12 + i] = 1;
                }
            }

            return IndexMapping.orientationToIndex(cuts, 2);
        }

        public byte[] getPiecesPermutation() {
            byte[] permutation = new byte[16];
            int nextSlot = 0;

            for (int i = 0; i < 12; i++) {
                int next = (i + 1) % 12;
                if (this.permutation[i] != this.permutation[next]) {
                    permutation[nextSlot++] = this.permutation[i];
                }
            }

            for (int i = 0; i < 12; i++) {
                int next = 12 + (i + 1) % 12;
                if (this.permutation[12 + i] != this.permutation[next]) {
                    permutation[nextSlot++] = this.permutation[12 + i];
                }
            }

            return permutation;
        }

        public CubeState toCubeState() {
            int[] cornerIndices = { 0, 3, 6, 9, 12, 15, 18, 21 };

            byte[] cornersPermutation = new byte[8];
            for (int i = 0; i < cornersPermutation.length; i++) {
                cornersPermutation[i] = this.permutation[cornerIndices[i]];
            }

            int[] edgeIndices = { 1, 4, 7, 10, 13, 16, 19, 22 };

            byte[] edgesPermutation = new byte[8];
            for (int i = 0; i < edgesPermutation.length; i++) {
                edgesPermutation[i] = (byte) (this.permutation[edgeIndices[i]] - 8);
            }

            return new CubeState(cornersPermutation, edgesPermutation);
        }

        public static State id;

        static {
            id = new State(new byte[] {
                 0,  8,  1,  1,  9,  2,  2, 10,  3,  3, 11,  0,
                 4, 12,  5,  5, 13,  6,  6, 14,  7,  7, 15,  4,
            });
        }
    }

    private static class CubeState {
        public byte[] cornersPermutation;
        public byte[] edgesPermutation;

        public CubeState(byte[] cornersPermutation, byte[] edgesPermutation) {
            this.cornersPermutation = cornersPermutation;
            this.edgesPermutation = edgesPermutation;
        }

        public CubeState multiply(CubeState move) {
            byte[] cornersPermutation = new byte[8];
            byte[] edgesPermutation = new byte[8];

            for (int i = 0; i < 8; i++) {
                cornersPermutation[i] = this.cornersPermutation[move.cornersPermutation[i]];
                edgesPermutation[i] = this.edgesPermutation[move.edgesPermutation[i]];
            }

            return new CubeState(cornersPermutation, edgesPermutation);
        }
    }

    private boolean initialized;

    // phase 1
    private State[] moves1;
    private ArrayList<State> shapes;
    private HashMap<Integer, Integer> evenShapeDistance;
    private HashMap<Integer, Integer> oddShapeDistance;

    // phase 2
    public final int N_CORNERS_PERMUTATIONS = 40320;
    public final int N_CORNERS_COMBINATIONS = 70;
    public final int N_EDGES_PERMUTATIONS = 40320;
    public final int N_EDGES_COMBINATIONS = 70;

    private CubeState[] moves2;
    private int[][] cornersPermutationMove;
    private int[][] cornersCombinationMove;
    private int[][] edgesPermutationMove;
    private int[][] edgesCombinationMove;
    private byte[][] cornersDistance;
    private byte[][] edgesDistance;

    public Square1Solver() {
        this.initialized = false;
    }

    private void initialize() {
        // -- phase 1 --

        // moves
        this.moves1 = new State[23];

        State move10 = new State(new byte[] {
            11,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10,
            12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
        });

        State move = move10;
        for (int i = 0; i < 11; i++) {
            this.moves1[i] = move;
            move = move.multiply(move10);
        }

        State move01 = new State(new byte[] {
             0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,
            13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 12,
        });

        move = move01;
        for (int i = 0; i < 11; i++) {
            this.moves1[11 + i] = move;
            move = move.multiply(move01);
        }

        State moveTwist = new State(new byte[] {
             0,  1, 19, 18, 17, 16, 15, 14,  8,  9, 10, 11,
            12, 13,  7,  6,  5,  4,  3,  2, 20, 21, 22, 23,
        });

        this.moves1[22] = moveTwist;

        // shape tables
        this.shapes = new ArrayList<State>();

        this.evenShapeDistance = new HashMap<Integer, Integer>();
        this.oddShapeDistance = new HashMap<Integer, Integer>();
        this.evenShapeDistance.put(State.id.getShapeIndex(), 0);

        ArrayList<State> fringe = new ArrayList<State>();
        fringe.add(State.id);

        int depth = 0;
        while (fringe.size() > 0) {
            ArrayList<State> newFringe = new ArrayList<State>();
            for (State state : fringe) {
                if (state.isTwistable()) {
                    this.shapes.add(state);
                }

                for (int i = 0; i < this.moves1.length; i++) {
                    if (i == 22 && !state.isTwistable()) {
                        continue;
                    }

                    State next = state.multiply(this.moves1[i]);

                    HashMap<Integer, Integer> distanceTable =
                        isEvenPermutation(next.getPiecesPermutation()) ?
                            this.evenShapeDistance : this.oddShapeDistance;

                    if (!distanceTable.containsKey(next.getShapeIndex())) {
                        distanceTable.put(next.getShapeIndex(), depth + 1);
                        newFringe.add(next);
                    }
                }
            }

            fringe = newFringe;
            depth++;
        }

        // -- phase 2 --

        // moves
        CubeState move30 =          new CubeState(new byte[] { 3, 0, 1, 2, 4, 5, 6, 7 }, new byte[] { 3, 0, 1, 2, 4, 5, 6, 7 });
        CubeState move03 =          new CubeState(new byte[] { 0, 1, 2, 3, 5, 6, 7, 4 }, new byte[] { 0, 1, 2, 3, 5, 6, 7, 4 });
        CubeState moveTwistTop =    new CubeState(new byte[] { 0, 6, 5, 3, 4, 2, 1, 7 }, new byte[] { 6, 5, 2, 3, 4, 1, 0, 7 });
        CubeState moveTwistBottom = new CubeState(new byte[] { 0, 6, 5, 3, 4, 2, 1, 7 }, new byte[] { 0, 5, 4, 3, 2, 1, 6, 7 });

        this.moves2 = new CubeState[] {
            move30,
            move30.multiply(move30),
            move30.multiply(move30).multiply(move30),
            move03,
            move03.multiply(move03),
            move03.multiply(move03).multiply(move03),
            moveTwistTop,
            moveTwistBottom,
        };

        // move tables
        this.cornersPermutationMove = new int[this.N_CORNERS_PERMUTATIONS][this.moves2.length];
        for (int i = 0; i < this.cornersPermutationMove.length; i++) {
            CubeState state = new CubeState(IndexMapping.indexToPermutation(i, 8), new byte[8]);
            for (int j = 0; j < this.cornersPermutationMove[i].length; j++) {
                this.cornersPermutationMove[i][j] =
                    IndexMapping.permutationToIndex(
                        state.multiply(this.moves2[j]).cornersPermutation);
            }
        }

        this.cornersCombinationMove = new int[this.N_CORNERS_COMBINATIONS][this.moves2.length];
        for (int i = 0; i < this.cornersCombinationMove.length; i++) {
            boolean[] combination = IndexMapping.indexToCombination(i, 4, 8);

            byte[] corners = new byte[8];
            byte nextTop = 0;
            byte nextBottom = 4;

            for (int j = 0; j < corners.length; j++) {
                if (combination[j]) {
                    corners[j] = nextTop++;
                } else {
                    corners[j] = nextBottom++;
                }
            }

            CubeState state = new CubeState(corners, new byte[8]);
            for (int j = 0; j < this.cornersCombinationMove[i].length; j++) {
                CubeState result = state.multiply(this.moves2[j]);

                boolean[] isTopCorner = new boolean[8];
                for (int k = 0; k < isTopCorner.length; k++) {
                    isTopCorner[k] = result.cornersPermutation[k] < 4;
                }

                this.cornersCombinationMove[i][j] =
                    IndexMapping.combinationToIndex(isTopCorner, 4);
            }
        }

        this.edgesPermutationMove = new int[this.N_EDGES_PERMUTATIONS][this.moves2.length];
        for (int i = 0; i < this.edgesPermutationMove.length; i++) {
            CubeState state = new CubeState(new byte[8], IndexMapping.indexToPermutation(i, 8));
            for (int j = 0; j < this.edgesPermutationMove[i].length; j++) {
                this.edgesPermutationMove[i][j] =
                    IndexMapping.permutationToIndex(
                        state.multiply(this.moves2[j]).edgesPermutation);
            }
        }

        this.edgesCombinationMove = new int[this.N_EDGES_COMBINATIONS][this.moves2.length];
        for (int i = 0; i < this.edgesCombinationMove.length; i++) {
            boolean[] combination = IndexMapping.indexToCombination(i, 4, 8);

            byte[] edges = new byte[8];
            byte nextTop = 0;
            byte nextBottom = 4;

            for (int j = 0; j < edges.length; j++) {
                if (combination[j]) {
                    edges[j] = nextTop++;
                } else {
                    edges[j] = nextBottom++;
                }
            }

            CubeState state = new CubeState(new byte[8], edges);
            for (int j = 0; j < this.edgesCombinationMove[i].length; j++) {
                CubeState result = state.multiply(this.moves2[j]);

                boolean[] isTopEdge = new boolean[8];
                for (int k = 0; k < isTopEdge.length; k++) {
                    isTopEdge[k] = result.edgesPermutation[k] < 4;
                }

                this.edgesCombinationMove[i][j] =
                    IndexMapping.combinationToIndex(isTopEdge, 4);
            }
        }

        // prune tables
        this.cornersDistance = new byte[this.N_CORNERS_PERMUTATIONS][this.N_EDGES_COMBINATIONS];
        for (int i = 0; i < this.cornersDistance.length; i++) {
            for (int j = 0; j < this.cornersDistance[i].length; j++) {
                this.cornersDistance[i][j] = -1;
            }
        }
        this.cornersDistance[0][0] = 0;

        int nVisited;
        do {
            nVisited = 0;

            for (int i = 0; i < this.cornersDistance.length; i++) {
                for (int j = 0; j < this.cornersDistance[i].length; j++) {
                    if (this.cornersDistance[i][j] == depth) {
                        for (int k = 0; k < this.moves2.length; k++) {
                            int nextCornerPermutation = this.cornersPermutationMove[i][k];
                            int nextEdgeCombination = this.edgesCombinationMove[j][k];
                            if (this.cornersDistance[nextCornerPermutation][nextEdgeCombination] < 0) {
                                this.cornersDistance[nextCornerPermutation][nextEdgeCombination] = (byte) (depth + 1);
                                nVisited++;
                            }
                        }
                    }
                }
            }

            depth++;
        } while (nVisited > 0);

        this.edgesDistance = new byte[this.N_EDGES_PERMUTATIONS][this.N_CORNERS_COMBINATIONS];
        for (int i = 0; i < this.edgesDistance.length; i++) {
            for (int j = 0; j < this.edgesDistance[i].length; j++) {
                this.edgesDistance[i][j] = -1;
            }
        }
        this.edgesDistance[0][0] = 0;

        depth = 0;
        do {
            nVisited = 0;

            for (int i = 0; i < this.edgesDistance.length; i++) {
                for (int j = 0; j < this.edgesDistance[i].length; j++) {
                    if (this.edgesDistance[i][j] == depth) {
                        for (int k = 0; k < this.moves2.length; k++) {
                            int nextEdgesPermutation = this.edgesPermutationMove[i][k];
                            int nextCornersCombination = this.cornersCombinationMove[j][k];
                            if (this.edgesDistance[nextEdgesPermutation][nextCornersCombination] < 0) {
                                this.edgesDistance[nextEdgesPermutation][nextCornersCombination] = (byte) (depth + 1);
                                nVisited++;
                            }
                        }
                    }
                }
            }

            depth++;
        } while (nVisited > 0);

        this.initialized = true;
    }

    private boolean isEvenPermutation(byte[] permutation) {
        int nInversions = 0;
        for (int i = 0; i < permutation.length; i++) {
            for (int j = i + 1; j < permutation.length; j++) {
                if (permutation[i] > permutation[j]) {
                    nInversions++;
                }
            }
        }

        return nInversions % 2 == 0;
    }

    public String[] solve(State state) {
        ArrayList<String> sequence = new ArrayList<String>();

        int top = 0;
        int bottom = 0;
        for (int moveIndex : solution(state)) {
            if (moveIndex < 11) {
                top += moveIndex + 1;
                top %= 12;
            } else if (moveIndex < 22) {
                bottom += (moveIndex - 11) + 1;
                bottom %= 12;
            } else {
                if (top != 0 || bottom != 0) {
                    if (top > 6) {
                        top = -(12 - top);
                    }

                    if (bottom > 6) {
                        bottom = -(12 - bottom);
                    }

                    sequence.add(String.format("(%d,%d)", top, bottom));
                    top = 0;
                    bottom = 0;
                }

                sequence.add("/");
            }
        }

        if (top != 0 || bottom != 0) {
            if (top > 6) {
                top = -(12 - top);
            }

            if (bottom > 6) {
                bottom = -(12 - bottom);
            }

            sequence.add(String.format("(%d,%d)", top, bottom));
        }

        String[] sequenceArray = new String[sequence.size()];
        sequence.toArray(sequenceArray);

        return sequenceArray;
    }

    public String[] generate(State state) {
        ArrayList<String> sequence = new ArrayList<String>();

        int top = 0;
        int bottom = 0;
        int[] solution = solution(state);
        for (int i = solution.length - 1; i >= 0; i--) {
            if (solution[i] < 11) {
                top += 12 - (solution[i] + 1);
                top %= 12;
            } else if (solution[i] < 22) {
                bottom += 12 - ((solution[i] - 11) + 1);
                bottom %= 12;
            } else {
                if (top != 0 || bottom != 0) {
                    if (top > 6) {
                        top = -(12 - top);
                    }

                    if (bottom > 6) {
                        bottom = -(12 - bottom);
                    }

                    sequence.add(String.format("(%d,%d)", top, bottom));
                    top = 0;
                    bottom = 0;
                }

                sequence.add("/");
            }
        }

        if (top != 0 || bottom != 0) {
            if (top > 6) {
                top = -(12 - top);
            }

            if (bottom > 6) {
                bottom = -(12 - bottom);
            }

            sequence.add(String.format("(%d,%d)", top, bottom));
        }

        String[] sequenceArray = new String[sequence.size()];
        sequence.toArray(sequenceArray);

        return sequenceArray;
    }

    private int[] solution(State state) {
        if (!this.initialized) {
            initialize();
        }

        for (int depth = 0;; depth++) {
            ArrayList<Integer> solution1 = new ArrayList<Integer>();
            ArrayList<Integer> solution2 = new ArrayList<Integer>();
            if (search(state, isEvenPermutation(state.getPiecesPermutation()), depth, solution1, solution2)) {
                ArrayList<Integer> sequence = new ArrayList<Integer>();

                for (int moveIndex : solution1) {
                    sequence.add(moveIndex);
                }

                int[][] phase2MoveMapping = {
                    {  2 },
                    {  5 },
                    {  8 },
                    { 13 },
                    { 16 },
                    { 19 },
                    {  0, 22, 10 },
                    { 21, 22, 11 },
                };

                for (int moveIndex : solution2) {
                    for (int phase1MoveIndex : phase2MoveMapping[moveIndex]) {
                        sequence.add(phase1MoveIndex);
                    }
                }

                int[] sequenceArray = new int[sequence.size()];
                for (int i = 0; i < sequenceArray.length; i++) {
                    sequenceArray[i] = sequence.get(i);
                }

                return sequenceArray;
            }
        }
    }

    private boolean search(State state, boolean isEvenPermutation, int depth, ArrayList<Integer> solution1, ArrayList<Integer> solution2) {
        if (depth == 0) {
            if (isEvenPermutation && state.getShapeIndex() == State.id.getShapeIndex()) {
                int[] sequence2 = solution2(state.toCubeState(), 17);
                if (sequence2 != null) {
                    for (int m : sequence2) {
                        solution2.add(m);
                    }

                    return true;
                }
            }

            return false;
        }

        int distance =
            isEvenPermutation ?
                this.evenShapeDistance.get(state.getShapeIndex()) :
                this.oddShapeDistance.get(state.getShapeIndex());
        if (distance <= depth) {
            for (int i = 0; i < this.moves1.length; i++) {
                if (i == 22 && !state.isTwistable()) {
                    continue;
                }

                State next = state.multiply(this.moves1[i]);

                solution1.add(i);
                if (search(
                    next,
                    isEvenPermutation(next.getPiecesPermutation()),
                    depth - 1,
                    solution1,
                    solution2)) {
                    return true;
                }
                solution1.remove(solution1.size() - 1);
            }
        }

        return false;
    }

    private int[] solution2(CubeState state, int maxDepth) {
        int cornersPermutation = IndexMapping.permutationToIndex(state.cornersPermutation);

        boolean[] isTopCorner= new boolean[8];
        for (int k = 0; k < isTopCorner.length; k++) {
            isTopCorner[k] = state.cornersPermutation[k] < 4;
        }
        int cornersCombination = IndexMapping.combinationToIndex(isTopCorner, 4);

        int edgesPermutation = IndexMapping.permutationToIndex(state.edgesPermutation);

        boolean[] isTopEdge = new boolean[8];
        for (int k = 0; k < isTopEdge.length; k++) {
            isTopEdge[k] = state.edgesPermutation[k] < 4;
        }

        int edgesCombination = IndexMapping.combinationToIndex(isTopEdge, 4);

        for (int depth = 0; depth <= maxDepth; depth++) {
            int[] solution = new int[depth];
            if (search2(cornersPermutation, cornersCombination, edgesPermutation, edgesCombination, depth, solution)) {
                return solution;
            }
        }

        return null;
    }

    private boolean search2(int cornersPermutation, int cornersCombination, int edgesPermutation, int edgesCombination, int depth, int[] solution) {
        if (depth == 0) {
            return cornersPermutation == 0 && edgesPermutation == 0;
        }

        if (this.cornersDistance[cornersPermutation][edgesCombination] <= depth &&
            this.edgesDistance[edgesPermutation][cornersCombination] <= depth) {
            for (int i = 0; i < this.moves2.length; i++) {
                if (solution.length - depth - 1 >= 0 && solution[solution.length - depth - 1] / 3 == i / 3) {
                    continue;
                }

                solution[solution.length - depth] = i;
                if (search2(
                    this.cornersPermutationMove[cornersPermutation][i],
                    this.cornersCombinationMove[cornersCombination][i],
                    this.edgesPermutationMove[edgesPermutation][i],
                    this.edgesCombinationMove[edgesCombination][i],
                    depth - 1,
                    solution)) {
                    return true;
                }
            }
        }

        return false;
    }

    public State getRandomState(State shape, Random random) {
        byte[] cornersPermutation =
            IndexMapping.indexToPermutation(
                random.nextInt(this.N_CORNERS_PERMUTATIONS), 8);

        byte[] edgesPermutation =
            IndexMapping.indexToPermutation(
                random.nextInt(this.N_EDGES_PERMUTATIONS), 8);

        byte[] permutation = new byte[shape.permutation.length];
        for (int i = 0; i < permutation.length; i++) {
            if (shape.permutation[i] < 8) {
                permutation[i] = cornersPermutation[shape.permutation[i]];
            } else {
                permutation[i] = (byte) (8 + edgesPermutation[shape.permutation[i] - 8]);
            }
        }

        return new State(permutation);
    }

    public State getRandomState(Random random) {
        if (!this.initialized) {
            initialize();
        }

        return getRandomState(
            this.shapes.get(random.nextInt(this.shapes.size())),
            random);
    }
}


text:
namespace TicketingSystem.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;

    public class Reply
    {
        [Key]
        public int Id { get; set; }

        [MinLength(10)]
        public string Content { get; set; }

        public string AuthorId { get; set; }

        public virtual User Author { get; set; }

        public int TicketId { get; set; }

        public virtual Ticket Ticket { get; set; }

        public DateTime PublishedAt { get; set; }
    }
}


text:
package com.verigreen.common.utils;

import java.nio.file.Path;
import java.nio.file.Paths;

public class DirectoryUtils {

    /**
     * Returns a path to the given directory, if such can be resolved from your current path.
     *
     * @param folder
     *            - the desired folder name
     */
    public static Path getDirectory(String folder) {

        Path basePath = Paths.get(".").toAbsolutePath();
        Path currentPath = basePath;
        while (currentPath != null) {
            Path cloudServicesPath = currentPath.resolve(folder);
            if (cloudServicesPath.toFile().exists()) {
                currentPath = cloudServicesPath;
                break;
            }
            currentPath = currentPath.getParent();
        }

        return currentPath;
    }
}


text:
package com.piketec.tpt.api.steplist;

import java.rmi.RemoteException;

import com.piketec.tpt.api.ApiException;
import com.piketec.tpt.api.Project;
import com.piketec.tpt.api.RemoteList;
import com.piketec.tpt.api.Scenario;
import com.piketec.tpt.api.ScenarioGroup;
import com.piketec.tpt.api.Testlet;
import com.piketec.tpt.api.diagram.DiagramScenario;

/**
 * A StepListScenario contains a list of {@link Step steps}.
 *
 *

 * In TPT, it represents both the variants as well as the test cases. Create a new
 * StepListScenario via {@link Testlet#createDiagVariant(String, ScenarioGroup)}
 *

 *
 * @see Testlet#createDiagVariant(String, ScenarioGroup)
 * @see Project#getTopLevelTestlet()
 */
public interface StepListScenario extends Scenario {

  /**
   * @return the list of {@link Step Steps} in their given order.
   *
   * @throws RemoteException
   *           remote communication problem
   */
  public RemoteList<Step> getSteps() throws RemoteException;

  /**
   * Creates a step of a given type at the given position.
   *
   * @param index
   *          Indicates the position where the new step shall be inserted in the step list
   *          represented by this object.
   * @param type
   *          The type of the newly created Step as String, look in {@link Step} for possible
   *          Strings as a type.
   * @return the newly created Step.
   *
   * @throws RemoteException
   *           remote communication problem
   * @throws ApiException
   *           if the given type does not exist.
   */
  public Step createStep(int index, String type) throws ApiException, RemoteException;

  /**
   * Sets the do assessment variable from a step list scenario. When it is set to true, all the
   * compare steps will be considered during the execution, otherwise they will be ignored. If the
   * variable is set to false, it will also automatically deactivate the report always variable.
   *
   * @param active
   *          true if the do assessment variable should be turned on.
   * @throws ApiException
   *           if the scenario is not a step list scenario
   * @throws RemoteException
   *           remote communication problem
   */
  void setDoAssessment(boolean active) throws ApiException, RemoteException;

  /**
   * Get the value from the do assessment variable for the given scenario.
   *
   * @return true if the do assessment variable is on, otherwise false.
   *
   * @throws RemoteException
   *           remote communication problem
   */
  boolean isDoAssessment() throws RemoteException;

  /**
   * Sets the report always variable from a step list scenario. When it is set to true, all the
   * compare step results will appear in the report, otherwise they will be ignored. If this
   * variable is set to true, it will also automatically activate the do assessment variable.
   *
   * @param active
   *          true if the report always variable should be turned on.
   *
   * @throws ApiException
   *           If the scenario is not a step list scenario
   * @throws RemoteException
   *           remote communication problem
   */
  void setReportAlways(boolean active) throws ApiException, RemoteException;

  /**
   * Get the value from the report always variable for this scenario.
   *
   * @return true if the report always variable is on, otherwise false.
   *
   * @throws RemoteException
   *           remote communication problem
   */
  boolean isReportAlways() throws RemoteException;

  /**
   * @return A comma separated list of the used namespaces for the step list scenario.
   *
   * @throws RemoteException
   *           remote communication problem
   */
  String getUsing() throws RemoteException;

  /**
   * Set the used namespace(s) for the step list scenario. For more namespaces provide a comma
   * separated list.
   *
   * @param using
   *          The new namespace(s) that shall be used.
   *
   * @throws RemoteException
   *           remote communication problem
   */
  void setUsing(String using) throws RemoteException;

  /**
   * Transforms this {@link StepListScenario} into a {@link DiagramScenario} without any transitions
   * added to the path. All contents will be deleted, but the meta data like ids and attributes will
   * be retained. Do not use this {@link StepListScenario} afterwards.
   *
   * @return This {@link StepListScenario} as an empty {@link DiagramScenario}.
   *
   * @throws RemoteException
   *           remote communication problem
   */
  public DiagramScenario transformToDiagramScenario() throws RemoteException;

  /**
   * Generates a specification containing the step list and the initial values. This specification
   * can be remimported via {@link #importTestSpecification(String)}.

   * Please note that some complex steps cannot be imported and will be imported as documentation
   * steps (e.g. embedded signal step) or will be unrolled (e.g. table step).
   *
   *
   * @return generated test specification for this step list.
   * @throws RemoteException
   *           remote communication problem
   */
  public String exportTestSpecification() throws RemoteException;

  /**
   * Imports a formatted step list specification into this {@link StepListScenario}. This method
   * imports initial values and appends all steps to the existing definitions.

   * Please note that some complex steps cannot be imported and will be imported as documentation
   * steps (e.g. embedded signal step) or will be unrolled (e.g. table step).
   *
   * @param specification
   *          The sepcification as formatted plain text, e.g.

   *

   *
   *          Initialize myVar to 17

   *          Set myVar to myVar+1 // myComment

   *          Ramp myParam to 1 with 2/s
   *
   * @throws RemoteException
   *           remote communication problem
   * @see #exportTestSpecification()
   */
  public void importTestSpecification(String specification)
      throws RemoteException;
}


text:
import { Injectable }                                     from '@angular/core';
import { AuthService }                                    from './auth.service';
import { Observable }                                     from 'rxjs/Observable';
import { SignalR, IConnectionOptions, ConnectionStatus,
         ISignalRConnection, ConnectionStatuses }         from 'ng2-signalr';
import { BehaviorSubject }                                from 'rxjs/BehaviorSubject';

@Injectable()
export class SignalRService {
  private signalrConnection: ISignalRConnection;
  private connectionStatus = ConnectionStatuses.disconnected;
  private stopFromCode = false;
  private connectionSubject = new BehaviorSubject<ISignalRConnection>(null);

  constructor(private authsrv: AuthService, private _signalR: SignalR) {

    this.authsrv.isLoggedInObs().filter(x => x === false).subscribe(x => this.stopConnection());

    const signalrObs = this.authsrv.isLoggedInObs()
      .filter(x => x === true)
      .map((): IConnectionOptions => this.getConnectionOptions())
      .switchMap((options: IConnectionOptions) =>
        Observable.defer(() => Observable.fromPromise(this._signalR.connect(options)))
        .retryWhen(err => err.scan<number>((errorCount, error) => {
          if (errorCount >= 2) {
            throw error;
          }
          return errorCount + 1;
        }, 0).delay(3000))
        .catch(err => Observable.empty())
      )
      .share();

    signalrObs.switchMap((x: ISignalRConnection) => x.status)
      .map((x) => this.connectionStatus = x)
      .filter((status) => status.equals(ConnectionStatuses.disconnected))
      .filter(() => !this.stopFromCode)
      .delay(5000)
      .subscribe((status: ConnectionStatus) => {
        this.startConnection();
    });

    signalrObs.switchMap((x: ISignalRConnection) => x.errors)
      .subscribe((error: any) => {
        console.error('SignalR ERROR: ', error);
      });

    signalrObs.switchMap((x: ISignalRConnection) => x.listenFor('echoMethodResponse'))
      .subscribe((data: any) => {
          console.log(data);
        }, (errmsg: any) => {
          console.error(errmsg);
        });

    signalrObs.subscribe((x: ISignalRConnection) => {
      this.connectionSubject.next(x);
      this.signalrConnection = x;
      this.sendMessageToServer('test message');
    }, (errmsg) => {
      console.error(errmsg);
    });
  }

  public sendMessageToServer(msg: string) {
    this.signalrConnection.invoke('echoMethod', msg)
    .then((data: string[]) => {
      console.log(data);
    })
    .catch((errmsg) => {
      console.error(errmsg);
    });
  }

  public stopConnection() {
    if (this.signalrConnection && this.signalrConnection.id && !this.connectionStatus.equals(ConnectionStatuses.disconnected)) {
      this.stopFromCode = true;
      this.signalrConnection.stop();
    }
  }

  public startConnection() {
    if (this.signalrConnection && this.signalrConnection.id && this.connectionStatus.equals(ConnectionStatuses.disconnected)) {
      this.stopFromCode = false;
      this.signalrConnection.start();
    }
  }

  public getSignalRConnection(): Observable<ISignalRConnection> {
    return this.connectionSubject.asObservable().filter(x => x !== null).share();
  }

  public callServerMethod(methodName: string, ...args: any[]): Observable<string> {
    return this.getSignalRConnection().mergeMap((x) => x.invoke(methodName, ...args));
  }

  public addEventListener(methodName: string): Observable<any> {
    return this.getSignalRConnection()
      .switchMap((x: ISignalRConnection) => x.listenFor(methodName))
      .map((x: string) => JSON.parse(x));
  }

  private getConnectionOptions() {
    return {
      hubName: 'messageHub',
      qs: {
        authorization: this.authsrv.getToken()
      }
    };
  }

}