text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>

<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <link rel="shortcut icon" href="favicon.ico"/>
      <meta http-equiv="Refresh" content="1; URL=content/index.html"/>
      <title>OpenStack API快速入门 </title>

                        If not automatically redirected, click here: content/index.html

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * 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.
 */

class Contents extends CI_Model {

    var $data = array(
        array('id' => '1', 'what' => 'In 1937, a team known as the Cincinnati Bengals was formed as a member
            of the American Football League. The 1937 Bengals finished with a 2-4-2
            record in their first year, but the AFL folded after the season. The
            Bengals continued as an independent team in 1938, and in 1939 joined a
            new AFL, finishing in second place with a 6-2 record. But again, the
            league folded after the season.

Once again in 1940, another new AFL emerged, and again the Bengals
            joined. But that AFL suffered the fate of the two AFLs before it,
            folding after the 1941 season as the United States entered World World
            II, and the Bengals folded along with it. Pro football returned to
            Cincinnati 26 years later in 1967 when Paul Brown headed an ownership
            group that landed an expansion franchise in the modern-era American
            Football League. Brown, a Pro Football Hall of Famer who founded and
            coached the Cleveland Browns from 1946-62, picked the name Bengals for
            the new team "to give it a link with past professional football in
            Cincinnati.'),

        array('id' => '2', 'what' => 'This site is for academic and learning purposes.
            Any use of names or media falls under the Fair use guidelines.')
       );

    // Constructor
    public function __construct() {
        parent::__construct();
    }

    public function homepage() {
        return $this->data[0];
    }

    public function about() {
        return $this->data[1];
    }

}


text:
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.FridaHookTest" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_200</item>
        <item name="colorPrimaryDark">@color/purple_700</item>
        <item name="colorAccent">@color/teal_200</item>
        <!-- Customize your theme here. -->
    </style>
</resources>


text:
using blink::WebApplicationCacheHost;
using blink::WebFrame;
using blink::WebMessagePortChannel;
using blink::WebMessagePortChannelArray;
using blink::WebSecurityOrigin;
using blink::WebString;
using blink::WebWorker;
using blink::WebSharedWorkerClient;

namespace content {

// How long to wait for worker to finish after it's been told to terminate.
#define kMaxTimeForRunawayWorkerSeconds 3

WebSharedWorkerClientProxy::WebSharedWorkerClientProxy(
    int route_id, WebSharedWorkerStub* stub)
    : route_id_(route_id),
      appcache_host_id_(0),
      stub_(stub),
      weak_factory_(this),
      devtools_agent_(NULL) {
}

WebSharedWorkerClientProxy::~WebSharedWorkerClientProxy() {
}

void WebSharedWorkerClientProxy::workerContextClosed() {
  Send(new WorkerHostMsg_WorkerContextClosed(route_id_));
}

void WebSharedWorkerClientProxy::workerContextDestroyed() {
  Send(new WorkerHostMsg_WorkerContextDestroyed(route_id_));
  // Tell the stub that the worker has shutdown - frees this object.
  if (stub_)
    stub_->Shutdown();
}

blink::WebNotificationPresenter*
WebSharedWorkerClientProxy::notificationPresenter() {
  // TODO(johnnyg): Notifications are not yet hooked up to workers.
  // Coming soon.
  NOTREACHED();
  return NULL;
}

WebApplicationCacheHost* WebSharedWorkerClientProxy::createApplicationCacheHost(
    blink::WebApplicationCacheHostClient* client) {
  WorkerWebApplicationCacheHostImpl* host =
      new WorkerWebApplicationCacheHostImpl(stub_->appcache_init_info(),
                                            client);
  // Remember the id of the instance we create so we have access to that
  // value when creating nested dedicated workers in createWorker.
  appcache_host_id_ = host->host_id();
  return host;
}

blink::WebWorkerPermissionClientProxy*
WebSharedWorkerClientProxy::createWorkerPermissionClientProxy(
    const blink::WebSecurityOrigin& origin) {
  return new SharedWorkerPermissionClientProxy(
      GURL(origin.toString()), origin.isUnique(), route_id_,
      ChildThread::current()->thread_safe_sender());
}

// TODO(kinuko): Deprecate these methods.
bool WebSharedWorkerClientProxy::allowDatabase(WebFrame* frame,
                                         const WebString& name,
                                         const WebString& display_name,
                                         unsigned long estimated_size) {
  return false;
}

bool WebSharedWorkerClientProxy::allowFileSystem() {
  return false;
}

bool WebSharedWorkerClientProxy::allowIndexedDB(const blink::WebString& name) {
  return false;
}

void WebSharedWorkerClientProxy::dispatchDevToolsMessage(
    const WebString& message) {
  if (devtools_agent_)
    devtools_agent_->SendDevToolsMessage(message);
}

void WebSharedWorkerClientProxy::saveDevToolsAgentState(
    const blink::WebString& state) {
  if (devtools_agent_)
    devtools_agent_->SaveDevToolsAgentState(state);
}

bool WebSharedWorkerClientProxy::Send(IPC::Message* message) {
  return WorkerThread::current()->Send(message);
}

void WebSharedWorkerClientProxy::EnsureWorkerContextTerminates() {
  // This shuts down the process cleanly from the perspective of the browser
  // process, and avoids the crashed worker infobar from appearing to the new
  // page. It's ok to post several of theese, because the first executed task
  // will exit the message loop and subsequent ones won't be executed.
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&WebSharedWorkerClientProxy::workerContextDestroyed,
                 weak_factory_.GetWeakPtr()),
      base::TimeDelta::FromSeconds(kMaxTimeForRunawayWorkerSeconds));
}

}  // namespace content


text:
MODULE_INFO(vermagic, VERMAGIC_STRING);

__visible struct module __this_module
__attribute__((section(".gnu.linkonce.this_module"))) = {
	.name = KBUILD_MODNAME,
	.init = init_module,
#ifdef CONFIG_MODULE_UNLOAD
	.exit = cleanup_module,
#endif
	.arch = MODULE_ARCH_INIT,
};

static const struct modversion_info ____versions[]
__used
__attribute__((section("__versions"))) = {
	{ 0xca05c877, __VMLINUX_SYMBOL_STR(module_layout) },
	{ 0xda2478d0, __VMLINUX_SYMBOL_STR(param_ops_short) },
	{ 0x6ebc5149, __VMLINUX_SYMBOL_STR(param_ops_long) },
	{ 0x5d41c87c, __VMLINUX_SYMBOL_STR(param_ops_charp) },
	{ 0xb6b46a7c, __VMLINUX_SYMBOL_STR(param_ops_int) },
	{ 0x20b2bb2d, __VMLINUX_SYMBOL_STR(param_array_ops) },
	{ 0x27e1a049, __VMLINUX_SYMBOL_STR(printk) },
};

static const char __module_depends[]
__used
__attribute__((section(".modinfo"))) =
"depends=";

MODULE_INFO(srcversion, "5B4FAA56FC37FE38070BC87");


text:
/**
 * ajaxRequest is used to initiate a request for an xml page
 * @param url the url of the requested page
 * @param callback, a function with a single parameter of type dom
 * @param errorCallback (optional), a parameterless function called if there is an error
 */

    function ajaxRequest(url, callback, errorCallback) {
        var ajax_request= false;

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            ajax_request= new XMLHttpRequest();
            if (ajax_request.overrideMimeType) {
                ajax_request.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                ajax_request= new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    ajax_request= new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!ajax_request) {
            // Unable to initiate the request
            errorCallback();
            return;
        }

        ajax_request.onreadystatechange = function() { ajaxStateChange(ajax_request, callback, errorCallback)};
        ajax_request.open('GET', url, true);
        ajax_request.send(null);

    }

    function ajaxStateChange(ajax_request, callback, errorCallback) {
        if (ajax_request.readyState == 4) {
            if (ajax_request.status == 200) {
                if (callback) {
                    callback(ajax_request.responseXML);
                }
            } else {
                if (errorCallback) {
                    errorCallback;
                }
            }
        }

    }


text:
from .howdoi import command_line_runner

command_line_runner()


text:
package com.yammer.metrics.spring;

import com.yammer.metrics.core.Gauge;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

public class GaugeMethod extends Gauge<Object> {

    private final Object bean;
    private final Method method;

    public GaugeMethod(final Object bean, final Method method) {
        this.bean = bean;
        this.method = method;

        ReflectionUtils.makeAccessible(method);
    }

    @Override
    public Object value() {
        return ReflectionUtils.invokeMethod(method, bean);
    }

}


text:
package com.uberverse.arkcraft.common.inventory;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;

/**
 * @author wildbill22
 *         Like InventoryBasic
 */
public class InventoryPlayerCrafting implements IInventory
{
    private String inventoryTitle;
    private int slotsCount;
    private ItemStack[] inventoryContents;
    private boolean hasCustomName;

    public InventoryPlayerCrafting(String title, boolean customName, int slotCount)
    {
        this.inventoryTitle = title;
        this.hasCustomName = customName;
        this.slotsCount = slotCount;
        this.inventoryContents = new ItemStack[slotCount];
    }

    public void loadInventoryFromNBT(NBTTagCompound nbt)
    {
        final byte NBT_TYPE_COMPOUND = 10;
        NBTTagList dataForAllItems = nbt.getTagList("Items", NBT_TYPE_COMPOUND);
        loadInventoryFromNBT(dataForAllItems);
    }

    public void loadInventoryFromNBT(NBTTagList nbt)
    {
        int i;
        for (i = 0; i < this.getSizeInventory(); ++i)
        {
            this.setInventorySlotContents(i, (ItemStack) null);
        }
        for (i = 0; i < nbt.tagCount(); ++i)
        {
            NBTTagCompound nbttagcompound = nbt.getCompoundTagAt(i);
            int j = nbttagcompound.getByte("Slot") & 255;

            if (j >= 0 && j < this.getSizeInventory())
            {
                this.setInventorySlotContents(j, ItemStack.loadItemStackFromNBT(nbttagcompound));
            }
        }
    }

    public void saveInventoryToNBT(NBTTagCompound nbt)
    {
        NBTTagList nbttaglist = new NBTTagList();
        for (int i = 0; i < this.getSizeInventory(); ++i)
        {
            ItemStack itemstack = this.getStackInSlot(i);
            if (itemstack != null)
            {
                NBTTagCompound nbttagcompound = new NBTTagCompound();
                nbttagcompound.setByte("Slot", (byte) i);
                itemstack.writeToNBT(nbttagcompound);
                nbttaglist.appendTag(nbttagcompound);
//                LogHelper.info("InventoryPlayerCrafting: Saved a " + itemstack.getItem() + " to inventory.");
            }
        }
        nbt.setTag("Items", nbttaglist);
    }

    /**
     * Do not make give this method the name canInteractWith because it clashes with Container
     */
    @Override
    public boolean isUseableByPlayer(EntityPlayer player)
    {
        return true;
    }

    @Override
    public void openInventory(EntityPlayer player) {}

    @Override
    public void closeInventory(EntityPlayer player) {}

    public ItemStack[] getItemStacks()
    {
        return inventoryContents;
    }

    @Override
    public String getName()
    {
        return this.inventoryTitle;
    }

    @Override
    public boolean hasCustomName()
    {
        return hasCustomName;
    }

    @Override
    public IChatComponent getDisplayName()
    {
        return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatComponentTranslation(this.getName(), new Object[0]));
    }

    @Override
    public int getSizeInventory()
    {
        return this.slotsCount;
    }

    @Override
    public ItemStack getStackInSlot(int index)
    {
        return index >= 0 && index < this.inventoryContents.length ? this.inventoryContents[index] : null;
    }

    @Override
    public ItemStack decrStackSize(int index, int count)
    {
        if (this.inventoryContents[index] != null)
        {
            ItemStack itemstack;
            if (this.inventoryContents[index].stackSize <= count)
            {
                itemstack = this.inventoryContents[index];
                this.inventoryContents[index] = null;
                this.markDirty();
                return itemstack;
            }
            else
            {
                itemstack = this.inventoryContents[index].splitStack(count);
                if (this.inventoryContents[index].stackSize == 0)
                {
                    this.inventoryContents[index] = null;
                }
                this.markDirty();
                return itemstack;
            }
        }
        else
        {
            return null;
        }
    }

    @Override
    public ItemStack getStackInSlotOnClosing(int index)
    {
        if (this.inventoryContents[index] != null)
        {
            ItemStack itemstack = this.inventoryContents[index];
            this.inventoryContents[index] = null;
            return itemstack;
        }
        else
        {
            return null;
        }
    }

    @Override
    public void setInventorySlotContents(int index, ItemStack stack)
    {
        this.inventoryContents[index] = stack;
        if (stack != null && stack.stackSize > this.getInventoryStackLimit())
        {
            stack.stackSize = this.getInventoryStackLimit();
        }
        this.markDirty();
    }

    @Override
    public int getInventoryStackLimit()
    {
        return 64;
    }

    @Override
    public void markDirty()
    {
    }

    @Override
    public boolean isItemValidForSlot(int index, ItemStack stack)
    {
        return true;
    }

    @Override
    public int getField(int id)
    {
        return 0;
    }

    @Override
    public void setField(int id, int value) {}

    @Override
    public int getFieldCount()
    {
        return 0;
    }

    @Override
    public void clear()
    {
        for (int i = 0; i < this.inventoryContents.length; ++i)
        {
            this.inventoryContents[i] = null;
        }
    }
}


text:
package com.amazonaws.services.applicationautoscaling.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.applicationautoscaling.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * StepScalingPolicyConfiguration JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StepScalingPolicyConfigurationJsonUnmarshaller implements Unmarshaller<StepScalingPolicyConfiguration, JsonUnmarshallerContext> {

    public StepScalingPolicyConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {
        StepScalingPolicyConfiguration stepScalingPolicyConfiguration = new StepScalingPolicyConfiguration();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("AdjustmentType", targetDepth)) {
                    context.nextToken();
                    stepScalingPolicyConfiguration.setAdjustmentType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("StepAdjustments", targetDepth)) {
                    context.nextToken();
                    stepScalingPolicyConfiguration.setStepAdjustments(new ListUnmarshaller<StepAdjustment>(StepAdjustmentJsonUnmarshaller.getInstance())
                            .unmarshall(context));
                }
                if (context.testExpression("MinAdjustmentMagnitude", targetDepth)) {
                    context.nextToken();
                    stepScalingPolicyConfiguration.setMinAdjustmentMagnitude(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("Cooldown", targetDepth)) {
                    context.nextToken();
                    stepScalingPolicyConfiguration.setCooldown(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("MetricAggregationType", targetDepth)) {
                    context.nextToken();
                    stepScalingPolicyConfiguration.setMetricAggregationType(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return stepScalingPolicyConfiguration;
    }

    private static StepScalingPolicyConfigurationJsonUnmarshaller instance;

    public static StepScalingPolicyConfigurationJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new StepScalingPolicyConfigurationJsonUnmarshaller();
        return instance;
    }
}


text:
    Card name: <[newStateName]>
    (was: <[oldStateName]>)

      <[headers.leftPane]>

      <[headers.rightPane]>

  <codemirror-mergeview options="CODEMIRROR_MERGEVIEW_OPTIONS"
                        left-value="yamlStrs.leftPane"
                        right-value="yamlStrs.rightPane">
  </codemirror-mergeview>

    Click arrows to desynchronize scrolling

  <button class="btn btn-default protractor-test-close-history-state-modal"
          ng-click="cancel()">
    Done
  </button>


text:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"  android:key="preferencescreen">
	<PreferenceCategory android:title="@string/preferredConnection">
		<PreferenceScreen android:title="@string/wlanBasedSettings" android:summary="@string/wlanBasedSettingsDescription" android:key="wifibasedScreen">
			<PreferenceCategory android:title="@string/chooseWLAN" android:key="wifibasedCategory">
			</PreferenceCategory>
		</PreferenceScreen>
	</PreferenceCategory>
	<PreferenceCategory android:visible="false" android:title="Default connection" android:key="defaultCategory">
		<PreferenceScreen android:title="@string/defaultSettings" android:summary="@string/defaultSettingsDescription" android:key="defaultScreen">
			<intent android:action="android.intent.action.MAIN"
                    android:targetPackage="org.musicpd.android"
                    android:targetClass="org.musicpd.android.ConnectionSettings" />
        </PreferenceScreen>
        <!--
		<EditTextPreference
	           android:key="hostname"
	           android:title="@string/host"
	           android:summary="@string/hostDescription"
	           />
	    <EditTextPreference
	           android:key="port"
	           android:title="@string/port"
	           android:defaultValue="6600"
	           android:summary="@string/portDescription"
	           />
	    <EditTextPreference
	           android:key="password"
	           android:title="@string/password"
	           android:defaultValue=""
	           android:password="true"
	           android:summary="@string/passwordDescription" />
	            -->
	</PreferenceCategory>
</PreferenceScreen>


text:
require "bundler/setup"
require "pry"
require "garager"

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
end


text:
Contains the Pop-Up design.

The vowels,numerals,diacritics will pop-up in the top row based on the buttons pressed .

	Advantage :-Simple to design.
			    Simple to Use for the user.

	Disadvantage :- Still an old design.
				    May make the typing slow.


text:
package au.com.agic;

import com.atlassian.bamboo.deployments.results.DeploymentResult;
import com.atlassian.bamboo.deployments.results.service.DeploymentResultService;
import com.atlassian.bamboo.ww2.BambooActionSupport;
import com.opensymphony.webwork.dispatcher.json.JSONException;
import com.opensymphony.webwork.dispatcher.json.JSONObject;
import com.opensymphony.xwork2.Action;

import org.apache.struts2.ServletActionContext;
import org.jetbrains.annotations.NotNull;

import javax.servlet.http.HttpServletRequest;

/**
 * Proxy-class that exposes endpoint to get JSON status for deployment version
 * Version ID is expected to be a value for 'version' query parameter
 *

 * In case of any error, returns json object
 * {
 * status: "error",
 * message: "...."
 * }
 *

 * Otherwise returns the positive result, for example
 * {
 * status: "OK",
 * life_cycle_state: "InProgress",
 * deployment_state: "Unknown"
 * }
 */
public class DeploymentVersionJSON extends BambooActionSupport {

	private static final long serialVersionUID = -122842815102740306L;
	private final DeploymentResultService deploymentResultService;
	private final JSONObject jsonObject = new JSONObject();

	public DeploymentVersionJSON(final DeploymentResultService deploymentResultService) {
		this.deploymentResultService = deploymentResultService;
	}

	private void errorResponse(final String message) throws JSONException {
		jsonObject.put("status", "error");
		jsonObject.put("message", message);
	}

	@NotNull
	@Override
	public JSONObject getJsonObject() throws JSONException {
		HttpServletRequest request = ServletActionContext.getRequest();
		Long versionId = null;

		try {
			versionId = Long.parseLong(request.getParameter("version"), 10);
		} catch (NumberFormatException ex) {
			ex.printStackTrace();
		}

		if (versionId == null) {
			errorResponse("Version Id not specified");
			return jsonObject;
		}

		DeploymentResult deploymentResult = deploymentResultService.getDeploymentResult(versionId);

		if (deploymentResult == null) {
			errorResponse("No deployment result for this Id");
			return jsonObject;
		}

		jsonObject.put("status", "OK");
		jsonObject.put("life_cycle_state", deploymentResult.getLifeCycleState().toString());
		jsonObject.put("deployment_state", deploymentResult.getDeploymentState().toString());

		return jsonObject;
	}

	@Override
	public String doDefault() throws Exception {
		return Action.SUCCESS;
	}
}


text:
const path = require('path');
const express = require('express');
const compression = require('compression');
const favicon = require('serve-favicon');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressHandlebars = require('express-handlebars');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const url = require('url');
const csrf = require('csurf');
// const boot = require('react-bootstrap');

const port = process.env.PORT || process.env.NODE_PORT || 3002;

const dbURL = process.env.MONGODB_URI || 'mongodb://localhost/Domomaker';

mongoose.connect(dbURL, (err) => {
  if (err) {
    console.log('Could not connect to the database');
    throw err;
  }
});

let redisURL = {
  hostname: 'localhost',
  post: 6379,
};

let redisPASS;

if (process.env.REDISCLOUD_URL) {
  redisURL = url.parse(process.env.REDISCLOUD_URL);
  redisPASS = redisURL.auth.split(':')[1];
}

// pull in our routes
const router = require('./router.js');

const app = express();
app.use('/assets', express.static(path.resolve(`${__dirname}/../hosted/`)));
app.use(favicon(`${__dirname}/../hosted/img/favicon.png`));
app.disable('x-powered-by');
app.use(compression());
app.use(bodyParser.urlencoded({
  extended: true,
}));
app.use(session({
  key: 'sessionid',
  store: new RedisStore({
    host: redisURL.hostname,
    port: redisURL.port,
    pass: redisPASS,
  }),
  secret: 'Hello',
  resave: true,
  saveUninitialized: true,
  cookie: {
    httpOnly: true,
  },
}));
app.engine('handlebars', expressHandlebars({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.set('views', `${__dirname}/../views`);
app.use(cookieParser());

app.use(csrf());
app.use((err, req, res, next) => {
  if (err.code !== 'EBADCSRFTOKEN') return next(err);

  console.log('Missing CSRF token');
  return false;
});

router(app);

app.listen(port, (err) => {
  if (err) {
    throw err;
  }
  console.log(`Listening on port ${port}`);
});


text:
require "octokit"

module OpenSesame
  class Member

    def self.organization_name
      OpenSesame.organization_name
    end

    def self.find(member_login)
      return nil unless member_login.present?
      return unless member?(member_login)
      member = find_member(member_login) # Sawyer::Resource
      return unless member # may have been an API error
      members << member
      new(member.attrs)
    end

    def self.find_member(member_login)
      members.detect { |m| m.login == member_login } || begin
        client.user(member_login)
      rescue Octokit::Error => ek
        OpenSesame.logger.info e
      end
    end

    def self.member?(member_login)
      member_logins.include?(member_login) || begin
        client.organization_member?(organization_name, member_login)
      rescue Octokit::ServerError => e
        OpenSesame.logger.info e
      end
    end

    # memoized list of accepted member
    def self.members
      @members ||= []
    end

    def self.member_logins
      members.map(&:login)
    end

    def self.client
      @client ||= begin
        require "faraday-http-cache"
        stack = faraday_builder.new do |builder|
          builder.response :logger, OpenSesame.logger
          builder.use Faraday::HttpCache unless OpenSesame.debug?
          builder.use Octokit::Response::RaiseError
          builder.adapter Faraday.default_adapter
        end
        Octokit.middleware = stack
        Octokit::Client.new(OpenSesame.github_application)
      end
    end

    def self.reset
      @members = nil
    end

    def self.lazy_attr_reader(*attrs)
      attrs.each do |attribute|
        class_eval do
          define_method(attribute) do
            @attributes[attribute] || @attributes[attribute] # allow string or symbol access
          end
        end
      end
    end

    def self.serialize_into_session(member)
      [member.login]
    end

    def self.serialize_from_session(*args)
      login = args.shift
      find(login)
    end

    # Faraday v0.9.0 deprecated Faraday::Builder
    def self.faraday_builder
      Faraday::RackBuilder
    rescue NameError
      Faraday::Builder
    end

    attr_accessor :attributes
    lazy_attr_reader :id, :login, :email

    def initialize(attributes = {})
      @attributes = attributes
    end

    def organization_name
      self.class.organization_name
    end

    def ==(other)
      super || (other.class == self.class && other.id == self.id)
    end

  end
end


text:
package transfer

import (
	"bufio"
	"encoding/gob"

	"github.com/d8x/bftp/storage"
	"github.com/damekr/backer/cmd/bacsrv/db"
	"github.com/damekr/backer/pkg/bftp"
	"github.com/sirupsen/logrus"
)

type RestoreSession struct {
	MainSession *MainSession
}

var logRestore = logrus.WithFields(logrus.Fields{"prefix": "transfer:restore"})

func CreateRestoreSession(mainSession *MainSession) *RestoreSession {
	return &RestoreSession{
		MainSession: mainSession,
	}
}

func (r *RestoreSession) HandleRestoreSession(assetID int) error {
	logRestore.Debugln("Handling incomming TGET transfer type")
	logRestore.Infoln("Client requesting asset ID: ", assetID)
	err := r.sendAssetMetadata(assetID)
	if err != nil {
		log.Errorln("ERROR in sending asset metadata, err: ", err)
		return err
	}
	modifiedAssetMetadata, err := r.receiveModifiedAssetMetadata()
	if err != nil {
		log.Errorln(err)
	}
	log.Debugln("Requesting assets according to metadata: ", modifiedAssetMetadata)

	for i := 0; i < len(modifiedAssetMetadata.FilesMetadata); i++ {

		fileT := new(bftp.FileMetadata)
		fileTEmpty := new(bftp.FileMetadata)

		// Decoding metadata of file to be transferred
		requestedAssetDecoder := gob.NewDecoder(r.MainSession.Conn)
		err := requestedAssetDecoder.Decode(&fileT)
		if err != nil {
			logRestore.Errorln("Could not decode FileMetadata struct, error: ", err)
			fileTEnc := gob.NewEncoder(r.MainSession.Conn)
			if err := fileTEnc.Encode(&fileTEmpty); err != nil {
				logRestore.Errorln("Could not encode empty FileMetadata struct, err: ", err)
				return err
			}
			return err
		}

		logRestore.Debugf("Checking if file %s exists", fileT.LocationOnServer)
		if !storage.CheckIfFileExists(fileT.LocationOnServer) {
			logRestore.Debugf("File: %s does not exist", fileT.LocationOnServer)
			fileTEncNotExist := gob.NewEncoder(r.MainSession.Conn)
			if err := fileTEncNotExist.Encode(&fileTEmpty); err != nil {
				logRestore.Errorln("Could not encode empty FileMetadata struct, err: ", err)
				return err
			}
		}

		// Sending empty as acknowledge
		err = r.MainSession.sendEmptyAckMessage()
		if err != nil {
			return err
		}
		logRestore.Debugln("Handling transfer with sending file to client, file: ", fileT.LocationOnServer)

		// Sending file
		err = r.uploadFile(fileT.LocationOnServer, fileT.FileSize)
		if err != nil {
			logRestore.Errorln("Could not send file, err: ", err.Error())
		}

		// Receiving file acknowledge
		fileSize := new(bftp.FileAcknowledge)
		fileSizeEncoder := gob.NewDecoder(r.MainSession.Conn)
		if err := fileSizeEncoder.Decode(&fileSize); err != nil {
			logRestore.Errorln("Could not decode FileAcknowledge struct, err: ", err)
			return err
		}
		logRestore.Debugln("Received file acknowledge, file size: ", fileSize.Size)
	}
	return nil
}

func (r *RestoreSession) sendAssetMetadata(assetID int) error {
	logRestore.Debugln("Sending asset metadata: ", assetID)
	connEncoder := gob.NewEncoder(r.MainSession.Conn)
	asset, err := db.DB().ReadAssetMetadata(assetID)
	if err != nil {
		log.Errorln("Cannot read asset metadata, err: ", err)
	}
	if err := connEncoder.Encode(&asset); err != nil {
		logRestore.Errorln("Could not encode asset struct, err: ", err)
		return err
	}
	return nil
}

func (r *RestoreSession) receiveModifiedAssetMetadata() (*bftp.AssetMetadata, error) {
	modifiedAssetMetadata := new(bftp.AssetMetadata)
	connDecoder := gob.NewDecoder(r.MainSession.Conn)
	if err := connDecoder.Decode(&modifiedAssetMetadata); err != nil {
		logRestore.Errorln("Could not decode modifiedAsset struct, err: ", err)
		return modifiedAssetMetadata, err
	}
	return modifiedAssetMetadata, nil
}

func (r *RestoreSession) uploadFile(localFilePath string, size int64) error {
	logRestore.Debugln("Starting sending fileReaderCloser: ", localFilePath)
	fileReaderCloser, err := r.MainSession.Storage.ReadFile(localFilePath)
	if err != nil {
		logRestore.Errorln("Cannot create localfile to write, err: ", err)
		return err
	}
	defer fileReaderCloser.Close()
	writer := bufio.NewWriter(r.MainSession.Conn)
	reader := bufio.NewReader(fileReaderCloser)
	var readFromFile int64
	var wroteToConnection int64
	buffer := make([]byte, r.MainSession.Transfer.Buffer)
	if size < int64(r.MainSession.Transfer.Buffer) {
		logRestore.Debugln("Shrinking buffer to file size: ", size)
		buffer = make([]byte, size)
	}
	for {
		read, err := reader.Read(buffer)
		if err != nil {
			logRestore.Errorln("Could not read from fileReaderCloser reader, error: ", err)
			break
		}
		readFromFile += int64(read)
		wrote, err := writer.Write(buffer[:read])
		if err != nil {
			logRestore.Errorln("Could not write to connection buffer, error: ", err)
			break
		}
		wroteToConnection += int64(wrote)
		if wroteToConnection == size {
			logRestore.Debugln("Wrote all data to connection")
			break
		}
	}
	writer.Flush()
	return nil
}


text:
package com.loren.textlibrary.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
 * 视图工具箱
 */
public class ViewUtils {

    private static final String CLASS_NAME_GRID_VIEW
            = "android.widget.GridView";
    private static final String FIELD_NAME_VERTICAL_SPACING
            = "mVerticalSpacing";

    private ViewUtils() {
        throw new AssertionError();
    }

    /**
     * get ListView height according to every children
     *
     * @param view view
     * @return int
     */
    public static int getListViewHeightBasedOnChildren(ListView view) {
        int height = getAbsListViewHeightBasedOnChildren(view);
        ListAdapter adapter;
        int adapterCount;
        if (view != null && (adapter = view.getAdapter()) != null &&
                (adapterCount = adapter.getCount()) > 0) {
            height += view.getDividerHeight() * (adapterCount - 1);
        }
        return height;
    }

    /**
     * get GridView vertical spacing
     *
     * @param view view
     * @return int
     */
    public static int getGridViewVerticalSpacing(GridView view) {
        // get mVerticalSpacing by android.widget.GridView
        Class<?> demo = null;
        int verticalSpacing = 0;
        try {
            demo = Class.forName(CLASS_NAME_GRID_VIEW);
            Field field = demo.getDeclaredField(FIELD_NAME_VERTICAL_SPACING);
            field.setAccessible(true);
            verticalSpacing = (Integer) field.get(view);
            return verticalSpacing;
        } catch (Exception e) {
            /**
             * accept all exception, include ClassNotFoundException, NoSuchFieldException, InstantiationException,
             * IllegalArgumentException, IllegalAccessException, NullPointException
             */
            e.printStackTrace();
        }
        return verticalSpacing;
    }

    /**
     * get AbsListView height according to every children
     *
     * @param view view
     * @return int
     */
    public static int getAbsListViewHeightBasedOnChildren(AbsListView view) {
        ListAdapter adapter;
        if (view == null || (adapter = view.getAdapter()) == null) {
            return 0;
        }

        int height = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View item = adapter.getView(i, null, view);
            if (item instanceof ViewGroup) {
                item.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));
            }
            item.measure(0, 0);
            height += item.getMeasuredHeight();
        }
        height += view.getPaddingTop() + view.getPaddingBottom();
        return height;
    }

    /**
     * set view height
     *
     * @param view view
     * @param height height
     */
    public static void setViewHeight(View view, int height) {
        if (view == null) {
            return;
        }

        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = height;
    }

    /**
     * @param view listview
     */
    public static void setListViewHeightBasedOnChildren(ListView view) {

        setViewHeight(view, getListViewHeightBasedOnChildren(view));
    }

    /**
     * @param view AbsListView
     */
    public static void setAbsListViewHeightBasedOnChildren(AbsListView view) {
        setViewHeight(view, getAbsListViewHeightBasedOnChildren(view));
    }

    /**
     * set SearchView OnClickListener
     *
     * @param v set SearchView OnClickListener
     * @param listener set SearchView OnClickListener
     */
    public static void setSearchViewOnClickListener(View v, OnClickListener listener) {
        if (v instanceof ViewGroup) {
            ViewGroup group = (ViewGroup) v;
            int count = group.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = group.getChildAt(i);
                if (child instanceof LinearLayout ||
                        child instanceof RelativeLayout) {
                    setSearchViewOnClickListener(child, listener);
                }

                if (child instanceof TextView) {
                    TextView text = (TextView) child;
                    text.setFocusable(false);
                }
                child.setOnClickListener(listener);
            }
        }
    }

    /**
     * get descended views from parent.
     *
     * @param <T> 泛型
     * @param parent ViewGroup
     * @param filter Type of views which will be returned.
     * @param includeSubClass Whether returned list will include views which
     * are
     * subclass of filter or not.
     * @return View
     */
    public static <T extends View> List<T> getDescendants(ViewGroup parent, Class<T> filter, boolean includeSubClass) {

        List<T> descendedViewList = new ArrayList<T>();
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            Class<? extends View> childsClass = child.getClass();
            if ((includeSubClass && filter.isAssignableFrom(childsClass)) ||
                    (!includeSubClass && childsClass == filter)) {
                descendedViewList.add(filter.cast(child));
            }
            if (child instanceof ViewGroup) {
                descendedViewList.addAll(
                        getDescendants((ViewGroup) child, filter,
                                includeSubClass));
            }
        }
        return descendedViewList;
    }

    /**
     * 手动测量布局大小
     *
     * @param view 被测量的布局
     * @param width 布局默认宽度
     * @param height 布局默认高度
     * 示例: measureView(view, ViewGroup.LayoutParams.MATCH_PARENT,
     * ViewGroup.LayoutParams.WRAP_CONTENT);
     */
    public static void measureView(View view, int width, int height) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params == null) {
            params = new ViewGroup.LayoutParams(width, height);
        }
        int mWidth = ViewGroup.getChildMeasureSpec(0, 0, params.width);

        int mHeight;
        int tempHeight = params.height;
        if (tempHeight > 0) {
            mHeight = View.MeasureSpec.makeMeasureSpec(tempHeight,
                    View.MeasureSpec.EXACTLY);
        }
        else {
            mHeight = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
        }
        view.measure(mWidth, mHeight);
    }

    //*****设置外边距相关函数*******************************************************************************

    /**
     * 设置View的左侧外边距
     *
     * @param view 要设置外边距的View
     * @param left 左侧外边距
     */
    public static void setMarginLeft(View view, int left) {
        setMargins(view, left, 0, 0, 0);
    }

    /**
     * 设置View的顶部外边距
     *
     * @param view 要设置外边距的View
     * @param top 顶部外边距
     */
    public static void setMarginTop(View view, int top) {
        setMargins(view, 0, top, 0, 0);
    }

    /**
     * 设置View的右侧外边距
     *
     * @param view 要设置外边距的View
     * @param right 右侧外边距
     */
    public static void setMarginRight(View view, int right) {
        setMargins(view, 0, 0, right, 0);
    }

    /**
     * 设置View的底部外边距
     *
     * @param view 要设置外边距的View
     * @param bottom 底部外边距
     */
    public static void setMarginBottom(View view, int bottom) {
        setMargins(view, 0, 0, 0, bottom);
    }

    /**
     * 设置View的外边距(Margins)
     *
     * @param view 要设置外边距的View
     * @param left 左侧外边距
     * @param top 顶部外边距
     * @param right 右侧外边距
     * @param bottom 底部外边距
     */
    public static void setMargins(View view, int left, int top, int right, int bottom) {
        if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view
                    .getLayoutParams();
            p.setMargins(left, top, right, bottom);
            view.requestLayout();       //请求重绘
        }
    }

    /**
     * 获取一个LinearLayout
     *
     * @param context 上下文
     * @param orientation 流向
     * @param width 宽
     * @param height 高
     * @return LinearLayout
     */
    public static LinearLayout createLinearLayout(Context context, int orientation, int width, int height) {
        LinearLayout linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(orientation);
        linearLayout.setLayoutParams(
                new LinearLayout.LayoutParams(width, height));
        return linearLayout;
    }

    /**
     * 获取一个LinearLayout
     *
     * @param context 上下文
     * @param orientation 流向
     * @param width 宽
     * @param height 高
     * @param weight 权重
     * @return LinearLayout
     */
    public static LinearLayout createLinearLayout(Context context, int orientation, int width, int height, int weight) {
        LinearLayout linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(orientation);
        linearLayout.setLayoutParams(
                new LinearLayout.LayoutParams(width, height, weight));
        return linearLayout;
    }

    /**
     * 根据ListView的所有子项的高度设置其高度
     */
    public static void setListViewHeightByAllChildrenViewHeight(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter != null) {
            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }

            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() *
                    (listAdapter.getCount() - 1));
            ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
            listView.setLayoutParams(params);
        }
    }

    /**
     * 将给定视图的高度增加一点
     *
     * @param view 给定的视图
     * @param increasedAmount 增加多少
     */
    public static void addViewHeight(View view, int increasedAmount) {
        ViewGroup.LayoutParams headerLayoutParams
                = (ViewGroup.LayoutParams) view.getLayoutParams();
        headerLayoutParams.height += increasedAmount;
        view.setLayoutParams(headerLayoutParams);
    }

    /**
     * 设置给定视图的宽度
     *
     * @param view 给定的视图
     * @param newWidth 新的宽度
     */
    public static void setViewWidth(View view, int newWidth) {
        ViewGroup.LayoutParams headerLayoutParams
                = (ViewGroup.LayoutParams) view.getLayoutParams();
        headerLayoutParams.width = newWidth;
        view.setLayoutParams(headerLayoutParams);
    }

    /**
     * 将给定视图的宽度增加一点
     *
     * @param view 给定的视图
     * @param increasedAmount 增加多少
     */
    public static void addViewWidth(View view, int increasedAmount) {
        ViewGroup.LayoutParams headerLayoutParams
                = (ViewGroup.LayoutParams) view.getLayoutParams();
        headerLayoutParams.width += increasedAmount;
        view.setLayoutParams(headerLayoutParams);
    }

    /**
     * 获取流布局的底部外边距
     */
    public static int getLinearLayoutBottomMargin(LinearLayout linearLayout) {
        return ((LinearLayout.LayoutParams) linearLayout.getLayoutParams()).bottomMargin;
    }

    /**
     * 设置流布局的底部外边距
     */
    public static void setLinearLayoutBottomMargin(LinearLayout linearLayout, int newBottomMargin) {
        LinearLayout.LayoutParams lp
                = (LinearLayout.LayoutParams) linearLayout.getLayoutParams();
        lp.bottomMargin = newBottomMargin;
        linearLayout.setLayoutParams(lp);
    }

    /**
     * 获取流布局的高度
     */
    public static int getLinearLayoutHiehgt(LinearLayout linearLayout) {
        return ((LinearLayout.LayoutParams) linearLayout.getLayoutParams()).height;
    }

    /**
     * 设置输入框的光标到末尾
     */
    public static final void setEditTextSelectionToEnd(EditText editText) {
        Editable editable = editText.getEditableText();
        Selection.setSelection((Spannable) editable,
                editable.toString().length());
    }

    /**
     * 执行测量,执行完成之后只需调用View的getMeasuredXXX()方法即可获取测量结果
     */
    public static final View measure(View view) {
        ViewGroup.LayoutParams p = view.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight,
                    View.MeasureSpec.EXACTLY);
        }
        else {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
        }
        view.measure(childWidthSpec, childHeightSpec);
        return view;
    }

    /**
     * 获取给定视图的测量高度
     */
    public static final int getMeasuredHeight(View view) {
        return measure(view).getMeasuredHeight();
    }

    /**
     * 获取给定视图的测量宽度
     */
    public static final int getMeasuredWidth(View view) {
        return measure(view).getMeasuredWidth();
    }

    /**
     * 获取视图1相对于视图2的位置,注意在屏幕上看起来视图1应该被视图2包含,但是视图1和视图并不一定是绝对的父子关系也可以是兄弟关系,只是一个大一个小而已
     */
    public static final Rect getRelativeRect(View view1, View view2) {
        Rect childViewGlobalRect = new Rect();
        Rect parentViewGlobalRect = new Rect();
        view1.getGlobalVisibleRect(childViewGlobalRect);
        view2.getGlobalVisibleRect(parentViewGlobalRect);
        return new Rect(childViewGlobalRect.left - parentViewGlobalRect.left,
                childViewGlobalRect.top - parentViewGlobalRect.top,
                childViewGlobalRect.right - parentViewGlobalRect.left,
                childViewGlobalRect.bottom - parentViewGlobalRect.top);
    }

    /**
     * 删除监听器
     */
    @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static final void removeOnGlobalLayoutListener(ViewTreeObserver viewTreeObserver, ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            viewTreeObserver.removeGlobalOnLayoutListener(
                    onGlobalLayoutListener);
        }
        else {
            viewTreeObserver.removeOnGlobalLayoutListener(
                    onGlobalLayoutListener);
        }
    }

    /**
     * 缩放视图
     */
    public static void zoomView(View view, float scaleX, float scaleY, Point originalSize) {
        int width = (int) (originalSize.x * scaleX);
        int height = (int) (originalSize.y * scaleY);
        ViewGroup.LayoutParams viewGroupParams = view.getLayoutParams();
        if (viewGroupParams != null) {
            viewGroupParams.width = width;
            viewGroupParams.height = height;
        }
        else {
            viewGroupParams = new ViewGroup.LayoutParams(width, height);
        }
        view.setLayoutParams(viewGroupParams);
    }

    /**
     * 缩放视图
     */
    public static void zoomView(View view, float scaleX, float scaleY) {
        zoomView(view, scaleX, scaleY,
                new Point(view.getWidth(), view.getHeight()));
    }

    /**
     * 缩放视图
     *
     * @param scale 比例
     */
    public static void zoomView(View view, float scale, Point originalSize) {
        zoomView(view, scale, scale, originalSize);
    }

    /**
     * 缩放视图
     */
    public static void zoomView(View view, float scale) {
        zoomView(view, scale, scale,
                new Point(view.getWidth(), view.getHeight()));
    }
}


text:
import os
import os.path
import sys
import tempfile
import shutil
import subprocess
import argparse
import platform

"""
This is the main driver for the compiler.

It invokes the preprocessor, the assembler, and linker. Will be
compatible enough with gcc enough so that is can be used in configure scripts
etc.
"""

argparser = argparse.ArgumentParser()

argparser.add_argument('input',help='source files')
argparser.add_argument('-O','--Optimization',default=0,type=int,help='Optimization level')
argparser.add_argument('-o','--output',default=None,help='output file')
argparser.add_argument('-S',action='store_true',help='assemble only, no link')
argparser.add_argument('-v','--verbose',action='store_true',help='verbose')

args = None

def getCompilerBasePath():
    return os.path.dirname(os.path.abspath(__file__))

def vprint(s):
    if args.verbose:
        print s

def preprocessSource(infname,outfname):
    subprocess.check_call( [
                            sys.executable,
                            getCompilerBasePath()+'/cpp.py',
                            '-I'+getCompilerBasePath() + '/include/',
                            infname,
                            '-o',outfname,
                            ])
def compileSource(infname,outfname):

    cmd = [
            sys.executable,
            getCompilerBasePath()+'/cc1.py',
            infname,
            '--output',outfname,
            ]
    if args.Optimization > 0:
        cmd += ['--iropt']

    subprocess.check_call(cmd)

def assembleSourceFile(infname,outfname):

    mflag = '-m32'

    cmd = [
            'gcc', '-c',mflag,
            infname,
            '-o',outfname,
            ]
    subprocess.check_call(cmd)

def linkExecuteable(objectfile,outfname):
    mflag = '-m32'
    cmd = [
        'gcc',
        mflag,
        objectfile,
        '-o',outfname,
        ]
    subprocess.check_call(cmd)

def main():
    global args
    args = argparser.parse_args()

    d = tempfile.mkdtemp()
    vprint("created temp dir %s" % d)
    fname = args.input
    base = os.path.basename(fname)[:-2]
    preprocessed = d+('/%s.preprocessed.c'%base)
    assembly = d+('/%s.s'%base)
    objectfile = d+('/%s.o'%base)
    ofile = args.output

    try:
        vprint("preprocessing source...")
        preprocessSource(fname,preprocessed)
        vprint("compiling file preprocessed source...")
        compileSource(preprocessed,assembly)
        vprint("assembling...")
        assembleSourceFile(assembly,objectfile)
        if args.S:
            if ofile == None:
                ofile = base + '.s'
            shutil.copy(assembly,ofile)
            vprint("Done!")
        else:
            vprint("linking...")
            if ofile == None:
                ofile = './a.out'
            linkExecuteable(objectfile,ofile)
            vprint("removing temp dir %s..." % d)
            shutil.rmtree(d)
            vprint("Done!")
    except subprocess.CalledProcessError:
        vprint("removing temp dir %s..." % d)
        shutil.rmtree(d)
        sys.stderr.write("ERROR terminating...\n")
        sys.exit(1)

if __name__ == '__main__':
    main()


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>AngularJS Cart Coding Challenge</title>

Cartified

Check console for output

		Add
		Remove
		Clear
		Change Quantity
		Console Output
		Unbind Custom Event


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const child_process = require("child_process");
const TeventDispatcher_1 = require("../events/TeventDispatcher");
const Promise = require("bluebird");
class TwindowsServiceManager extends TeventDispatcher_1.TeventDispatcher {
    constructor(args = null) {
        super();
        this.startingService = false;
        this.stoppingService = false;
        this.logger = app.getLogger("TwindowsServiceManager");
    }
    getServiceState(name) {
        return this._execCommand("sc query " + name + " | findstr STATE").then(function (result) {
            result.stdout = result.stdout.trim().replace(/\s+/g, " ");
            return result.stdout.split(" ")[3];
        }.bind(this));
    }
    _execCommand(cmd) {
        return new Promise(function (resolve, reject) {
            var child = child_process.exec(cmd);
            child.unref();
            var r = {
                pid: child.pid,
                stdout: "",
                stderr: "",
                exitCode: -1
            };
            var pid = child.pid;
            child.stdout.on('data', function (data) {
                r.stdout += data;
            }.bind(this));
            child.stderr.on('data', function (data) {
                r.stderr += data;
            }.bind(this));
            child.on('error', function (error) {
                reject(error);
            }.bind(this));
            child.on('exit', function (code, signal) {
                r.exitCode = code;
                resolve(r);
            }.bind(this));
        }.bind(this));
    }
    startService(name) {
        this.startingService = true;
        this.logger.warn("start service " + name + " ....");
        return this._execCommand("net start " + name)
            .then(function (result) {
            this.startingService = false;
            if (result.exitCode > 0) {
                throw new Error("startService '" + name + "': " + result.stdout + " " + result.stderr);
            }
            else {
                this.logger.info("Service " + name + " démarré");
                return result;
            }
        }.bind(this))
            .catch(function (err) {
            this.startingService = false;
            throw new Error(err.toString());
        }.bind(this));
    }
    stopService(name) {
        this.stoppingService = true;
        this.logger.warn("stop service " + name + " ....");
        return this._execCommand("net stop " + name)
            .then(function (result) {
            this.stoppingService = false;
            if (result.exitCode > 0) {
                throw new Error("stopService '" + name + "': " + result.stdout + " " + result.stderr);
            }
            else {
                this.logger.info("Service " + name + " arrêté");
                return result;
            }
        }.bind(this))
            .catch(function (err) {
            this.stoppingService = false;
            throw new Error(err.toString());
        }.bind(this));
    }
}
exports.TwindowsServiceManager = TwindowsServiceManager;
//# sourceMappingURL=TwindowsServiceManager.js.map


text:
require "chef/resource/lwrp_base"

class Chef::Resource::GoogleKeyPair < Chef::Resource::LWRPBase
  provides :google_key_pair

  actions :create, :destroy
  default_action :create

  # Private key to use as input (will be generated if it does not exist)
  attribute :private_key_path, :kind_of => String
  # Public key to use as input (will be generated if it does not exist)
  attribute :public_key_path, :kind_of => String
  # List of parameters to the private_key resource used for generation of the key
  attribute :private_key_options, :kind_of => Hash

  # This applies to both the local keys and the remote key
  attribute :allow_overwrite, :kind_of => [TrueClass, FalseClass], :default => false

  # TODO: add a `user` attribute which sets the user to login with the key
  # GCE uses the key user to create a user on the instance, which may duplicate
  # some logic the user is trying to do with their chef recipes

  def after_created
    # We default these here so load_current_resource can diff
    if private_key_path.nil?
      private_key_path ::File.join(driver.config[:private_key_write_path], "google_default")
    elsif Pathname.new(private_key_path).relative?
      private_key_path ::File.join(driver.config[:private_key_write_path], private_key_path)
    end
    # TODO you don't actually need to write the private key to disc if it isn't provided
    # it can be read from the private key, but this code update needs testing
    if public_key_path.nil?
      public_key_path ::File.join(driver.config[:private_key_write_path], "google_default.pub")
    elsif Pathname.new(public_key_path).relative?
      public_key_path ::File.join(driver.config[:private_key_write_path], public_key_path)
    end
  end

  # TODO introduce base class and add this as attribute, like AWS does
  # Ideally, we won't be creating lots of copies of the same driver object, but it is okay
  # if we do - they aren't singletons
  def driver
    run_context.chef_provisioning.driver_for(run_context.chef_provisioning.current_driver)
  end
end


text:
from concurrent.futures.thread import ThreadPoolExecutor
import webview
from .util import run_test, assert_js

def test_expose_single():
    window = webview.create_window('JSBridge test', html='TEST')
    window.expose(get_int)
    run_test(webview, window, expose_single)

def test_expose_multiple():
    window = webview.create_window('JSBridge test', html='TEST')
    window.expose(get_int, get_float)
    run_test(webview, window, expose_multiple)

def test_expose_runtime():
    window = webview.create_window('JSBridge test', html='TEST')
    run_test(webview, window, expose_runtime)

def test_override():
    api = Api()
    window = webview.create_window('JSBridge test', js_api=api)
    window.expose(get_int)
    run_test(webview, window, expose_override)

def get_int():
    return 420

def get_float():
    return 420.420

class Api:
    def get_int(self):
        return 421

def expose_single(window):
    assert_js(window, 'get_int', 420)

def expose_multiple(window):
    assert_js(window, 'get_int', 420)
    assert_js(window, 'get_float', 420.420)

def expose_runtime(window):
    window.expose(get_int, get_float)
    assert_js(window, 'get_int', 420)

def expose_override(window):
    assert_js(window, 'get_int', 420)


text:
package com.authcore.response.errors;

/**
 * Created by imreleventeracz on 26/03/17.
 */
public class HttpError extends Exception {
    public int status;
    public HttpError(String msg, int status) {
        super(msg);
        this.status = status;
    }
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="com.livescribe.frameworks.orm.fb.UserContact" table="UserContact">

		<id name="primaryKey" column="primaryKey" type="binary">
			<generator class="assigned"/>
		</id>

		<property name="contactProfileKey"	column="contactProfileKey"	type="binary" />
		<property name="email"				column="email"				type="string"	length="128" />
		<property name="metaInfo"			column="metaInfo"			type="clob" />
		<property name="nickName"			column="nickName"			type="string"	length="128" />
		<property name="ownerProfileKey"	column="ownerProfileKey"	type="binary" />

	</class>
</hibernate-mapping>


text:
package uk.artdude.tweaks.twisted.common.blocks;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import uk.artdude.tweaks.twisted.common.configuration.ConfigurationHelper;
import uk.artdude.tweaks.twisted.common.tileentity.TileEntityLiquidVoid;
import uk.artdude.tweaks.twisted.common.util.Strings;

import static uk.artdude.tweaks.twisted.api.TTCBlocks.liquidVoid;

public class TTBlocks {

    /**
     * This is the main function call to this class.
     */
    public static void init() {
        // Initialize the blocks to add to the game.
        initializeBlocks();
    }

    /**
     * This function starts the initialization of blocks to the game.
     */
    public static void initializeBlocks() {
        // Check to see if the user has enabled the Liquid Void.
        if (ConfigurationHelper.enableLiquidVoid) {
            // Register the block to the game.
            liquidVoid = registerBlock(new LiquidVoid().setBlockName(Strings.blockLiquidVoid));
            // Register the TileEntity to the game.
            GameRegistry.registerTileEntity(TileEntityLiquidVoid.class, Strings.blockLiquidVoid);
        }
    }

    /**
     * This function allows you to add blocks easily.
     * @param block The block you want to register to the game.
     */
    public static Block registerBlock(Block block) {
        // Register the block to the game.
        GameRegistry.registerBlock(block, block.getLocalizedName().replace("tile.", ""));
        // Return the block back.
        return block;
    }
}


text:
<com.tle.beans.mime.MimeEntry>
  <id>6071</id>
  <institution>
    <id>41</id>
    <uniqueId>0</uniqueId>
    <quota>0.0</quota>
    <enabled>true</enabled>
  </institution>
  <extensions class="list">
    <string>html</string>
    <string>htm</string>
    <string>shtml</string>
  </extensions>
  <type>text/html</type>
  <description>HTML Document</description>
  <attributes>
    <entry>
      <string>PluginIconPath</string>
      <string>icons/html.png</string>
    </entry>
  </attributes>
</com.tle.beans.mime.MimeEntry>


text:
package io.doov.core.dsl.field.types;

import io.doov.core.dsl.field.BaseFieldInfo;
import io.doov.core.dsl.impl.DefaultCondition;
import io.doov.core.dsl.impl.NumericCondition;
import io.doov.core.dsl.lang.StepCondition;

/**
 * Base interface for numeric field info.
 * <p>
 * It contains default methods for common checks, which are calls to methods on {@link NumericCondition}.
 *
 * @param <N> the type of the field value
 */
public interface NumericFieldInfo<N extends Number> extends BaseFieldInfo<N> {

    /**
     * See {@link NumericCondition#lesserThan(Number)}
     *
     * @param value the right side value
     * @return the step condition
     * @see NumericCondition#lesserThan(Number)
     */
    default StepCondition lesserThan(N value) {
        return getNumericCondition().lesserThan(value);
    }

    /**
     * See {@link NumericCondition#lesserThan(NumericFieldInfo)}
     *
     * @param value the right side value
     * @return the step condition
     * @see NumericCondition#lesserThan(NumericFieldInfo)
     */
    default StepCondition lesserThan(NumericFieldInfo<N> value) {
        return getNumericCondition().lesserThan(value);
    }

    /**
     * See {@link NumericCondition#lesserOrEquals(Number)}
     *
     * @param value the right side value
     * @return the step condition
     * @see NumericCondition#lesserOrEquals(Number)
     */
    default StepCondition lesserOrEquals(N value) {
        return getNumericCondition().lesserOrEquals(value);
    }

    /**
     * See {@link NumericCondition#lesserOrEquals(NumericFieldInfo)}
     *
     * @param value the right side value
     * @return the step condition
     * @see NumericCondition#lesserOrEquals(NumericFieldInfo)
     */
    default StepCondition lesserOrEquals(NumericFieldInfo<N> value) {
        return getNumericCondition().lesserOrEquals(value);
    }

    /**
     * See {@link NumericCondition#greaterThan(Number)}
     *
     * @param value the right side value
     * @return the step condition
     * @see NumericCondition#greaterThan(Number)
     */
    default StepCondition greaterThan(N value) {
        return getNumericCondition().greaterThan(value);
    }

    /**
     * See {@link NumericCondition#greaterThan(NumericFieldInfo)}
     *
     * @param value the right side value
     * @return the step condition
     * @see NumericCondition#greaterThan(NumericFieldInfo)
     */
    default StepCondition greaterThan(NumericFieldInfo<N> value) {
        return getNumericCondition().greaterThan(value);
    }

    /**
     * See {@link NumericCondition#greaterOrEquals(Number)}
     *
     * @param value the right side value
     * @return the step condition
     * @see NumericCondition#greaterOrEquals(Number)
     */
    default StepCondition greaterOrEquals(N value) {
        return getNumericCondition().greaterOrEquals(value);
    }

    /**
     * See {@link NumericCondition#greaterOrEquals(NumericFieldInfo)}
     *
     * @param value the right side value
     * @return the step condition
     * @see NumericCondition#greaterOrEquals(NumericFieldInfo)
     */
    default StepCondition greaterOrEquals(NumericFieldInfo<N> value) {
        return getNumericCondition().greaterOrEquals(value);
    }

    /**
     * See {@link NumericCondition#between(Number, Number)}
     *
     * @param minIncluded the min value included
     * @param maxExcluded the max value excluded
     * @return the step condition
     * @see NumericCondition#between(Number, Number)
     */
    default StepCondition between(N minIncluded, N maxExcluded) {
        return getNumericCondition().between(minIncluded, maxExcluded);
    }

    /**
     * See {@link NumericCondition#between(NumericFieldInfo, NumericFieldInfo)}
     *
     * @param minIncluded the min value included
     * @param maxExcluded the max value excluded
     * @return the step condition
     * @see NumericCondition#between(NumericFieldInfo, NumericFieldInfo)
     */
    default StepCondition between(NumericFieldInfo<N> minIncluded, NumericFieldInfo<N> maxExcluded) {
        return getNumericCondition().between(minIncluded, maxExcluded);
    }

    /**
     * See {@link NumericCondition#times(int)}
     *
     * @param multiplier the multiplier
     * @return the step condition
     * @see NumericCondition#times(int)
     */
    default NumericCondition<N> times(int multiplier) {
        return getNumericCondition().times(multiplier);
    }

    /**
     * See {@link NumericCondition#when(StepCondition)}
     *
     * @param condition the condition to evaluate
     * @return the step condition
     * @see NumericCondition#when(StepCondition)
     */
    default NumericCondition<N> when(StepCondition condition) {
        return getNumericCondition().when(condition);
    }

    /**
     * Returns a new numeric condition that will use this as a value.
     *
     * @return the numeric condition
     */
    NumericCondition<N> getNumericCondition();

    @Override
    default NumericCondition<N> getDefaultCondition() {
        return getNumericCondition();
    }
}


text:
package com.vaadin.tests.minitutorials.v7a1;

import com.vaadin.server.Page.UriFragmentChangedEvent;
import com.vaadin.server.Page.UriFragmentChangedListener;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

/**
 * Mini tutorial code for
 * https://vaadin.com/wiki/-/wiki/Main/Using%20URI%20fragments
 *
 * @author Vaadin Ltd
 * @since 7.0.0
 */
public class UsingUriFragments extends UI {

    private VerticalLayout layout;

    @Override
    protected void init(VaadinRequest request) {
        layout = new VerticalLayout();
        layout.setMargin(true);
        setContent(layout);

        Label label = new Label(
                "Hello, your fragment is " + getPage().getUriFragment());
        layout.addComponent(label);

        // React to fragment changes
        getPage().addUriFragmentChangedListener(
                new UriFragmentChangedListener() {
                    @Override
                    public void uriFragmentChanged(
                            UriFragmentChangedEvent source) {
                        handleFragment(source.getUriFragment());
                    }
                });

        // Handle the fragment received in the initial request
        handleFragment(getPage().getUriFragment());

        layout.addComponent(
                new Button("Show and set fragment", new Button.ClickListener() {
                    @Override
                    public void buttonClick(ClickEvent event) {
                        handleFragment(getPage().getUriFragment());
                        getPage().setUriFragment("customFragment");
                    }
                }));
    }

    private void handleFragment(String uriFragment) {
        layout.addComponent(new Label("Got new fragment: " + uriFragment));
    }

}


text:
package org.databene.commons.iterator;

import org.databene.commons.HeavyweightIterable;

/**
 * Special sub type of {@link Iterable} which creates {@link TabularIterator}s.
 * Created: 26.01.2012 17:59:58
 * @since 0.5.14
 * @author Volker Bergmann
 */
public interface TabularIterable extends HeavyweightIterable<Object[]> {
	@Override
	TabularIterator iterator();
}


text:
export default function(handles, image = {}) {
  // Calculate the long axis length
  const dx =
    (handles.start.x - handles.end.x) * (image.columnPixelSpacing || 1);
  const dy = (handles.start.y - handles.end.y) * (image.rowPixelSpacing || 1);
  const length = Math.sqrt(dx * dx + dy * dy) || 0;

  // Calculate the short axis length
  const wx =
    (handles.perpendicularStart.x - handles.perpendicularEnd.x) *
    (image.columnPixelSpacing || 1);
  const wy =
    (handles.perpendicularStart.y - handles.perpendicularEnd.y) *
    (image.rowPixelSpacing || 1);
  const width = Math.sqrt(wx * wx + wy * wy) || 0;

  return {
    longestDiameter: length.toFixed(1),
    shortestDiameter: width.toFixed(1),
  };
}


text:
package org.eclipse.rdf4j.query.parser.sparql.ast;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class UnicodeEscapeStream extends JavaCharStream {

	public UnicodeEscapeStream(String string, int tabSize) {
		super(new StringReader(string), 1, 1, string.length());
		setTabSize(tabSize);
	}

	public UnicodeEscapeStream(Reader dstream, int tabSize) {
		super(dstream);
		setTabSize(tabSize);
	}

	@Override
	public char readChar() throws IOException {
		if (inBuf > 0) {
			--inBuf;

			if (++bufpos == bufsize) {
				bufpos = 0;
			}

			return buffer[bufpos];
		}

		char c;

		if (++bufpos == available) {
			AdjustBuffSize();
		}

		if ((buffer[bufpos] = c = ReadByte()) == '\\') {
			UpdateLineColumn(c);

			int backSlashCnt = 1;

			for (;;) // Read all the backslashes
			{
				if (++bufpos == available) {
					AdjustBuffSize();
				}

				try {
					if ((buffer[bufpos] = c = ReadByte()) != '\\') {
						UpdateLineColumn(c);
						// found a non-backslash char.
						if ((c == 'u' || c == 'U') && ((backSlashCnt & 1) == 1)) {
							if (--bufpos < 0) {
								bufpos = bufsize - 1;
							}

							break;
						}

						backup(backSlashCnt);
						return '\\';
					}
				} catch (java.io.IOException e) {
					// We are returning one backslash so we should only backup (count-1)
					if (backSlashCnt > 1) {
						backup(backSlashCnt - 1);
					}

					return '\\';
				}

				UpdateLineColumn(c);
				backSlashCnt++;
			}

			// Here, we have seen an odd number of backslash's followed by a 'u'
			try {
				if (c == 'u') {
					buffer[bufpos] = c = (char) (hexval(ReadByte()) << 12 | hexval(ReadByte()) << 8
							| hexval(ReadByte()) << 4 | hexval(ReadByte()));
					column += 4;
				} else if (c == 'U') {
					String hex = new String(new char[] { ReadByte(), ReadByte(), ReadByte(), ReadByte(), ReadByte(),
							ReadByte(), ReadByte(), ReadByte() });
					int cp = Integer.parseInt(hex, 16);
					char[] chrs = Character.toChars(cp); // length of 1 or 2
					buffer[bufpos] = c = chrs[0];
					if (chrs.length > 1) {
						if (++bufpos == available) {
							AdjustBuffSize();
						}
						buffer[bufpos] = chrs[1];
						UpdateLineColumn(c);
						backup(1);
					}
					column += hex.length();
				}
			} catch (java.io.IOException | IllegalArgumentException e) {
				throw new Error("Invalid escape character at line " + line + " column " + column + ".", e);
			}

			if (backSlashCnt == 1) {
				return c;
			} else {
				backup(backSlashCnt - 1);
				return '\\';
			}
		} else {
			UpdateLineColumn(c);
			return c;
		}
	}
}


text:
package org.uberfire.client.mvp;

import static org.uberfire.commons.validation.PortablePreconditions.*;

import org.uberfire.client.annotations.WorkbenchPopup;
import org.uberfire.client.workbench.widgets.popup.PopupView;

import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.ui.IsWidget;

/**
 * Implementation of behaviour common to all popup activities. Concrete implementations are typically not written by
 * hand; rather, they are generated from classes annotated with {@link WorkbenchPopup}.
 */
public abstract class AbstractPopupActivity extends AbstractActivity implements PopupActivity {

    private final PopupView popup;

    /**
     * Interlock to prevent a call back into PlaceManager.closePlace() when this activity is already in the process of
     * closing.
     */
    private boolean placeManagerIsClosingUs = false;

    /**
     * Interlock to prevent a call back into PopupView.hide() when the view is already in the process of hiding.
     */
    private boolean popupAlreadyHiding = false;

    /**
     * MVP constructor that allows caller to provide the PopupView instance.
     */
    public AbstractPopupActivity( final PlaceManager placeManager, final PopupView popupView ) {
        super( placeManager );
        popup = checkNotNull( "popupView", popupView );
    }

    /**
     * Used by generated PopupActivity subclasses.
     */
    public AbstractPopupActivity( final PlaceManager placeManager ) {
        // XXX this class (an MVP Presenter) should not be creating its own view instance!
        this( placeManager, new PopupView() );
    }

    @Override
    public abstract String getTitle();

    @Override
    public IsWidget getTitleDecoration() {
        return null;
    }

    @Override
    public abstract IsWidget getWidget();

    @Override
    public void onOpen() {
        super.onOpen();

        popup.addCloseHandler( new CloseHandler<PopupView>() {
            @Override
            public void onClose( CloseEvent<PopupView> event ) {
                if ( !placeManagerIsClosingUs ) {
                    try {
                        popupAlreadyHiding = true;
                        placeManager.closePlace( place );
                    } finally {
                        popupAlreadyHiding = false;
                    }
                }
            }
        } );

        final IsWidget widget = getWidget();

        popup.setContent( widget );
        popup.setTitle( getTitle() );
        popup.show();
    }

    @Override
    public void onClose() {
        super.onClose();
        if ( !popupAlreadyHiding ) {
            try {
                placeManagerIsClosingUs = true;
                popup.hide();
            } finally {
                placeManagerIsClosingUs = false;
            }
        }
    }

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

}