text:
using namespace HoneycombEngine;
using namespace HoneycombTest::Components;
using Honeycomb::Debug::Logger;
using Honeycomb::Render::Renderer;
using Honeycomb::Render::Deferred::DeferredRenderer;

namespace HoneycombTest {
	void TestGame::input() {

	}

	void TestGame::render() {

	}

	void TestGame::start() {
		// Build the Skybox and send to the Renderer
		std::string skyboxDir =
			"../Honeycomb GE/res/textures/default/aurora_skybox/";
		CubemapTextureTarget targets[6] = {
			CubemapTextureTarget::RIGHT,
			CubemapTextureTarget::LEFT,
			CubemapTextureTarget::TOP,
			CubemapTextureTarget::BOTTOM,
			CubemapTextureTarget::BACK,
			CubemapTextureTarget::FRONT
		};
		ImageIO skyboxTex[6] = {
			ImageIO(skyboxDir + "right.bmp"),
			ImageIO(skyboxDir + "left.bmp"),
			ImageIO(skyboxDir + "top.bmp"),
			ImageIO(skyboxDir + "bottom.bmp"),
			ImageIO(skyboxDir + "back.bmp"),
			ImageIO(skyboxDir + "front.bmp")
		};
		auto skybox = Cubemap::newCubemapShared();
		skybox->setFacesDataIO(6, targets, skyboxTex);
		Renderer::getRenderer()->setSkybox(skybox);

		// Import all of the mesh game objects and construct them
		this->car = GameObjectFactory::getFactory().
			newGameObject(Model("../Test Game/res/models/car.fbx"));
		this->cube = GameObjectFactory::getFactory().
			newGameObject(Model("../Test Game/res/models/brick-cube/cube.fbx"));
		this->plane = GameObjectFactory::getFactory().newPlane();

		// Give the plane a textured material
		auto colorMaterial =
			this->plane->getComponent<MeshRenderer>().getMaterials()[0];
		auto colorTexture = Texture2D::newTexture2DShared();
		colorTexture->
			setImageDataIO(ImageIO("../Test Game/res/textures/colors.bmp"));
		colorTexture->setAnisotropicFiltering(8);
		colorMaterial->getSampler2Ds().setValue("albedoTexture.sampler",
			colorTexture);
		colorMaterial->getFloats().setValue("shininess", 128.0F);
		colorMaterial->getVector2fs().setValue("globalTiling",
			Vector2f(10.0F, 10.0F));
		colorMaterial->getVector3fs().setValue("diffuseColor",
			Vector3f(1, 1, 0));
		this->plane->getComponent<MeshRenderer>().getMaterials().clear();
		this->plane->getComponent<MeshRenderer>().addMaterial(colorMaterial);

		// Give Suzanne an Input Transformable Component
		std::unique_ptr<InputTransformable> suzInputTranfs = std::make_unique<InputTransformable>(
			GameInput::KEY_CODE_UP, GameInput::KEY_CODE_DOWN,
			GameInput::KEY_CODE_LEFT, GameInput::KEY_CODE_RIGHT,
			GameInput::KEY_CODE_COMMA, GameInput::KEY_CODE_PERIOD,
			GameInput::KEY_CODE_I, GameInput::KEY_CODE_K,
			GameInput::KEY_CODE_J, GameInput::KEY_CODE_L,
			GameInput::KEY_CODE_U, GameInput::KEY_CODE_O,
			GameInput::KEY_CODE_Z, GameInput::KEY_CODE_X,
			GameInput::KEY_CODE_C, GameInput::KEY_CODE_V,
			GameInput::KEY_CODE_B, GameInput::KEY_CODE_N,
			3.5F, 3.5F, 3.5F, Space::GLOBAL);
		std::unique_ptr<InputTransformable> suzInputTransf2 = suzInputTranfs->clone();
		auto suzInputTransf3 = suzInputTransf2->clone();
		this->car->addComponent(std::move(suzInputTranfs));

		// Construct a default Ambient and Directional Light; decrease the
		// intensity of the lights so they don't overwhelm the scene
		this->ambient = GameObjectFactory::getFactory().newAmbientLight();
		this->directional = GameObjectFactory::getFactory().newDirectionalLight();
		this->ambient->getComponent<AmbientLight>().setIntensity(0.01F);
		this->directional->getComponents<DirectionalLight>()[0].get().
			setIntensity(0.25F);
		this->directional->getComponent<DirectionalLight>().
			getShadow().setShadowType(ShadowType::SHADOW_VARIANCE_AA);
		this->directional->getComponent<DirectionalLight>().
			getShadow().setIntensity(1.0F);
		this->directional->addComponent(std::move(suzInputTransf2));

		// Construct a default Camera and give it a default Input Transformable
		this->camera = GameObjectFactory::getFactory().newCamera();
		auto camTransf = std::make_unique<InputTransformable>();
		this->camera->addComponent(std::move(camTransf));
		this->camera->onStart();

		// Scale and position the Game Objects
		this->plane->getComponents<Transform>()[0].get().setScale(
			Vector3f(15.0F, 1.0F, 25.0F));
		this->cube->getComponents<Transform>()[0].get().setTranslation(
			Vector3f(-2.5F, 1.0F, -5.0F));
		this->car->getComponents<Transform>()[0].get().setTranslation(
			Vector3f(-3.0F, 1.36F, 8.0F));
		this->car->getComponent<Transform>().setScale(
			Vector3f(2.0F, 2.0F, 2.0F));
		this->directional->getComponent<Transform>().rotate(
			Vector3f::getGlobalRight(), -PI / 4);
		this->directional->getComponent<DirectionalLight>().getShadow().setShadowType(ShadowType::SHADOW_NONE);

		// Construct a left and right spotlight for the front of the car and
		// add to the car (similar to headlights).
		auto carHeadlightLPtr = GameObjectFactory::getFactory().newSpotLight();
		auto carHeadlightRPtr = GameObjectFactory::getFactory().newSpotLight();
		carHeadlightLPtr->setName("HeadlightL");
		carHeadlightRPtr->setName("HeadlightR");
		auto &carHeadlightL = this->car->addChild(std::move(carHeadlightLPtr));
		auto &carHeadlightR = this->car->addChild(std::move(carHeadlightRPtr));
		carHeadlightL.getComponent<SpotLight>().setAttenuation(
			Attenuation(1.0F, 0.0F, 0.05F));
		carHeadlightL.getComponent<SpotLight>().getRange() = 15.0F;
		carHeadlightL.getComponent<SpotLight>().getAngle() = PI / 2;
		carHeadlightL.getComponent<SpotLight>().setIntensity(8.0F);
		carHeadlightL.getComponent<SpotLight>().getShadow().setIntensity(1.0F);
		carHeadlightL.getComponent<Transform>().setTranslation(
			Vector3f(-4.391F, 0.709F, 3.321F));
		carHeadlightR.getComponent<SpotLight>().setAttenuation(
			Attenuation(1.0F, 0.0F, 0.05F));
		carHeadlightR.getComponent<SpotLight>().getRange() = 15.0F;
		carHeadlightR.getComponent<SpotLight>().getAngle() = PI / 2;
		carHeadlightR.getComponent<SpotLight>().setIntensity(8.0F);
		carHeadlightR.getComponent<SpotLight>().getShadow().setIntensity(1.0F);
		carHeadlightR.getComponent<Transform>().setTranslation(
			Vector3f(-1.391F, 0.709F, 3.321F));
		carHeadlightL.getComponent<SpotLight>().getShadow().setShadowType(ShadowType::SHADOW_NONE);
		carHeadlightR.getComponent<SpotLight>().getShadow().setShadowType(ShadowType::SHADOW_NONE);

		this->car->getChild("Body").getComponents<MeshRenderer>()[0].get().
			getMaterials()[1]->getVector3fs().setValue(
			"albedoColor", Vector3f(1.0F, 1.0F, 1.0F));

		auto test1 = this->car->getComponentsInheritedInDescendants<BaseLight>();
		auto test2 = this->car->getChild("HeadlightL").getComponentsInheritedInAncestors<BaseLight>();
		auto test3 = this->car->getComponentsInherited<GameComponent>();
		this->car->setName("Car Root");

		// Add all of the initialized objects to the Game Scene hierarchy
		this->carPtr = &this->gameScene.addChild(std::move(this->car));
		this->gameScene.addChild(std::move(this->cube));
		this->gameScene.addChild(std::move(this->plane));
		this->gameScene.addChild(std::move(this->ambient));
		this->gameScene.addChild(std::move(this->directional));
		this->gameScene.addChild(std::move(this->camera));

		// these must throw exceptions:
		//carHeadlightL.addComponent<Transform>();									// disallow multiple
		//carHeadlightL.removeComponent(&carHeadlightL.getComponent<Transform>());  // permanent component

		// Start the Game Scene and set it as the active scene
		this->gameScene.onStart();

		auto &imrunningoutofnames = this->gameScene.getChild("Car Root");

		GameWindow::getGameWindow()->setWindowTitle("Honeycomb Test Game");
	}

	void TestGame::stop() {
		this->gameScene.onStop();
	}

	void TestGame::update() {
		float LO = -10.0F;
		float HI = 10.0F;
		float LO2 = 0.0F;
		float HI2 = 2.0F;

		if (GameInput::getGameInput()->getKeyReleased(GameInput::KEY_CODE_1)) {
			auto light = GameObjectFactory::getFactory().newPointLight();
			light->getComponent<Transform>().setTranslation(
				Vector3f(LO + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI - LO))),
					LO2 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI2 - LO2))),
					LO + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI - LO)))));
			light->getComponent<PointLight>().setIntensity(5.0F);

			this->gameScene.addChild(std::move(light));
		} else if (GameInput::getGameInput()->getKeyReleased(GameInput::KEY_CODE_2)) {
			this->gameScene.removeChild(&this->gameScene.getChild("Point Light"));
		}

	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">

<document>

    <title>POST pig </title>

   <title>Description</title>

Create and queue a Pig job.

   <title>URL</title>

http://www.myserver.com/templeton/v1/pig

   <title>Parameters</title>

Name	Description	Required?	Default

execute
        String containing an entire, short pig program to run.
        One of either "execcute" or "file" is required
        None

file
        HDFS file name of a pig program to run.
        One of either "exec" or "file" is required
        None

arg
        Set a program argument.
        Optional
        None

files
        Comma separated files to be copied to the map reduce cluster
        Optional
        None

statusdir
        A directory where Templeton will write the status of the
         Pig job.  If provided, it is the caller's responsibility
         to remove this directory when done.
        Optional
        None

callback
        Define a URL to be called upon job completion. You may embed a specific
         job ID into this URL using $jobId.  This tag
         will be replaced in the callback URL with this job's job ID.
        Optional
        None

   <title>Results</title>

Name	Description

id
        A string containing the job ID similar to "job_201110132141_0001".

info
        A JSON object containing the information returned when the job was queued.
            See the Hadoop documentation
            (Class
            TaskController) for more information.

   <title>Example</title>

Code and Data Setup

<source>
% cat id.pig
A = load 'passwd' using PigStorage(':');
B = foreach A generate $0 as id;
dump B;

% cat fake-passwd
ctdean:Chris Dean:secret
pauls:Paul Stolorz:good
carmas:Carlos Armas:evil
dra:Deirdre McClure:marvelous

% hadoop fs -put id.pig .
% hadoop fs -put fake-passwd passwd
</source>

Curl Command

<source>
% curl -s -d user.name=ctdean \
       -d file=id.pig \
       -d arg=-v \
       'http://localhost:50111/templeton/v1/pig'
</source>

JSON Output

<source>
{
 "id": "job_201111101627_0018",
 "info": {
          "stdout": "templeton-job-id:job_201111101627_0018
                    ",
          "stderr": "",
          "exitcode": 0
         }
}
</source>

</document>

redpajama_set_name: RedPajamaGithub


text:
namespace te
{
	// TODO: Make camera only a wrapper for a view and projection matrix and associate different methods with it.
	class TE_EXPORT Camera
	{
	public:

		Camera(float FOV = 90, glm::vec3 pos = glm::vec3(), glm::vec3 rot = glm::vec3());

		void render(api::Shader& shader, const vec2f& viewport);

		void bindRaytrace(api::Shader& shader, const vec2f& viewport);

		glm::vec3 pos, rot, dir, right, up;
		float FOV, nearPlane, farPlane, aspect;
	private:
		glm::mat4 m_projection, m_view;
	};
}


text:
<?php

App::uses('ThemeViewTask', 'Theme.Console/Command/Task');

class ThemeViewTaskTest extends CakeTestCase
{
	public function testGetPath() {
		$task = new ThemeViewTask();
		$task->initialize();

		Configure::delete('Theme.default');
		$task->params['theme'] = 'Cake3';
		$expected = APP . 'View' . DS . 'Themed' . DS . 'Cake3' . DS;
		$this->assertEquals($expected, $task->getPath());

		$task->params['theme'] = 'default';
		$expected = APP . 'View' . DS;
		$this->assertEquals($expected, $task->getPath());

		Configure::write('Theme.default', 'Cake3');
		$task->params['theme'] = 'Cake3';
		$expected = APP . 'View' . DS;
		$this->assertEquals($expected, $task->getPath());
	}
}


text:
const strings = require('./strings')
const log = require('./log')

// Localized strings
exports.setLanguage = lang => {
  exports.language = lang
}
exports.str = id => {
  let string
  try {
    if (id in strings) {
      string = strings[id][exports.language]
    }
  } catch (e) {
    console.error(e.stack)
  }
  if (!string) {
    log(`string id "${id}" not found for language ${exports.language}`)
    string = ''
  }
  return string
}


text:
package org.drools.guvnor.client.moduleeditor.drools;

import com.google.gwt.user.client.ui.*;
import org.drools.guvnor.client.common.ErrorPopup;
import org.drools.guvnor.client.common.FormStyleLayout;
import org.drools.guvnor.client.common.FormStylePopup;
import org.drools.guvnor.client.common.GenericCallback;
import org.drools.guvnor.client.common.HTMLFileManagerFields;
import org.drools.guvnor.client.common.ImageButton;
import org.drools.guvnor.client.common.LoadingPopup;
import org.drools.guvnor.client.common.RulePackageSelector;
import org.drools.guvnor.client.messages.Constants;
import org.drools.guvnor.client.moduleeditor.ModuleNameValidator;
import org.drools.guvnor.client.resources.DroolsGuvnorImageResources;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import org.drools.guvnor.client.resources.DroolsGuvnorImages;
import org.drools.guvnor.client.rpc.ModuleService;
import org.drools.guvnor.client.rpc.ModuleServiceAsync;

/**
 * This is the wizard used when creating new packages or importing them.
 */
public class NewSubPackageWizard extends FormStylePopup {

    private TextBox               nameBox;
    private TextBox               descBox;
    private RulePackageSelector   parentPackage;
    private final FormStyleLayout importLayout     = new FormStyleLayout();
    private final FormStyleLayout newPackageLayout = new FormStyleLayout();

    public NewSubPackageWizard(final Command afterCreatedEvent) {
        super(DroolsGuvnorImages.INSTANCE.Wizard(),
               Constants.INSTANCE.CreateANewSubPackage() );
        nameBox = new TextBox();
        descBox = new TextBox();
        parentPackage = new RulePackageSelector();

        newPackageLayout.addAttribute( Constants.INSTANCE.NameColon(),
                                       nameBox );
        newPackageLayout.addAttribute( Constants.INSTANCE.DescriptionColon(),
                                       descBox );
        newPackageLayout.addAttribute( Constants.INSTANCE.ParentPackage(),
                                       parentPackage );

        nameBox.setTitle( Constants.INSTANCE.PackageNameTip() );

        RadioButton newPackage = new RadioButton( "action",
                                                  Constants.INSTANCE.CreateNewPackageRadio() ); //NON-NLS
        RadioButton importPackage = new RadioButton( "action",
                                                     Constants.INSTANCE.ImportFromDrlRadio() ); //NON-NLS
        newPackage.setValue( true );
        newPackageLayout.setVisible( true );

        newPackage.addClickHandler( new ClickHandler() {
            public void onClick(ClickEvent event) {
                newPackageLayout.setVisible( true );
                importLayout.setVisible( false );
            }
        } );

        this.setAfterShow( new Command() {
            public void execute() {
                nameBox.setFocus( true );
            }
        } );

        importLayout.setVisible( false );

        importPackage.addClickHandler( new ClickHandler() {
            public void onClick(ClickEvent event) {
                newPackageLayout.setVisible( false );
                importLayout.setVisible( true );
            }
        } );
        VerticalPanel ab = new VerticalPanel();
        ab.add( newPackage );
        ab.add( importPackage );
        addAttribute( "",
                      ab );

        addRow( newPackageLayout );
        addRow( importLayout );

        importLayout.addAttribute( Constants.INSTANCE.DRLFileToImport(),
                                   newImportWidget( afterCreatedEvent,
                                                    this ) );

        importLayout.addRow( new HTML( "
" + Constants.INSTANCE.NoteNewPackageDrlImportWarning() + "" ) );
        importLayout.addRow( new HTML( Constants.INSTANCE.ImportDRLDesc1() ) );
        importLayout.addRow( new HTML( Constants.INSTANCE.ImportDRLDesc2() ) );
        importLayout.addRow( new HTML( Constants.INSTANCE.ImportDRLDesc3() ) );

        Button create = new Button( Constants.INSTANCE.CreatePackage() );
        create.addClickHandler( new ClickHandler() {
            public void onClick(ClickEvent event) {
                if ( ModuleNameValidator.validatePackageName( nameBox.getText() ) ) {
                    createSubPackageAction( nameBox.getText(),
                                            descBox.getText(),
                                            parentPackage.getSelectedPackage(),
                                            afterCreatedEvent );
                    hide();
                } else {
                    nameBox.setText( "" );
                    Window.alert( Constants.INSTANCE.PackageNameCorrectHint() );
                }
            }
        } );

        newPackageLayout.addAttribute( "",
                                       create );

    }

    private void createSubPackageAction(final String name,
                                        final String descr,
                                        String parentPackage,
                                        final Command refresh) {
        LoadingPopup.showMessage( Constants.INSTANCE.CreatingPackagePleaseWait() );
        ModuleServiceAsync moduleService = GWT.create(ModuleService.class);
        moduleService.createSubModule(name,
                                    descr,
                                    parentPackage,
                                    new GenericCallback<String>() {
                                        public void onSuccess(String data) {
                                            RulePackageSelector.currentlySelectedPackage = name;
                                            LoadingPopup.close();
                                            refresh.execute();
                                        }
                                    });
    }

    public static Widget newImportWidget(final Command afterCreatedEvent,
                                         final FormStylePopup parent) {

        final FormPanel uploadFormPanel = new FormPanel();
        uploadFormPanel.setAction( GWT.getModuleBaseURL() + "package" );
        uploadFormPanel.setEncoding( FormPanel.ENCODING_MULTIPART );
        uploadFormPanel.setMethod( FormPanel.METHOD_POST );

        HorizontalPanel panel = new HorizontalPanel();
        uploadFormPanel.setWidget( panel );

        final FileUpload upload = new FileUpload();
        upload.setName( HTMLFileManagerFields.CLASSIC_DRL_IMPORT );
        panel.add( upload );

        panel.add( new Label( Constants.INSTANCE.upload() ) );
        Image ok = DroolsGuvnorImages.INSTANCE.Upload();
        ok.setAltText(Constants.INSTANCE.Import() );
        ClickHandler okClickHandler = new ClickHandler() {
            public void onClick(ClickEvent event) {
                if ( Window.confirm( Constants.INSTANCE.ImportMergeWarning() ) ) {
                    LoadingPopup.showMessage( Constants.INSTANCE.ImportingDRLPleaseWait() );
                    uploadFormPanel.submit();
                }
            }

        };
        ok.addClickHandler( okClickHandler );

        panel.add( ok );

        Image image = new Image(DroolsGuvnorImageResources.INSTANCE.packageLarge());
        image.setAltText(Constants.INSTANCE.Package());
        final FormStylePopup packageNamePopup = new FormStylePopup(image,
                                                                    Constants.INSTANCE.PackageName() );
        HorizontalPanel packageNamePanel = new HorizontalPanel();
        packageNamePopup.addRow( new Label( Constants.INSTANCE.ImportedDRLContainsNoNameForThePackage() ) );

        final TextBox packageName = new TextBox();
        packageNamePanel.add( new Label( Constants.INSTANCE.PackageName() + ":" ) );
        packageNamePanel.add( packageName );
        Button uploadWithNameButton = new Button( Constants.INSTANCE.OK() );
        uploadWithNameButton.addClickHandler( okClickHandler );
        packageNamePanel.add( uploadWithNameButton );
        packageNamePopup.addRow( packageNamePanel );

        uploadFormPanel.addSubmitCompleteHandler( new SubmitCompleteHandler() {
            public void onSubmitComplete(SubmitCompleteEvent event) {
                if ( event.getResults().indexOf( "OK" ) > -1 ) { //NON-NLS
                    LoadingPopup.close();
                    Window.alert( Constants.INSTANCE.PackageWasImportedSuccessfully() );
                    afterCreatedEvent.execute();
                    parent.hide();
                    if ( packageNamePopup != null ) {
                        packageNamePopup.hide();
                    }
                } else if ( event.getResults().indexOf( "Missing package name." ) > -1 ) { //NON-NLS
                    LoadingPopup.close();
                    packageNamePopup.show();
                } else {
                    ErrorPopup.showMessage( Constants.INSTANCE.UnableToImportIntoThePackage0( event.getResults() ) );
                }
                LoadingPopup.close();
            }
        } );
        uploadFormPanel.addSubmitHandler( new SubmitHandler() {
            public void onSubmit(SubmitEvent event) {
                if ( upload.getFilename().length() == 0 ) {
                    Window.alert( Constants.INSTANCE.YouDidNotChooseADrlFileToImport() );
                    event.cancel();
                } else if ( !upload.getFilename().endsWith( ".drl" ) ) { //NON-NLS
                    Window.alert( Constants.INSTANCE.YouCanOnlyImportDrlFiles() );
                    event.cancel();
                } else if ( packageName.getText() != null && !packageName.getText().equals( "" ) ) {
                    uploadFormPanel.setAction( uploadFormPanel.getAction() + "?packageName=" + packageName.getText() );
                } else {
                    LoadingPopup.showMessage( Constants.INSTANCE.CreatingPackagePleaseWait() );
                }
            }
        } );

        return uploadFormPanel;
    }

}


text:
require 'test_helper'

class EnvestigationTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
namespace CivGen
{
    using System;
    using System.Collections.Generic;

    public partial class GreatWork_YieldChanges
    {
        public string GreatWorkType { get; set; }
        public string YieldType { get; set; }
        public long YieldChange { get; set; }

        public virtual Yield Yield { get; set; }
        public virtual GreatWork GreatWork { get; set; }
    }
}


text:
create or replace package AMB_UTIL_VERSION
/**
 * Applications Manager project version utilities
 * @author:dailey.dai@oracle.com
 * @since: 1.0
 * @date: 2016/02/25
 */
as

/**
 * genarate project version guid as key
 */
function generate_guid return varchar2;

/**
 * generate the LOV query sql for project version environment
 */
function list_enviroment_query return varchar2;

/**
 * check the given version is the base version or not
 */
function is_base(f_version_id varchar2) return boolean;

function list_initialize_mode_query return varchar2;

function list_base_version_query(f_project_id varchar2) return varchar2;

end AMB_UTIL_VERSION;


text:
UINT nInjectionsCount = 0;
#pragma data_seg()

// this section is exported in a def file, but you can also specify it here.
// #pragma comment(linker, "/section:.DENISEG,RWS")

HINSTANCE hInstance = NULL;
HWND hLauncherWnd = NULL;
UINT uiHookMessage = WM_NULL;
HHOOK hKeyboardHook = NULL;

UINT CALLBACK GetInjectionsCount()
{
	return nInjectionsCount;
}

LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam)
{
	if (code == HC_ACTION && hLauncherWnd)
	{
		// if first parameter is HWND_BROADCAST, the message
		// is sent to all top-level windows in the system
		PostMessage(hLauncherWnd, uiHookMessage, wParam, lParam);
	}
	return CallNextHookEx(hKeyboardHook, code, wParam, lParam);
}

BOOL CALLBACK SetKeyboardHook(HWND hParentWnd)
{
	hLauncherWnd = hParentWnd;
	if (!hKeyboardHook)
		hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardProc, hInstance, 0);
	return hKeyboardHook ? TRUE : FALSE;
}

VOID CALLBACK UnhookKeyboardHook()
{
	if (hKeyboardHook)
		UnhookWindowsHookEx(hKeyboardHook);
	hKeyboardHook = NULL;
	hLauncherWnd = NULL;
}

BOOL WINAPI DllMain(HINSTANCE hDLL, DWORD dwReason, LPVOID lpvReserved)
{
	switch (dwReason)
	{
	case DLL_PROCESS_ATTACH:
		hInstance = hDLL;
		uiHookMessage = RegisterWindowMessage(TEXT("HookSampleMessage"));
		InterlockedIncrement(&nInjectionsCount);
		break;
	case DLL_PROCESS_DETACH:
		InterlockedDecrement(&nInjectionsCount);
		break;
	}
	return TRUE;
}


text:
"use strict";
var auth = require("./auth");
'use strict';
var MobileAuthenticationApi = (function () {
    function MobileAuthenticationApi($http, config, $httpParamSerializer) {
        this.$http = $http;
        this.config = config;
        this.$httpParamSerializer = $httpParamSerializer;
        this.defaultHeaders = {};
        this.authentications = {
            'default': new auth.VoidAuth(),
            'oauth2': new auth.OAuth(),
        };
    }
    Object.defineProperty(MobileAuthenticationApi.prototype, "accessToken", {
        set: function (token) {
            this.authentications.oauth2.accessToken = token;
        },
        enumerable: true,
        configurable: true
    });
    MobileAuthenticationApi.prototype.extendObj = function (objA, objB) {
        for (var key in objB) {
            if (objB.hasOwnProperty(key)) {
                objA[key] = objB[key];
            }
        }
        return objA;
    };
    MobileAuthenticationApi.prototype.getExternalFacebookLogin = function (accessToken, extraHttpRequestParams) {
        var localVarPath = this.config.basePath + '/authorization/externalFacebookLogin';
        var queryParameters = {};
        var headerParams = this.extendObj({}, this.defaultHeaders);
        if (accessToken === null || accessToken === undefined) {
            throw new Error('Required parameter accessToken was null or undefined when calling getExternalFacebookLogin.');
        }
        if (accessToken !== undefined) {
            queryParameters['access_token'] = accessToken;
        }
        var httpRequestParams = {
            method: 'GET',
            url: localVarPath,
            json: true,
            params: queryParameters,
            headers: headerParams
        };
        if (extraHttpRequestParams) {
            httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams);
        }
        this.authentications.default.applyToRequest(httpRequestParams);
        return this.$http(httpRequestParams);
    };
    MobileAuthenticationApi.prototype.getExternalLogin = function (provider, error, extraHttpRequestParams) {
        var localVarPath = this.config.basePath + '/authorization/externalLogin';
        var queryParameters = {};
        var headerParams = this.extendObj({}, this.defaultHeaders);
        if (provider === null || provider === undefined) {
            throw new Error('Required parameter provider was null or undefined when calling getExternalLogin.');
        }
        if (provider !== undefined) {
            queryParameters['provider'] = provider;
        }
        if (error !== undefined) {
            queryParameters['error'] = error;
        }
        var httpRequestParams = {
            method: 'GET',
            url: localVarPath,
            json: true,
            params: queryParameters,
            headers: headerParams
        };
        if (extraHttpRequestParams) {
            httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams);
        }
        this.authentications.default.applyToRequest(httpRequestParams);
        return this.$http(httpRequestParams);
    };
    MobileAuthenticationApi.prototype.getExternalLogins = function (returnUrl, generateState, extraHttpRequestParams) {
        var localVarPath = this.config.basePath + '/authorization/externalLogins';
        var queryParameters = {};
        var headerParams = this.extendObj({}, this.defaultHeaders);
        if (returnUrl === null || returnUrl === undefined) {
            throw new Error('Required parameter returnUrl was null or undefined when calling getExternalLogins.');
        }
        if (returnUrl !== undefined) {
            queryParameters['returnUrl'] = returnUrl;
        }
        if (generateState !== undefined) {
            queryParameters['generateState'] = generateState;
        }
        var httpRequestParams = {
            method: 'GET',
            url: localVarPath,
            json: true,
            params: queryParameters,
            headers: headerParams
        };
        if (extraHttpRequestParams) {
            httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams);
        }
        this.authentications.default.applyToRequest(httpRequestParams);
        return this.$http(httpRequestParams);
    };
    return MobileAuthenticationApi;
}());
MobileAuthenticationApi.$inject = ['$http', 'IApiConfig', '$httpParamSerializer'];
exports.MobileAuthenticationApi = MobileAuthenticationApi;
//# sourceMappingURL=MobileAuthenticationApi.js.map


text:
package org.apache.axis2.examples.httpsclient;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;

public class SimpleServiceClient {

    public static void main(String[] ars) throws AxisFault, XMLStreamException {
        // Client side keystore location, here we use same keystore
        System.setProperty("javax.net.ssl.trustStore", "../httpsService/target/jetty-ssl.keystore");
        System.setProperty("javax.net.ssl.trustStorePassword", "axis2key");
        String epr = "https://localhost:8443/services/SimpleService/";

        Options options = new Options();
        options.setTo(new EndpointReference(epr));
        ServiceClient sender = new ServiceClient();
        sender.setOptions(options);
        OMElement ret = sender.sendReceive(creatMsg());
        ret.serialize(System.out);

    }

    public static OMElement creatMsg() {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace("http://httpsservice.examples.axis2.apache.org",
                "ns1");
        OMElement method = fac.createOMElement("helloService", omNs);
        OMElement value = fac.createOMElement("msg", omNs);
        value.setText("World ");
        method.addChild(value);
        return method;
    }

}


text:
.title_in_image.main { position: relative; display: inline-block; margin: 0; height: 0; width: 100%; float: left; background-position: center; background-repeat: no-repeat; background-size: cover; display: inline-block; height: 0; outline: 1px solid white; }
.title_in_image.gradient { position: absolute; display: inline-block; height: 50%; bottom: 0; left: 0; margin: 0; padding: 0; width: 100%; background: -webkit-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,1));  background: -o-linear-gradient(bottom,rgba(0,0,0,0),rgba(0,0,0,1));  background: -moz-linear-gradient(bottom,rgba(0,0,0,0),rgba(0,0,0,1));   background: linear-gradient(to bottom, rgba(0,0,0,0), rgba(0,0,0,1));  }

.title_in_image.title { position: absolute; display: inline-block; margin: 0; padding: 10px 20px; height: 20%; bottom: 20px; overflow: hidden; width: calc(100% - 40px); color: white; font-weight: 400; text-align: left; left: 0; text-decoration: none; cursor: pointer; line-height: 1.5; }
.title_in_image.title:hover { text-decoration: underline; }
.title_in_image.date { display: inline-block;  position: absolute;  margin: 0; padding: 10px 20px; bottom: 0px; color: white; font-weight: 300; font-size: 12px; left: 0; }

@media (min-width: 0px) {
	.title_in_image.main { padding-bottom: 71%; }
	.title_in_image.title { font-size: 2em; }
	.title_in_image.mobile { display: inline-block; }
	.title_in_image.desktop { display: none; }
}
@media (min-width: 768px) {
	.title_in_image.main { width: calc( 33.33% - 0px); padding-bottom: 26%; }
	.title_in_image.title {font-size: 1.4em;}
	.title_in_image.mobile {display: none;}
	.title_in_image.desktop {display: inline-block;}
}
@media (min-width: 992px) {
	.title_in_image.main { width: calc( 33.33% - 0px); padding-bottom: 26%; }
	.title_in_image.title {font-size: 1.6em;}
	.title_in_image.mobile {display: none;}
	.title_in_image.desktop {display: inline-block;}
}


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using Microsoft.AspNetCore.Http;

namespace IdentityServer4.Hosting
{
    public interface IEndpointRouter
    {
        IEndpoint Find(HttpContext context);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.touwolf.weatherer"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:name=".WeatherApp"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".activity.DayListActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity
            android:name=".activity.DayDetailActivity"
            android:parentActivityName=".activity.DayListActivity"
            android:screenOrientation="portrait">
        </activity>

        <activity
            android:name=".activity.SettingsActivity"
            android:label="@string/settings"
            android:parentActivityName=".activity.DayListActivity"
            android:screenOrientation="portrait">
        </activity>
    </application>

</manifest>


text:
Functions Logs

List indexes in your project's Cloud Firestore database.

  <form clrForm [formGroup]="form" clrLayout="horizontal">

    <clr-radio-container>
      Display
      <clr-radio-wrapper>
        <input type="radio" clrRadio formControlName="display" value="show" />
        Show on screen
      </clr-radio-wrapper>
      <clr-radio-wrapper>
        <input type="radio" clrRadio formControlName="display" value="open" />
        Open log viewer in browser
      </clr-radio-wrapper>
      <clr-control-helper>Whether to show the logs on screen or to open the GCP log viewer in the browser
      </clr-control-helper>
    </clr-radio-container>

    <clr-input-container>
      Functions
      <input clrInput type="text" formControlName="only" />
      <clr-control-helper>
        Only show logs of specified, comma-seperated functions
        (e.g. funcA,funcB).

        Leave blank to show logs for all functions.
      </clr-control-helper>
    </clr-input-container>

    <clr-input-container *ngIf="display === 'show'">
      Num. lines
      <input clrInput type="number" formControlName="lines" placeholder="35" />
      <clr-control-helper>Specify the number of log lines to fetch</clr-control-helper>
    </clr-input-container>

                <clr-icon class="alert-icon" shape="exclamation-circle"></clr-icon>

        <button [clrLoading]="running" class="btn btn-primary" type="submit" (click)="start()" [disabled]="!form.valid">
          {{ display | titlecase }} logs
        </button>

  </form>

<clr-modal [(clrModalOpen)]="modalVisible" [clrModalSize]="'xl'" class="logs-modal">

Logs

          Timestamp
          Level
          Function
          Event message

          {{ entry.timestamp | date:'medium' }}
          {{ entry.severity }}

            {{ entry.resource.labels['function_name'] }}

            {{ entry.textPayload }}

            {{ entry.protoPayload | json }}

    <button type="button" class="btn btn-primary" (click)="modalVisible = false">Close</button>

</clr-modal>


text:
from oslo.config import cfg

from ironic.common import context as nova_context
from ironic.common import exception
from ironic.openstack.common import log as logging
from ironic import db

CONF = cfg.CONF

LOG = logging.getLogger(__name__)

class BareMetalVIFDriver(object):

    def _after_plug(self, instance, network, mapping, pif):
        pass

    def _after_unplug(self, instance, network, mapping, pif):
        pass

    def plug(self, instance, vif):
        LOG.debug(_("plug: instance_uuid=%(uuid)s vif=%(vif)s")
                  % {'uuid': instance['uuid'], 'vif': vif})
        network, mapping = vif
        vif_uuid = mapping['vif_uuid']
        ctx = nova_context.get_admin_context()
        node = db.bm_node_get_by_instance_uuid(ctx, instance['uuid'])

        # TODO(deva): optimize this database query
        #             this is just searching for a free physical interface
        pifs = db.bm_interface_get_all_by_bm_node_id(ctx, node['id'])
        for pif in pifs:
            if not pif['vif_uuid']:
                db.bm_interface_set_vif_uuid(ctx, pif['id'], vif_uuid)
                LOG.debug(_("pif:%(id)s is plugged (vif_uuid=%(vif_uuid)s)")
                          % {'id': pif['id'], 'vif_uuid': vif_uuid})
                self._after_plug(instance, network, mapping, pif)
                return

        # NOTE(deva): should this really be raising an exception
        #             when there are no physical interfaces left?
        raise exception.NovaException(_(
                "Baremetal node: %(id)s has no available physical interface"
                " for virtual interface %(vif_uuid)s")
                % {'id': node['id'], 'vif_uuid': vif_uuid})

    def unplug(self, instance, vif):
        LOG.debug(_("unplug: instance_uuid=%(uuid)s vif=%(vif)s"),
                  {'uuid': instance['uuid'], 'vif': vif})
        network, mapping = vif
        vif_uuid = mapping['vif_uuid']
        ctx = nova_context.get_admin_context()
        try:
            pif = db.bm_interface_get_by_vif_uuid(ctx, vif_uuid)
            db.bm_interface_set_vif_uuid(ctx, pif['id'], None)
            LOG.debug(_("pif:%(id)s is unplugged (vif_uuid=%(vif_uuid)s)")
                      % {'id': pif['id'], 'vif_uuid': vif_uuid})
            self._after_unplug(instance, network, mapping, pif)
        except exception.NovaException:
            LOG.warn(_("no pif for vif_uuid=%s") % vif_uuid)


text:
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)

require 'yaml'
require 'loaderio'
require 'active_support/core_ext/object'

require 'loaderio-cli/version'
require 'loaderio-cli/cli'
require 'loaderio-cli/config'
require 'loaderio-cli/command'
require 'loaderio-cli/command/app'
require 'loaderio-cli/command/test'

module LoaderioCLI
end


text:
@interface WMFCrossProcessCoreDataSynchronizer () {
    dispatch_semaphore_t _semaphore;
    int _token;
}

@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, copy) NSURL *containerURL;

@end

static uint64_t bundleHash() {
    static dispatch_once_t onceToken;
    static uint64_t bundleHash;
    dispatch_once(&onceToken, ^{
        bundleHash = (uint64_t)[[[NSBundle mainBundle] bundleIdentifier] hash];
    });
    return bundleHash;
}

@implementation WMFCrossProcessCoreDataSynchronizer

- (instancetype)initWithIdentifier:(NSString *)identifier storageDirectory:(NSURL *)directoryURL {
    self = [super init];
    if (self) {
        _semaphore = dispatch_semaphore_create(1);
        self.containerURL = directoryURL;
        self.identifier = identifier;
    }
    return self;
}

- (void)dealloc {
    [self stop];
}

- (void)startSynchronizingContexts:(NSArray<NSManagedObjectContext *> *)contexts {
    if (!self.identifier) {
        DDLogError(@"missing channel name");
        return;
    }
    const char *name = [self.identifier UTF8String];
    for (NSManagedObjectContext *context in contexts) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:context];
    }
    @weakify(self)
    notify_register_dispatch(name, &_token, dispatch_get_main_queue(), ^(int token) {
        @strongify(self)
        uint64_t state;
        notify_get_state(token, &state);
        BOOL isExternal = state != bundleHash();
        if (isExternal) {
            [self readCrossProcessCoreDataNotificationWithState:state intoContexts:contexts];
        }
    });
}

- (void)stop {
    if (_token != 0) {
        notify_cancel(_token);
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Writing Changes from this Process

- (void)contextDidSave:(NSNotification *)note {
    [self writeCrossProcessCoreDataNotification:note];
}

- (void)writeCrossProcessCoreDataNotification:(NSNotification *)note {
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    NSDictionary *userInfo = note.userInfo;
    if (!userInfo) {
        return;
    }

    uint64_t state = bundleHash();

    NSDictionary *archiveableUserInfo = [self archivableNotificationUserInfoForUserInfo:userInfo];

    NSError *archiveError = nil;
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:archiveableUserInfo requiringSecureCoding:NO error:&archiveError];
    if (archiveError) {
        DDLogError(@"Error archiving cross process changes: %@", archiveError);
        return;
    }

    NSURL *fileURL = [self archivedChangesFileURLWithState:state];
    [data writeToURL:fileURL atomically:YES];

    const char *name = [self.identifier UTF8String];
    notify_set_state(_token, state);
    notify_post(name);
    dispatch_semaphore_signal(_semaphore);
}

#pragma mark - Reading changes from other processes

- (void)readCrossProcessCoreDataNotificationWithState:(uint64_t)state intoContexts:(NSArray<NSManagedObjectContext *> *)contexts {
    NSURL *fileURL = [self archivedChangesFileURLWithState:state];
    NSError *unarchiveError = nil;
    NSDictionary *userInfo = [self unarchivedDictionaryFromFileURL:fileURL error:&unarchiveError];
    if (unarchiveError) {
        DDLogError(@"Error unarchiving cross process core data notification: %@", unarchiveError);
        return;
    }
    [NSManagedObjectContext mergeChangesFromRemoteContextSave:userInfo intoContexts:contexts];
}

#pragma mark - Notification Archive Utitlities

- (NSDictionary *)unarchivedDictionaryFromFileURL:(NSURL *)fileURL error:(NSError **)error {
    NSData *data = [NSData dataWithContentsOfURL:fileURL];
    NSSet *allowedClasses = [NSSet setWithArray:[NSSecureUnarchiveFromDataTransformer allowedTopLevelClasses]];
    return [NSKeyedUnarchiver unarchivedObjectOfClasses:allowedClasses fromData:data error:error];
}

- (NSURL *)archivedChangesFileURLWithState:(uint64_t)state {
    NSString *fileName = [NSString stringWithFormat:@"%llu.%@.changes", state, self.identifier];
    return [self.containerURL URLByAppendingPathComponent:fileName isDirectory:NO];
}

- (nullable id)archiveableNotificationValueForValue:(id)value {
    if ([value isKindOfClass:[NSManagedObject class]]) {
        return [[value objectID] URIRepresentation];
    } else if ([value isKindOfClass:[NSManagedObjectID class]]) {
        return [value URIRepresentation];
    } else if ([value isKindOfClass:[NSSet class]] || [value isKindOfClass:[NSArray class]]) {
        return [value wmf_map:^id(id obj) {
            return [self archiveableNotificationValueForValue:obj];
        }];
    } else if ([value conformsToProtocol:@protocol(NSCoding)]) {
        return value;
    } else {
        return nil;
    }
}

- (NSDictionary *)archivableNotificationUserInfoForUserInfo:(NSDictionary *)userInfo {
    NSMutableDictionary *archiveableUserInfo = [NSMutableDictionary dictionaryWithCapacity:userInfo.count];
    NSArray *allKeys = userInfo.allKeys;
    for (NSString *key in allKeys) {
        id value = userInfo[key];
        if ([value isKindOfClass:[NSDictionary class]]) {
            value = [self archivableNotificationUserInfoForUserInfo:value];
        } else {
            value = [self archiveableNotificationValueForValue:value];
        }
        if (value) {
            archiveableUserInfo[key] = value;
        }
    }
    return archiveableUserInfo;
}

@end


text:
import ssl
import socket
import os
import re
import sys

# You can provide the name of a file containing a list of URLs
# on the command line. If not provided, it defaults to "target_list"
try:
    hostfile = sys.argv[1]
except:
    hostfile = 'target_list'

children = []
hosts = []

try:
    f = open(hostfile, 'r')
    for line in f:
        hosts.append(line.rstrip('\r\n'))
    f.closed
except (IOError, OSError) as e:
    print "Abort - couldn't open URL file: " + str(e)
    file.closed
    exit()

print "Checking hosts for SSLv3:"

for host in hosts:
    # Check it's not a comment
    if (re.search('^\s*#', host)):
        continue

    # Fork into its own process
    pid = os.fork()
    if (pid == 0):
        # We are in the child process

        # Sanity check the provided "URL"
        # If URL says "http://" warn and ignore it
        if (re.search('^\s*http://', host)):
            print "Ignoring http host".rjust(40) + ":  !! " + host
            os._exit(0)

        # Strip https:// if present (we assume https)
        if (re.search('^\s*https://', host)):
            print "Stripping https from " + host + "\n"
            host = re.sub('^\s*https://', '', host)
        elif (re.search(r'//', host)):
            # It isn't http, it isn't https, yet we still have // in there?
            # Ditch
            print "Invalid URI".rjust(40) + ":  !! " + host
            os._exit(0)

        # Now check for a /path on the end and split it off as it's not
        # necessary
        # No mercy!
        host = re.sub('/.*$', '', host)

        # Check for : defining a specific port
        match = re.search(':(\d+)$', host)
        if (match):
            tcpport = int(match.group(1))
            host = re.sub(':\d+$', '', host)
            print "Using port ", tcpport, " for host ", host
        else:
            tcpport = 443

        # Create socket and define SSL negotiation
        s_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s = ssl.wrap_socket(
            s_,
            ca_certs='/Library/Python/2.7/site-packages/requests/cacert.pem',
            cert_reqs=ssl.CERT_NONE,
            ssl_version=ssl.PROTOCOL_SSLv3,
            )
        flag = '  '
        try:
            # Make it rain
            s.connect((host, tcpport))
            usedcipher = str(s.cipher())
        except ssl.SSLError as e:
            # Failed
            usedcipher = 'Exception: ' + str(e)
        except:
            usedcipher = 'Other: some other error occurred'
            flag = '??'

        # Flag any using SSLv3
        if (re.search(r'SSLv3', usedcipher)):
            flag = 'XX'

        # Dump cipher tuple / status out
        hoststring = host + ':' + str(tcpport)
        print hoststring.rjust(40) + ":  " + flag + " " + usedcipher

        # Don't need to to any more, so close out this session
        s.close()

        # Exit child process!
        os._exit(0)

    else:
        # We are in the parent process
        children.append(pid)
        next

# Wait for the children to die (as it were)

for child in children:
        os.waitpid(child, 0)
print "Done\n"


text:
package org.o3project.odenos.remoteobject.message;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.msgpack.packer.Packer;
import org.msgpack.type.Value;
import org.msgpack.unpacker.Unpacker;
import org.powermock.reflect.Whitebox;

import java.io.IOException;

/**
 *
 *
 */
public class EventTest {
  private Event target = null;
  private Object body = null;

  /**
   * @throws java.lang.Exception throws Exception in targets
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
  }

  /**
   * @throws java.lang.Exception throws Exception in targets
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception {
  }

  /**
   * @throws java.lang.Exception throws Exception in targets
   */
  @Before
  public void setUp() throws Exception {
    body = Mockito.mock(Object.class);
    target = Mockito.spy(new Event("publisherId", "eventType", "txid", body));
  }

  /**
   * @throws java.lang.Exception throws Exception in targets
   */
  @After
  public void tearDown() throws Exception {
    target = null;
    body = null;
  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#Event(java.lang.String, java.lang.String, java.lang.String, java.lang.Object)}.
   */
  @Test
  public final void testEventStringStringObject() {
    target = Mockito.spy(new Event("publisherId", "eventType", "txid", body));

    assertThat(target.publisherId, is("publisherId"));
    assertThat(target.eventType, is("eventType"));
    assertThat(target.body, is(body));

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#Event()}.
   */
  @Test
  public final void testEvent() {
    target = Mockito.spy(new Event());

    assertThat(target.publisherId, is(nullValue()));
    assertThat(target.eventType, is(nullValue()));
    assertThat(target.body, is(nullValue()));

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#getPublisherId()}.
   */
  @Test
  public final void testGetPublisherId() {

    /*
     * test
     */
    String result = target.getPublisherId();

    /*
     * check
     */
    assertThat(result, is("publisherId"));

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#setPublisherId(java.lang.String)}.
   */
  @Test
  public final void testSetPublisherId() {

    /*
     * test
     */
    target.setPublisherId("NewPublisherId");

    /*
     * check
     */
    String resultMember = Whitebox.getInternalState(target, "publisherId");
    assertThat(resultMember, is("NewPublisherId"));

    String resultGet = target.getPublisherId();
    assertThat(resultGet, is("NewPublisherId"));

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#getEventType()}.
   */
  @Test
  public final void testGetEventType() {

    /*
     * test
     */
    String result = target.getEventType();

    /*
     * check
     */
    assertThat(result, is("eventType"));

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#setEventType(String)}.
   */
  @Test
  public final void testSetEventType() {

    /*
     * test
     */
    target.setEventType("NewEventType");

    /*
     * check
     */
    String resultMember = Whitebox.getInternalState(target, "eventType");
    assertThat(resultMember, is("NewEventType"));

    String resultGet = target.getEventType();
    assertThat(resultGet, is("NewEventType"));

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#readFrom(org.msgpack.unpacker.Unpacker)}.
   * @throws IOException throws IOException in targets
   */
  @Test
  public final void testReadFrom() throws IOException {
    Unpacker unpacker = Mockito.mock(Unpacker.class);
    doReturn("publisherId").doReturn("eventType").when(unpacker)
        .readString();

    target.readFrom(unpacker);

    verify(unpacker).readArrayBegin();
    verify(unpacker, times(3)).readString();
    verify(unpacker).readValue();
    verify(unpacker).readArrayEnd();
  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#readFrom(org.msgpack.unpacker.Unpacker)}.
   * @throws IOException throws IOException in targets
   */
  @Test(expected = IOException.class)
  public final void testReadFromWithIoException() throws IOException {
    Unpacker unpacker = Mockito.mock(Unpacker.class);
    doReturn("publisherId").doReturn("eventType").when(unpacker)
        .readString();

    doThrow(new IOException()).when(unpacker).readArrayEnd();

    target.readFrom(unpacker);

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#writeTo(org.msgpack.packer.Packer)}.
   * @throws IOException throws IOException in targets
   */
  @Test
  public final void testWriteTo() throws IOException {
    Packer packer = Mockito.mock(Packer.class);
    doReturn(packer).when(packer).write(anyObject());

    target.writeTo(packer);

    verify(packer).writeArrayBegin(4);
    verify(packer).write("publisherId");
    verify(packer).write("eventType");
    verify(packer).write("txid");
    verify(packer).write(body);
    verify(packer).writeArrayEnd();
  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#writeTo(org.msgpack.packer.Packer)}.
   * @throws IOException throws IOException in targets
   */
  @Test
  public final void testWriteToWithBodyValue() throws IOException {
    Packer packer = Mockito.mock(Packer.class);
    doReturn(packer).when(packer).write(anyObject());
    target.bodyValue = Mockito.mock(Value.class);

    target.writeTo(packer);

    verify(packer).writeArrayBegin(4);
    verify(packer).write("publisherId");
    verify(packer).write("eventType");
    verify(packer).write("txid");
    verify(packer).write(target.bodyValue);
    verify(packer).writeArrayEnd();
  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#writeTo(org.msgpack.packer.Packer)}.
   * @throws IOException throws IOException in targets
   */
  @Test(expected = IOException.class)
  public final void testWriteToWithIoException() throws IOException {
    Packer packer = Mockito.mock(Packer.class);
    doReturn(packer).when(packer).write(anyObject());

    doThrow(new IOException()).when(packer).writeArrayEnd();

    target.writeTo(packer);

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#hashCode()}.
   */
  @Test
  public final void testHashCodeTrue() {

    /*
     * setting
     */
    Object body = new Object();
    Event target1 = new Event("publisherId", "eventType", "txid", body);
    Event target2 = new Event("publisherId", "eventType", "txid", body);

    Object eventBody = new Object(); // not body
    Event target3 = new Event("publisherId", "eventType", "txid", eventBody);

    /*
     * test
     */
    int result1 = target1.hashCode();
    int result2 = target2.hashCode();
    int result3 = target3.hashCode();

    /*
     * check
     */
    assertThat(result2, is(result1));
    assertThat(result3, is(result1));
  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#equals(Object)}.
   */
  @Test
  public final void testHashCodeFalse() {

    /*
     * setting
     */
    Object body = new Object();
    Event target11 = new Event("publisherId", "eventType", "txid", body);
    Event target12 = new Event("publisherId", "eventType2", "txid", body);
    Event target21 = new Event("publisherId2", "eventType", "txid", body);
    Event target22 = new Event("publisherId2", "eventType2", "txid", body);

    /*
     * test
     */
    int result11 = target11.hashCode();
    int result12 = target12.hashCode();
    int result21 = target21.hashCode();
    int result22 = target22.hashCode();

    /*
     * check
     */
    assertThat(result12, is(not(result11)));
    assertThat(result21, is(not(result11)));
    assertThat(result22, is(not(result11)));

    assertThat(result21, is(not(result12)));
    assertThat(result22, is(not(result12)));

    assertThat(result22, is(not(result21)));

  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#equals(Object)}.
   */
  @Test
  public final void testEqualsEventTrue() {

    /*
     * setting
     */
    Object body = new Object();
    Event target = new Event("publisherId", "eventType", "txid", body);
    Event event2 = new Event("publisherId", "eventType", "txid", body);

    Object eventBody = new Object(); // not body
    Event event3 = new Event("publisherId", "eventType", "txid", eventBody);

    /*
     * test
     */
    boolean result1 = target.equals(target);
    boolean result2 = target.equals(event2);
    boolean result3 = target.equals(event3);

    /*
     *
     */
    assertThat(result1, is(true));
    assertThat(result2, is(true));
    assertThat(result3, is(true));

    assertThat(target.hashCode(), is(target.hashCode()));
    assertThat(event2.hashCode(), is(target.hashCode()));
    assertThat(event3.hashCode(), is(target.hashCode()));
  }

  /**
   * Test method for {@link org.o3project.odenos.remoteobject.message.Event#equals(java.lang.Object)}.
   */
  @Test
  public final void testEqualsEventFalse() {

    /*
     * setting
     */
    Object body = new Object();
    Event target11 = new Event("publisherId", "eventType", "txid", body);
    Event event12 = new Event("publisherId", "eventType2", "txid", body);
    Event event21 = new Event("publisherId2", "eventType", "txid", body);
    Event event22 = new Event("publisherId2", "eventType2", "txid", body);

    /*
     * test
     */
    boolean result12 = target11.equals(event12);
    boolean result21 = target11.equals(event21);
    boolean result22 = target11.equals(event22);

    /*
     *
     */
    assertThat(result12, is(false));
    assertThat(result21, is(false));
    assertThat(result22, is(false));

  }

}


text:
using Microsoft.AspNetCore.Authorization;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace ASPWiki.Tests
{
    public class AuthorizeStub : IAuthorizationService
    {
        bool result;

        /// <summary>
        /// Stub for authorization in controller tests.
        /// </summary>
        /// <param name="result">If true, AuthorizeAsync will pass, false it will not</param>
        public AuthorizeStub(bool result)
        {
            this.result = result;
        }

        public Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
        {
            return Task.FromResult(result);
        }

        public Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements)
        {
            return Task.FromResult(result);
        }
    }
}


text:
@interface BindCell : UICollectionViewCell

- (void)setIcon:(NSString *)imageStr name:(NSString *)name;

@end


text:
layout: post
title: Clojure-py lite
navigation: True
class: post-template
subclass: 'post'
cover: images/clojure-py.jpg
---

I have been tracking the progress of [clojure-py][1] on and off for the past two years or so but unfortunately it has officially been [dropped by its current maintainer][2]. I know node.js and Clojurescript are Clojures "de-facto" scripting solution but I am more familiar with the Python ecosystem so I was looking forward to being able to use the libraries I know with Clojure. However, on the clojure-py mailing list [Hy][3] was mentioned as a possible alternative so I decided to take a look at Hy and see how close we can get to a Clojure "like" environment on cPython. _Note:_ I am not suggesting anyone use this setup for serious systems, its just a fun exercise.
<!--excerpt-->

## Clojure features

This is not an exhaustive list of Clojure features but they are some
of the ones I use most often and I would like to have something
similar on the cPython platform.

* REPL
* Standard functional and Lisp functions/constructs
* Host interop
* Persistent data structures
* Protocols
* Concurrency constructs: Atoms, Futures, Threads, Refs, Agents
* Laziness
* Clojure niceties: threading macros,
* Macros
* Meta data
* _Bonus_ Although not a language feature something like the awesome core.async library would be a clincher

OK, lets install hy and see how far we can get.

## REPL

Running `hy` on the command line gives us a REPL. It seems to do paren matching and the up and down arrow keys work like you would expect. Comments in hy start with a ; like Clojure, however writing a comment in the REPL raises a parsing error. Being able to use this from iPython would be very nice, not sure what it would entail however. One for another day.

Verdict: 8/10

## Functional Lisp constructs

Hy seems to have a lot of the standard things you expect in a Lisp. Lets try out some of the basic functions we expect.

```
=> (first [1 2 3 4 5])
1
=> (rest [1 2 3 4 5])
[2, 3, 4, 5]
=> (car [1 2 3 4 5])
1
=> (cdr [1 2 3 4 5])
[2, 3, 4, 5]
=> (take 2 [ 1 2 3 4 ])
<generator object _hy_anon_fn_35 at 0x10d39ab40>
=> (list (take 2 [ 1 2 3 4 ]))
[1, 2]
=> (map inc [1 2 3 4 5])
[2, 3, 4, 5, 6]
=> (import operator)
=> (reduce operator.add [1 2 3 4 5])
15
=> (filter even? [1 2 3 4 5 6 7 8 9 10])
<generator object _hy_anon_fn_12 at 0x10d39ab40>
=> (list (filter even? [1 2 3 4 5 6 7 8 9 10]))
[2, 4, 6, 8, 10]
```

Ah, OK, take and filter are lazy and return a Python generator. Everything works as expected so far. There is also a third party Python library called [toolz][4] whose aim is to build on the functions available in the Python functools and itertools modules. It is heavily influenced by Clojure, "the toolz project generally adheres closely to the API found in the Clojure standard library". Using it from hy is easy:

```
=> (import [toolz.itertoolz.core [concat cons count]])
=> (list (concat [[1 2] [3 4]]))
[1, 2, 3, 4]
=> (list (cons 1 [2 3]))
[1, 2, 3]
=> (count [1 2 3 4 5])
5
```

Using toolz in conjunction with Hy allows us to get most of the basics we would expect. Lets move on to something more interesting.

Verdict: 8/10

## Host interop

Hy claims to be a "pythonic lisp" and its structure is converted to Pythons AST for execution. As you would expect interop works very well. Hy provides Clojure like ''.'' access to methods and an import statement to import Python code. The kwapply function required to supply keyword arguments is a bit ugly however (nitpicking).

Verdict: 9/10

## Persistent data structures

This is a big Clojure advantage, but since Hy is built on Python we are stuck with Pythons mutable data structures by default. There seems to be two third party libraries that provide basic persistent data structures to Python, [pysistence][5] and [pyrsistent][6]. Pysistence has an experimental C module so it may be more performant but it doesn''t seem to be actively maintained. Pysistence was recently released and claims to have been inspired by Clojure. Performance is "generally in the range of 2 - 100 times slower than using the corresponding built in types in Python" but the author claims running on PyPy can greatly improve performance. Since I plan to use this setup for non-production scripts, performance isn''t a deal breaker for me.

```
=> (import [pyrsistent [pvec pmap pset]])
=> (def p1 (pvec 1 2 3))
=> (.append p1 4)
[1, 2, 3, 4]
=> p1
[1, 2, 3]
=> (def pm1 (kwapply (pmap) {:a 1 :b 2}))
=> pm1
{u''\ufdd0:a'': 1, u''\ufdd0:b'': 2}
=> (.todict pm1)
{u''\ufdd0:a'': 1, u''\ufdd0:b'': 2}
=> (:a pm1)
1
=> (.assoc pm1 :c 3)
{u''\ufdd0:a'': 1, u''\ufdd0:c'': 3, u''\ufdd0:b'': 2}
```

Pyrsistent gives us persistent data structures but because its a third party library we lose literal syntax (constructing a map is unwieldy) and it is a very young project.

Verdict: 5/10

## Protocols

Protocols are a fundamental abstraction in Clojure and allow one to write performant polymorphic functions. As part of this setup I am just looking for something to provide me with a way to write polymorphic functions of my own (performance not a concern). As luck would have it [PEP 443][7] was recently approved and, a version of it has been [back-ported to Python 2.7][8]. Singledispatch is a decorator and does not let us group functions together like protocols.

```
=> (import [singledispatch [singledispatch]])
=> (defclass bird [object])
=> (defclass aeroplane [object])
=> (with-decorator singledispatch (defn fly [arg] (print "I fly")))
=> (with-decorator (fly.register bird) (defn _ [self] (print "I fly by flapping")))
=> (with-decorator (fly.register aeroplane) (defn _ [self] (print "I fly using engines")))
=> (fly 1)
I fly
=> (fly (bird))
I fly by flapping
=> (fly (aeroplane))
I fly using engines
```

singledispath is not as powerful as protocols in the broader sense. However it is part of the stdlib from 3.4 onwards and it lets us write polymorphic functions in Hy which is what I was looking for.

Verdict: 8/10

## Next

Ok, this post is already longer than I was expecting and I am not finished yet. I will finish the investigation in my next post.

[1]: https://github.com/halgari/clojure-py "Clojure-py"
[2]: https://groups.google.com/d/msg/clojure-py-dev/HbeNEkIG23U/61rN0wR2qDwJ "Gone"
[3]: http://hylang.org/ "Hy"
[4]: http://toolz.readthedocs.org/ "toolz"
[5]: http://pythonhosted.org/pysistence/ "Pysistence"
[6]: http://pyrsistent.readthedocs.org/en/latest/ "Pyrsistent"
[7]: http://www.python.org/dev/peps/pep-0443/ "PEP 443"
[8]: https://pypi.python.org/pypi/singledispatch "singledispatch"


text:
The files in the tests directory are from the
[mal](https://github.com/kanakad/mal) repo.  And used under the terms of
its [Mozilla Public License, Version 2.0](LICENSE.txt).


text:
package com.davidjohnburrowes.io;

import java.io.EOFException;

/**
 * Used to indicate a LimitingDatainput has been asked to read beyond its limit.
 */
public class LimitExceeded extends EOFException {

   private static final long serialVersionUID = 1L;

   /**
	 * Number of bytes that couldn't be read (0 indicates unknown)
	 */
	protected int amount;

	/**
	 * The instance that threw this exception
	 */
	protected LimitingDataInput instance;

	/**
	 * Constructor
	 * @param message Exception message
	 */
	public LimitExceeded(String message) {
		this(message, 0, null);
	}

	/**
	 * Constructor
	 * @param message Exception message
	 * @param exceededAmount Number of bytes exceeded (0 means unknown)
	 * @param instance The object that couldn't read in the bytes
	 */
	public LimitExceeded(String message, int exceededAmount,
			LimitingDataInput instance) {
		super(message);
		this.amount = exceededAmount;
		this.instance = instance;
	}

	/**
	 * @return Number of bytes that could not be read (0 indicated unknown)
	 */
	public int getExceededAmount() {
		return amount;
	}

	/**
	 * @return The instance reporting this exception
	 */
	public LimitingDataInput getIntance() {
		return instance;
	}
}


text:
"enable aexpr";

import Morph from 'src/components/widgets/lively-morph.js';
import ContextMenu from 'src/client/contextmenu.js';
import {pt} from 'src/client/graphics.js';

export default class LivelyPetrinet extends Morph {

  // Initialization

  async initialize() {
    this.windowTitle = "LivelyPetrinet";
    this.registerButtons();
    this.mouseIsOnNode = false;
    this.positionUpdate = setInterval(() => this.updateConnectorPosition(), 1000);

  }

  // The connectors don't behave probperly when reloaded, because they are not connected to the components with the previous data-lively-id anymore. So we remove them and create new connectors instead (updating didnt properly work)
  async initializeConnectors() {
    for (const connector of this.connectors) {
      const fromComponent = this.getComponentFrom(connector.fromComponentId);
      const toComponent = this.getComponentFrom(connector.toComponentId);
      if (!fromComponent || !toComponent) {
        lively.error("Connector is not connected to component");
      }
      await this.addConnector(fromComponent, toComponent);
      connector.remove();

    }
  }

  detachedCallback() {
    clearInterval(this.positionUpdate);
  }

  // Access Methods

  get places() {
    return Array.from(this.querySelectorAll("lively-petrinet-place"));
  }

  get transitions() {
    const probTransitions = Array.from(this.querySelectorAll("lively-petrinet-prob-transition"));
    const codeTransitions = Array.from(this.querySelectorAll("lively-petrinet-code-transition"));
    return [...probTransitions, ...codeTransitions]
  }

  get connectors() {
    return Array.from(this.querySelectorAll("lively-petrinet-edge"))
  }

  getComponentFrom(id) {
    const allComponents = [...this.places, ...this.transitions];
    for (const component of allComponents) {
      if (component.componentId == id) {
        return component;
      }
    }
  }

  // Lively Methods

  async livelyExample() {
    await this.addPlace(pt(100, 100));
    this.places[0].addToken();
    await this.addPlace(pt(500, 300));
    await this.addTransition(pt(300, 200));
    this.addConnector(this.places[0], this.transitions[0]);
    this.addConnector(this.transitions[0],this.places[1]);
  }

  // Connector Creation

  updateAllConnectors() {
    for (const connector of this.connectors) {
      connector.updateConnector();
    }
  }

  // Add And Delete Elements

  async addConnector(fromComponent, toComponent) {
    const newConnector = await(<lively-petrinet-edge></lively-petrinet-edge>);
    this.appendChild(newConnector);
    await newConnector.connectPetrinetComponents(fromComponent, toComponent);
    // The connector has some weird behaviour, in that it is not 100% connected to the elements in the beginning. We fix this by manually updating its position.
    return newConnector;
  }

  updateConnectorPosition() {
    for (const connector of this.connectors) {
      connector.updateConnector();
    }
  }

  async addTransition(position) {
    var transition = await (<lively-petrinet-prob-transition></lively-petrinet-prob-transition>);
    this.initializeElement(transition, position);
    this.appendChild(transition);
    return transition;
  }

  async addPlace(position) {
      var place = await (<lively-petrinet-place></lively-petrinet-place>);
      this.initializeElement(place, position);
      this.appendChild(place);
      return place;
  }

  async addCodeTransition(position) {
    var codeTransition = await (<lively-petrinet-code-transition></lively-petrinet-code-transition>);
    this.initializeElement(codeTransition, position);
    this.appendChild(codeTransition);
    return codeTransition;
  }

  async initializeElement(element, position) {
      lively.setPosition(element, position);
  }

}


text:
class AttendeesController < ApplicationController
  load_and_authorize_resource except: [:create]

  def destroy
    @attendee.destroy
    name_if_found = @attendee.contact ? @attendee.contact.full_name :
    "Contact Not Found"
    flash[:notice] = "Removed Attendee: #{@attendee.contact.full_name}"
    redirect_to edit_event_path(@attendee.event)
  end
end


text:
import {currentRoute} from '../../shared/router';

//-----------------------------------------------------------------------------
// Set window title based on the current viewed page
//
// Component name: cko-window-title
//
export default class WindowTitle {
  constructor() {
    this._routeChangedSubscription = currentRoute.subscribe(this._onRouteChanged, this);
  }

  _onRouteChanged(route) {
    var routeInfo = route.$route;
    var docTitle = '';

    if (routeInfo && routeInfo.meta) {

      if (typeof routeInfo.meta.docTitle === 'function') {
        docTitle = routeInfo.meta.docTitle(route);
      }
      else {
        docTitle = routeInfo.meta.docTitle;
      }
    }
    if (docTitle) {
      window.document.title = `${docTitle} - Knockout-Validation Docs`;
    }
    else {
      window.document.title = `Knockout-Validation Docs`;
    }
  }

  dispose() {
    if (this._routeChangedSubscription) {
      this._routeChangedSubscription.dispose();
      this._routeChangedSubscription = undefined;
    }
  }
}


text:
<!---
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
-->

## Using Arrow's HDFS (Apache Hadoop Distributed File System) interface

### Build requirements

To build the integration, pass the following option to CMake

```shell
-DARROW_HDFS=on
```

For convenience, we have bundled `hdfs.h` for libhdfs from Apache Hadoop in
Arrow's thirdparty. If you wish to build against the `hdfs.h` in your installed
Hadoop distribution, set the `$HADOOP_HOME` environment variable.

### Runtime requirements

By default, the HDFS client C++ class in `libarrow_io` uses the libhdfs JNI
interface to the Java Hadoop client. This library is loaded **at runtime**
(rather than at link / library load time, since the library may not be in your
LD_LIBRARY_PATH), and relies on some environment variables.

* `HADOOP_HOME`: the root of your installed Hadoop distribution. Often has
`lib/native/libhdfs.so`.
* `JAVA_HOME`: the location of your Java SDK installation.
* `CLASSPATH`: must contain the Hadoop jars. You can set these using:

```shell
export CLASSPATH=`$HADOOP_HOME/bin/hadoop classpath --glob`
```

* `ARROW_LIBHDFS_DIR` (optional): explicit location of `libhdfs.so` if it is
installed somewhere other than `$HADOOP_HOME/lib/native`.

To accommodate distribution-specific nuances, the `JAVA_HOME` variable may be
set to the root path for the Java SDK, the JRE path itself, or to the directory
containing the `libjvm` library.

### Mac Specifics

The installed location of Java on OS X can vary, however the following snippet
will set it automatically for you:

```shell
export JAVA_HOME=$(/usr/libexec/java_home)
```

Homebrew's Hadoop does not have native libs. Apache doesn't build these, so
users must build Hadoop to get the native libs. See this Stack Overflow
answer for details:

http://stackoverflow.com/a/40051353/478288

Be sure to include the path to the native libs in `JAVA_LIBRARY_PATH`:

```shell
export JAVA_LIBRARY_PATH=$HADOOP_HOME/lib/native:$JAVA_LIBRARY_PATH
```

If you get an error about needing to install Java 6, then add *BundledApp* and
*JNI* to the `JVMCapabilities` in `$JAVA_HOME/../Info.plist`. See

https://oliverdowling.com.au/2015/10/09/oracles-jre-8-on-mac-os-x-el-capitan/

https://derflounder.wordpress.com/2015/08/08/modifying-oracles-java-sdk-to-run-java-applications-on-os-x/


text:
<?php

namespace mobilejazz\yii2\cms\common\models;

use mobilejazz\yii2\cms\common\components\TimeStampActiveRecord;
use yii;
use yii\db\Expression;

/**
 * This is the base-model class for table "user_notification".
 *
 * @property integer $id
 * @property integer $user_id
 * @property string  $item_class
 * @property integer $item_id
 * @property string  $message
 * @property string  $data
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $sent_at
 * @property integer $read_at
 *
 * @property User    $user
 */
class UserNotification extends TimeStampActiveRecord
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_notification';
    }

    public function send()
    {
        $data = json_decode($this->data);
        \Yii::$app->pn->send2d($this->getUser()
                                    ->one()->username, $this->message, $data);
        $this->sent_at = new Expression('NOW()');
        $this->save();
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), [ 'id' => 'user_id' ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [ [ 'user_id', 'message' ], 'required' ],
            [ [ 'user_id', 'item_id' ], 'integer' ],
            [ [ 'data' ], 'string' ],
            [ [ 'created_at', 'updated_at', 'sent_at', 'read_at' ], 'safe' ],
            [ [ 'item_class', 'message' ], 'string', 'max' => 255 ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id'         => Yii::t('app', 'ID'),
            'user_id'    => Yii::t('app', 'User ID'),
            'item_class' => Yii::t('app', 'Item Class'),
            'item_id'    => Yii::t('app', 'Item ID'),
            'message'    => Yii::t('app', 'Message'),
            'data'       => Yii::t('app', 'Data'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
            'sent_at'    => Yii::t('app', 'Sent At'),
            'read_at'    => Yii::t('app', 'Read At'),
        ];
    }
}


text:
(function () {
    'use strict';

    angular
        .module('ng-easy-crud')
        .directive('ecrudList', ecrudList);

    ecrudList.$inject = ['Restangular', '$location'];

    function ecrudList(Restangular, $location) {
        var directive = {
            restrict: 'E',
            transclude: true,
            scope: {},
            templateUrl: getTemplatePath,
            link: link
        };
        return directive;

        function getTemplatePath(element, attrs) {
            return attrs.ecrudTemplate;
        }

        function getResourcePath(attrs) {
            return attrs.ecrudResource;
        }

	    // for future use
	    function getPrefix(attrs) {
	        if (attrs.hasOwnProperty('ecrudPrefix')) {
                return attrs.ecrudPrefix;
	        } else {
                return ''
            }
	    }

        function link(scope, element, attrs) {
            scope.loadData = loadData;

            scope.$on('$locationChangeSuccess', function(event){
                loadData();
            });

            function loadData() {
                // loading = true for the use in template (eg show/hide sth)
		        var query = $location.search();
                scope.loading = true;
                Restangular.all(getResourcePath(attrs)).getList(query).then(function(data) {
                    scope.object_list = data;
                    console.log('list:');
                    console.log(scope.object_list);
                })
		        scope.loading = false;
            }
            scope.loadData();
        }
    }
})();


text:
<?php

namespace Campus\Entity;

/**
 * School
 *
 * @Table(name="school")
 * @Entity(repositoryClass = "Campus\Entity\Repository\SchoolRepository")
 */
class School
{
    /**
     * @var bigint $schoolId
     *
     * @Column(name="school_id", type="bigint", nullable=false)
     * @Id
     * @GeneratedValue(strategy="IDENTITY")
     */
    private $schoolId;

    /**
     * @var string $schoolName
     *
     * @Column(name="school_name", type="string", length=100, nullable=false)
     */
    private $schoolName;

    /**
     * @var string $principal
     *
     * @Column(name="principal", type="string", length=20, nullable=true)
     */
    private $principal;

    /**
     * @var string $chairman
     *
     * @Column(name="chairman", type="string", length=20, nullable=true)
     */
    private $chairman;

    /**
     * @var string $adminUsername
     *
     * @Column(name="admin_username", type="string", length=100, nullable=false)
     */
    private $adminUsername;

    /**
     * @var string $adminPassword
     *
     * @Column(name="admin_password", type="string", length=100, nullable=false)
     */
    private $adminPassword;

    /**
     * @var string $streetAddress
     *
     * @Column(name="street_address", type="string", length=100, nullable=false)
     */
    private $streetAddress;

    /**
     * @var string $subscriptionDate
     *
     * @Column(name="subscription_date", type="string", length=100, nullable=false)
     */
    private $subscriptionDate;

    /**
     * @var string $expiryDate
     *
     * @Column(name="expiry_date", type="string", length=100, nullable=false)
     */
    private $expiryDate;

    /**
     * Get schoolId
     *
     * @return bigint $schoolId
     */
    public function getSchoolId()
    {
        return $this->schoolId;
    }

    /**
     * Set schoolName
     *
     * @param string $schoolName
     */
    public function setSchoolName($schoolName)
    {
        $this->schoolName = $schoolName;
    }

    /**
     * Get schoolName
     *
     * @return string $schoolName
     */
    public function getSchoolName()
    {
        return $this->schoolName;
    }

    /**
     * Set principal
     *
     * @param string $principal
     */
    public function setPrincipal($principal)
    {
        $this->principal = $principal;
    }

    /**
     * Get principal
     *
     * @return string $principal
     */
    public function getPrincipal()
    {
        return $this->principal;
    }

    /**
     * Set chairman
     *
     * @param string $chairman
     */
    public function setChairman($chairman)
    {
        $this->chairman = $chairman;
    }

    /**
     * Get chairman
     *
     * @return string $chairman
     */
    public function getChairman()
    {
        return $this->chairman;
    }

    /**
     * Set adminUsername
     *
     * @param string $adminUsername
     */
    public function setUsername($adminUsername)
    {
        $this->adminUsername = $adminUsername;
    }

    /**
     * Get adminUsername
     *
     * @return string $adminUsername
     */
    public function getUsername()
    {
        return $this->adminUsername;
    }

    /**
     * Set adminPassword
     *
     * @param string $adminPassword
     */
    public function setPassword($adminPassword)
    {
        $this->adminPassword = $adminPassword;
    }

    /**
     * Get adminPassword
     *
     * @return string $adminPassword
     */
    public function getPassword()
    {
        return $this->adminPassword;
    }

    /**
     * Set streetAddress
     *
     * @param string $streetAddress
     */
    public function setStreetAddress($streetAddress)
    {
        $this->streetAddress = $streetAddress;
    }

    /**
     * Get streetAddress
     *
     * @return string $streetAddress
     */
    public function getStreetAddress()
    {
        return $this->streetAddress;
    }

    /**
     * Set subscriptionDate
     *
     * @param string $subscriptionDate
     */
    public function setSubscriptionDate($subscriptionDate)
    {
        $this->subscriptionDate = $subscriptionDate;
    }

    /**
     * Get subscriptionDate
     *
     * @return string $subscriptionDate
     */
    public function getSubscriptionDate()
    {
        return $this->subscriptionDate;
    }

    /**
     * Set expiryDate
     *
     * @param string $expiryDate
     */
    public function setExpiryDate($expiryDate)
    {
        $this->expiryDate = $expiryDate;
    }

    /**
     * Get expiryDate
     *
     * @return string $expiryDate
     */
    public function getExpiryDate()
    {
        return $this->expiryDate;
    }
}


text:
from __future__ import absolute_import, print_function

import os
import os.path
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

NAME = "future"
PACKAGES = ["future",
            "future.builtins",
            "future.types",
            "future.standard_library",
            "future.backports",
            "future.backports.email",
            "future.backports.email.mime",
            "future.backports.html",
            "future.backports.http",
            "future.backports.test",
            "future.backports.urllib",
            "future.backports.xmlrpc",
            "future.moves",
            "future.moves.dbm",
            "future.moves.html",
            "future.moves.http",
            "future.moves.test",
            "future.moves.tkinter",
            "future.moves.urllib",
            "future.moves.xmlrpc",
            "future.tests",     # for future.tests.base
            # "future.tests.test_email",
            "future.utils",
            "past",
            "past.builtins",
            "past.types",
            "past.utils",
            "past.translation",
            "libfuturize",
            "libfuturize.fixes",
            "libpasteurize",
            "libpasteurize.fixes",
           ]

# PEP 3108 stdlib moves:
if sys.version_info[:2] < (3, 0):
    PACKAGES += [
            "builtins",
            # "configparser",  # removed in v0.16.0
            "copyreg",
            "html",
            "http",
            "queue",
            "reprlib",
            "socketserver",
            "tkinter",
            "winreg",
            "xmlrpc",
            "_dummy_thread",
            "_markupbase",
            "_thread",
           ]

PACKAGE_DATA = {'': [
                     'README.rst',
                     'LICENSE.txt',
                     'futurize.py',
                     'pasteurize.py',
                     'check_rst.sh',
                     'TESTING.txt',
                    ],
                'tests': ['*.py'],
                }

import src.future
VERSION = src.future.__version__
DESCRIPTION = "Clean single-source support for Python 3 and 2"
LONG_DESC = src.future.__doc__
AUTHOR = "Ed Schofield"
AUTHOR_EMAIL = "ed@pythoncharmers.com"
URL="https://python-future.org"
LICENSE = "MIT"
KEYWORDS = "future past python3 migration futurize backport six 2to3 modernize pasteurize 3to2"
CLASSIFIERS = [
    "Programming Language :: Python",
    "Programming Language :: Python :: 2",
    "Programming Language :: Python :: 2.6",
    "Programming Language :: Python :: 2.7",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.3",
    "Programming Language :: Python :: 3.4",
    "Programming Language :: Python :: 3.5",
    "Programming Language :: Python :: 3.6",
    "Programming Language :: Python :: 3.7",
    "License :: OSI Approved",
    "License :: OSI Approved :: MIT License",
    "Development Status :: 4 - Beta",
    "Intended Audience :: Developers",
]

setup_kwds = {}

# * Important *
# We forcibly remove the build folder to avoid breaking the
# user's Py3 installation if they run "python2 setup.py
# build" and then "python3 setup.py install".

try:
    # If the user happens to run:
    #     python2 setup.py build
    #     python3 setup.py install
    # then folders like "copyreg" will be in build/lib.
    # If so, we CANNOT let the user install this, because
    # this may break his/her Python 3 install, depending on the folder order in
    # sys.path. (Running "import html" etc. may pick up our Py2
    # substitute packages, instead of the intended system stdlib modules.)
    SYSTEM_MODULES = set([
                          '_dummy_thread',
                          '_markupbase',
                          '_thread',
                          'builtins',
                          # Catch the case that configparser is in the build folder
                          # from a previous version of `future`:
                          'configparser',
                          'copyreg',
                          'html',
                          'http',
                          'queue',
                          'reprlib',
                          'socketserver',
                          'tkinter',
                          'winreg',
                          'xmlrpc'
                         ])

    if sys.version_info[0] >= 3:
        # Do any of the above folders exist in build/lib?
        files = os.listdir(os.path.join('build', 'lib'))
        if len(set(files) & set(SYSTEM_MODULES)) > 0:
            print('ERROR: Your build folder is in an inconsistent state for '
                  'a Python 3.x install. Please remove it manually and run '
                  'setup.py again.', file=sys.stderr)
            sys.exit(1)
except OSError:
    pass

setup(name=NAME,
      version=VERSION,
      author=AUTHOR,
      author_email=AUTHOR_EMAIL,
      url=URL,
      description=DESCRIPTION,
      long_description=LONG_DESC,
      license=LICENSE,
      keywords=KEYWORDS,
      entry_points={
          'console_scripts': [
              'futurize = libfuturize.main:main',
              'pasteurize = libpasteurize.main:main'
          ]
      },
      package_dir={'': 'src'},
      packages=PACKAGES,
      package_data=PACKAGE_DATA,
      include_package_data=True,
      python_requires=">=2.6, !=3.0.*, !=3.1.*, !=3.2.*",
      classifiers=CLASSIFIERS,
      **setup_kwds
     )


text:
namespace GafferScene
{

IE_CORE_FORWARDDECLARE( ScenePlug )

class GAFFERSCENE_API Render : public GafferDispatch::TaskNode
{

	public :

		Render( const std::string &name=defaultName<Render>() );
		~Render() override;

		GAFFER_GRAPHCOMPONENT_DECLARE_TYPE( GafferScene::Render, GafferScene::RenderTypeId, GafferDispatch::TaskNode );

		enum Mode
		{
			RenderMode = 0,
			SceneDescriptionMode = 1
		};

		ScenePlug *inPlug();
		const ScenePlug *inPlug() const;

		Gaffer::StringPlug *rendererPlug();
		const Gaffer::StringPlug *rendererPlug() const;

		Gaffer::IntPlug *modePlug();
		const Gaffer::IntPlug *modePlug() const;

		Gaffer::StringPlug *fileNamePlug();
		const Gaffer::StringPlug *fileNamePlug() const;

		ScenePlug *outPlug();
		const ScenePlug *outPlug() const;

	protected :

		// Constructor for derived classes which wish to hardcode the renderer type. Perhaps
		// at some point we won't even have derived classes, but instead will always use the
		// base class? At the moment the main purpose of the derived classes is to force the
		// loading of the module which registers the required renderer type.
		Render( const IECore::InternedString &rendererType, const std::string &name );

		void preTasks( const Gaffer::Context *context, Tasks &tasks ) const override;
		void postTasks( const Gaffer::Context *context, Tasks &tasks ) const override;
		IECore::MurmurHash hash( const Gaffer::Context *context ) const override;
		void execute() const override;

	private :

		ScenePlug *adaptedInPlug();
		const ScenePlug *adaptedInPlug() const;

		static size_t g_firstPlugIndex;

		// Friendship for the bindings
		friend struct GafferDispatchBindings::Detail::TaskNodeAccessor;

};

IE_CORE_DECLAREPTR( Render );

} // namespace GafferScene

#endif // GAFFERSCENE_RENDER_H


text:
package kr.co.shineware.nlp.komoran.run;

import kr.co.shineware.nlp.komoran.core.Komoran;
import kr.co.shineware.nlp.komoran.modeler.builder.ModelBuilder;

import java.util.HashMap;
import java.util.Map;

public class NewKomoranConsoleRunner2 {
    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            printUsage();
            return;
        }

        Map<String, String> argMap = parseArgs(args);
        if (argMap == null) {
            printUsage();
            return;
        }
        if(!argMap.containsKey("-thread")) {
            argMap.put("-thread", "4");
        }

        if (argMap.containsKey("-train") && argMap.containsKey("-model")) {
            long begin = System.currentTimeMillis();
            printTrainingInfo(argMap);
            training(argMap);
            long end = System.currentTimeMillis();
            System.out.println("Training elapsed time : " + (end - begin) + "ms");

        } else if (argMap.containsKey("-in") && argMap.containsKey("-out") && argMap.containsKey("-model")) {
            long begin = System.currentTimeMillis();
            printAnalyzeInfo(argMap);
            analyzing(argMap);
            long end = System.currentTimeMillis();
            System.out.println("Analyze elapsed time : " + (end - begin) + "ms");
        } else {
            printUsage();
            return;
        }
    }

    private static void training(Map<String, String> argMap) {
        ModelBuilder modelBuilder = new ModelBuilder();
        if (argMap.containsKey("-externalDic")) {
            modelBuilder.setExternalDic(argMap.get("-externalDic"));
        }
        modelBuilder.buildPath(argMap.get("-train"));
        modelBuilder.save(argMap.get("-model"));
    }

    private static void printTrainingInfo(Map<String, String> argMap) {
        System.out.println("training data : " + argMap.get("-train"));
        if (argMap.containsKey("-externalDic")) {
            System.out.println("externalDic : " + argMap.get("-externalDic"));
        }
        System.out.println("model path(output dir) : " + argMap.get("-model"));
    }

    private static void analyzing(Map<String, String> argMap) throws Exception {
        Komoran komoran = new Komoran(argMap.get("-model"));
        if (argMap.containsKey("-userDic")) {
            komoran.setUserDic(argMap.get("-userDic"));
        }
        if (argMap.containsKey("-fwd")) {
            komoran.setFWDic(argMap.get("-fwd"));
        }

        komoran.analyzeTextFile(argMap.get("-in"), argMap.get("-out"), Integer.parseInt(argMap.get("-thread")));
    }

    private static void printAnalyzeInfo(Map<String, String> argMap) {
        System.out.println("input file : " + argMap.get("-in"));
        System.out.println("output file : " + argMap.get("-out"));
        System.out.println("model path : " + argMap.get("-model"));
        System.out.println("thread : " + argMap.get("-thread"));
        if (argMap.containsKey("-userDic")) {
            System.out.println("user dic : " + argMap.get("-userDic"));
        }
        if (argMap.containsKey("-fwd")) {
            System.out.println("fwd : " + argMap.get("-fwd"));
        }
    }

    private static Map<String, String> parseArgs(String[] args) {
        try {
            Map<String, String> argMap = new HashMap<>();
            for (int i = 0; i < args.length; i++) {
                switch (args[i]) {
                    case "-train":
                        argMap.put(args[i], args[i + 1]);
                        i++;
                        break;
                    case "-externalDic":
                        argMap.put(args[i], args[i + 1]);
                        i++;
                        break;
                    case "-model":
                        argMap.put(args[i], args[i + 1]);
                        i++;
                        break;
                    case "-userDic":
                        argMap.put(args[i], args[i + 1]);
                        i++;
                        break;
                    case "-fwd":
                        argMap.put(args[i], args[i + 1]);
                        i++;
                        break;
                    case "-in":
                        argMap.put(args[i], args[i + 1]);
                        i++;
                        break;
                    case "-out":
                        argMap.put(args[i], args[i + 1]);
                        i++;
                        break;
                    case "-thread":
                        argMap.put(args[i], args[i + 1]);
                        i++;
                        break;
                    default:
                        return null;
                }
            }
            return argMap;
        } catch (Exception e) {
            return null;
        }
    }

    private static void printUsage() {
        System.out.println("[코모란 트레이닝 방법]");
        System.out.println("\tjava -jar KOMORAN.jar -train '학습 데이터가 포함된 폴더명' [-externalDic '학습 시 추가될 사전'] -model '학습 모델이 저장될 폴더명'");
        System.out.println("[코모란 파일 분석 방법]");
        System.out.println("\tjava -jar KOMORAN.jar -model '학습된 모델이 포함된 폴더명' [-userDic '사용사 사전 파일'] [-fwd '기분석 사전 파일'] -in '분석 대상 파일' -out '분석 결과 파일' -thread '쓰레드 수'");
    }
}


text:
void user_implemented_init(struct mfb_window *window);

void user_implemented_update(struct mfb_window *window);