text:
require 'spec_helper'
require 'post_creator'
require 'topic_subtype'

describe PostCreator do

  before do
    ActiveRecord::Base.observers.enable :all
  end

  let(:user) { Fabricate(:user) }

  context "new topic" do
    let(:category) { Fabricate(:category, user: user) }
    let(:topic) { Fabricate(:topic, user: user) }
    let(:basic_topic_params) { {title: "hello world topic", raw: "my name is fred", archetype_id: 1} }
    let(:image_sizes) { {'http://an.image.host/image.jpg' => {"width" => 111, "height" => 222}} }

    let(:creator) { PostCreator.new(user, basic_topic_params) }
    let(:creator_with_category) { PostCreator.new(user, basic_topic_params.merge(category: category.id )) }
    let(:creator_with_meta_data) { PostCreator.new(user, basic_topic_params.merge(meta_data: {hello: "world"} )) }
    let(:creator_with_image_sizes) { PostCreator.new(user, basic_topic_params.merge(image_sizes: image_sizes)) }

    it "can be created with auto tracking disabled" do
      p = PostCreator.create(user, basic_topic_params.merge(auto_track: false))
      # must be 0 otherwise it will think we read the topic which is clearly untrue
      TopicUser.where(user_id: p.user_id, topic_id: p.topic_id).count.should == 0
    end

    it "ensures the user can create the topic" do
      Guardian.any_instance.expects(:can_create?).with(Topic,nil).returns(false)
      lambda { creator.create }.should raise_error(Discourse::InvalidAccess)
    end

    context "invalid title" do

      let(:creator_invalid_title) { PostCreator.new(user, basic_topic_params.merge(title: 'a')) }

      it "has errors" do
        creator_invalid_title.create
        expect(creator_invalid_title.errors).to be_present
      end

    end

    context "invalid raw" do

      let(:creator_invalid_raw) { PostCreator.new(user, basic_topic_params.merge(raw: '')) }

      it "has errors" do
        creator_invalid_raw.create
        expect(creator_invalid_raw.errors).to be_present
      end

    end

    context "success" do

      it "doesn't return true for spam" do
        creator.create
        creator.spam?.should be_false
      end

      it "does not notify on system messages" do
        admin = Fabricate(:admin)
        messages = MessageBus.track_publish do
          p = PostCreator.create(admin, basic_topic_params.merge(post_type: Post.types[:moderator_action]))
          PostCreator.create(admin, basic_topic_params.merge(topic_id: p.topic_id, post_type: Post.types[:moderator_action]))
        end
        # don't notify on system messages they introduce too much noise
        channels = messages.map(&:channel)
        channels.find{|s| s =~ /unread/}.should be_nil
        channels.find{|s| s =~ /new/}.should be_nil
      end

      it "generates the correct messages for a secure topic" do

        admin = Fabricate(:admin)

        cat = Fabricate(:category)
        cat.set_permissions(:admins => :full)
        cat.save

        created_post = nil
        reply = nil

        messages = MessageBus.track_publish do
          created_post = PostCreator.new(admin, basic_topic_params.merge(category: cat.id)).create
          reply = PostCreator.new(admin, raw: "this is my test reply 123 testing", topic_id: created_post.topic_id).create
        end

        topic_id = created_post.topic_id

        messages.map{|m| m.channel}.sort.should == [ "/new",
                                                     "/users/#{admin.username}",
                                                     "/users/#{admin.username}",
                                                     "/unread/#{admin.id}",
                                                     "/unread/#{admin.id}",
                                                     "/topic/#{created_post.topic_id}"
                                                   ].sort
        admin_ids = [Group[:admins].id]

        messages.any?{|m| m.group_ids != admin_ids && m.user_ids != [admin.id]}.should be_false
      end

      it 'generates the correct messages for a normal topic' do

        p = nil
        messages = MessageBus.track_publish do
          p = creator.create
          topic_id = p.topic_id
        end

        latest = messages.find{|m| m.channel == "/new"}
        latest.should_not be_nil

        read = messages.find{|m| m.channel == "/unread/#{p.user_id}"}
        read.should_not be_nil

        user_action = messages.find{|m| m.channel == "/users/#{p.user.username}"}
        user_action.should_not be_nil

        messages.length.should == 3
      end

      it 'extracts links from the post' do
        TopicLink.expects(:extract_from).with(instance_of(Post))
        creator.create
      end

      it 'queues up post processing job when saved' do
        Jobs.expects(:enqueue).with(:feature_topic_users, has_key(:topic_id))
        Jobs.expects(:enqueue).with(:process_post, has_key(:post_id))
        creator.create
      end

      it 'passes the invalidate_oneboxes along to the job if present' do
        Jobs.stubs(:enqueue).with(:feature_topic_users, has_key(:topic_id))
        Jobs.expects(:enqueue).with(:process_post, has_key(:invalidate_oneboxes))
        creator.opts[:invalidate_oneboxes] = true
        creator.create
      end

      it 'passes the image_sizes along to the job if present' do
        Jobs.stubs(:enqueue).with(:feature_topic_users, has_key(:topic_id))
        Jobs.expects(:enqueue).with(:process_post, has_key(:image_sizes))
        creator.opts[:image_sizes] = {'http://an.image.host/image.jpg' => {'width' => 17, 'height' => 31}}
        creator.create
      end

      it 'assigns a category when supplied' do
        creator_with_category.create.topic.category.should == category
      end

      it 'adds  meta data from the post' do
        creator_with_meta_data.create.topic.meta_data['hello'].should == 'world'
      end

      it 'passes the image sizes through' do
        Post.any_instance.expects(:image_sizes=).with(image_sizes)
        creator_with_image_sizes.create
      end

      it 'increases topic response counts' do
        first_post = creator.create

        # ensure topic user is correct
        topic_user = first_post.user.topic_users.where(topic_id: first_post.topic_id).first
        topic_user.should be_present
        topic_user.should be_posted
        topic_user.last_read_post_number.should == first_post.post_number
        topic_user.seen_post_count.should == first_post.post_number

        user2 = Fabricate(:coding_horror)
        user2.user_stat.topic_reply_count.should == 0

        first_post.user.user_stat.reload.topic_reply_count.should == 0

        PostCreator.new(user2, topic_id: first_post.topic_id, raw: "this is my test post 123").create

        first_post.user.user_stat.reload.topic_reply_count.should == 0

        user2.user_stat.reload.topic_reply_count.should == 1
      end
    end

    context 'when auto-close param is given' do
      it 'ensures the user can auto-close the topic, but ignores auto-close param silently' do
        Guardian.any_instance.stubs(:can_moderate?).returns(false)
        post = PostCreator.new(user, basic_topic_params.merge(auto_close_time: 2)).create
        post.topic.auto_close_at.should be_nil
      end
    end
  end

  context 'uniqueness' do

    let!(:topic) { Fabricate(:topic, user: user) }
    let(:basic_topic_params) { { raw: 'test reply', topic_id: topic.id, reply_to_post_number: 4} }
    let(:creator) { PostCreator.new(user, basic_topic_params) }

    context "disabled" do
      before do
        SiteSetting.stubs(:unique_posts_mins).returns(0)
        creator.create
      end

      it "returns true for another post with the same content" do
        new_creator = PostCreator.new(user, basic_topic_params)
        new_creator.create.should be_present
      end
    end

    context 'enabled' do
      let(:new_post_creator) { PostCreator.new(user, basic_topic_params) }

      before do
        SiteSetting.stubs(:unique_posts_mins).returns(10)
        creator.create
      end

      it "returns blank for another post with the same content" do
        new_post_creator.create
        new_post_creator.errors.should be_present
      end

      it "returns a post for admins" do
        user.admin = true
        new_post_creator.create
        new_post_creator.errors.should be_blank
      end

      it "returns a post for moderators" do
        user.moderator = true
        new_post_creator.create
        new_post_creator.errors.should be_blank
      end
    end

  end

  context "host spam" do

    let!(:topic) { Fabricate(:topic, user: user) }
    let(:basic_topic_params) { { raw: 'test reply', topic_id: topic.id, reply_to_post_number: 4} }
    let(:creator) { PostCreator.new(user, basic_topic_params) }

    before do
      Post.any_instance.expects(:has_host_spam?).returns(true)
    end

    it "does not create the post" do
      GroupMessage.stubs(:create)
      creator.create
      creator.errors.should be_present
      creator.spam?.should be_true
    end

    it "sends a message to moderators" do
      GroupMessage.expects(:create).with do |group_name, msg_type, params|
        group_name == Group[:moderators].name and msg_type == :spam_post_blocked and params[:user].id == user.id
      end
      creator.create
    end

  end

  # more integration testing ... maximise our testing
  context 'existing topic' do
    let!(:topic) { Fabricate(:topic, user: user) }
    let(:creator) { PostCreator.new(user, raw: 'test reply', topic_id: topic.id, reply_to_post_number: 4) }

    it 'ensures the user can create the post' do
      Guardian.any_instance.expects(:can_create?).with(Post, topic).returns(false)
      lambda { creator.create }.should raise_error(Discourse::InvalidAccess)
    end

    context 'success' do
      it 'create correctly' do
        post = creator.create
        Post.count.should == 1
        Topic.count.should == 1
        post.reply_to_post_number.should == 4
      end

    end

  end

  context "cooking options" do
    let(:raw) { "this is my awesome message body hello world" }

    it "passes the cooking options through correctly" do
      creator = PostCreator.new(user,
                                title: 'hi there welcome to my topic',
                                raw: raw,
                                cooking_options: { traditional_markdown_linebreaks: true })

      Post.any_instance.expects(:cook).with(raw, has_key(:traditional_markdown_linebreaks)).returns(raw)
      creator.create
    end
  end

  # integration test ... minimise db work
  context 'private message' do
    let(:target_user1) { Fabricate(:coding_horror) }
    let(:target_user2) { Fabricate(:moderator) }
    let(:unrelated) { Fabricate(:user) }
    let(:post) do
      PostCreator.create(user, title: 'hi there welcome to my topic',
                               raw: "this is my awesome message @#{unrelated.username_lower}",
                               archetype: Archetype.private_message,
                               target_usernames: [target_user1.username, target_user2.username].join(','))
    end

    it 'acts correctly' do
      post.topic.archetype.should == Archetype.private_message
      post.topic.topic_allowed_users.count.should == 3

      # does not notify an unrelated user
      unrelated.notifications.count.should == 0
      post.topic.subtype.should == TopicSubtype.user_to_user

      # if a mod replies they should be added to the allowed user list
      mod = Fabricate(:moderator)
      PostCreator.create(mod, raw: 'hi there welcome topic, I am a mod',
                         topic_id: post.topic_id)

      post.topic.reload
      post.topic.topic_allowed_users.where(user_id: mod.id).count.should == 1
    end
  end

  context 'private message to group' do
    let(:target_user1) { Fabricate(:coding_horror) }
    let(:target_user2) { Fabricate(:moderator) }
    let(:group) do
      g = Fabricate.build(:group)
      g.add(target_user1)
      g.add(target_user2)
      g.save
      g
    end
    let(:unrelated) { Fabricate(:user) }
    let(:post) do
      PostCreator.create(user, title: 'hi there welcome to my topic',
                               raw: "this is my awesome message @#{unrelated.username_lower}",
                               archetype: Archetype.private_message,
                               target_group_names: group.name)
    end

    it 'acts correctly' do
      post.topic.archetype.should == Archetype.private_message
      post.topic.topic_allowed_users.count.should == 1
      post.topic.topic_allowed_groups.count.should == 1

      # does not notify an unrelated user
      unrelated.notifications.count.should == 0
      post.topic.subtype.should == TopicSubtype.user_to_user
      target_user1.notifications.count.should == 1
      target_user2.notifications.count.should == 1
    end
  end

  context 'setting created_at' do
    created_at = 1.week.ago
    let(:topic) do
      PostCreator.create(user,
                         raw: 'This is very interesting test post content',
                         title: 'This is a very interesting test post title',
                         created_at: created_at)
    end

    let(:post) do
      PostCreator.create(user,
                         raw: 'This is very interesting test post content',
                         topic_id: Topic.last,
                         created_at: created_at)
    end

    it 'acts correctly' do
      topic.created_at.should be_within(10.seconds).of(created_at)
      post.created_at.should be_within(10.seconds).of(created_at)
    end
  end

  context 'disable validations' do
    it 'can save a post' do
      creator = PostCreator.new(user, raw: 'q', title: 'q', skip_validations: true)
      post = creator.create
      creator.errors.should be_nil
    end
  end

  describe "word_count" do
    it "has a word count" do
      creator = PostCreator.new(user, title: 'some inspired poetry for a rainy day', raw: 'mary had a little lamb, little lamb, little lamb. mary had a little lamb')
      post = creator.create
      post.word_count.should == 14

      post.topic.reload
      post.topic.word_count.should == 14
    end
  end

end


text:
namespace llvm {

class MemoryBuffer;
class Target;
class raw_ostream;
class SourceMgr;
class MCSubtargetInfo;
class MCStreamer;

class Disassembler {
public:
  static int disassemble(const Target &T,
                         const std::string &Triple,
                         MCSubtargetInfo &STI,
                         MCStreamer &Streamer,
                         MemoryBuffer &Buffer,
                         SourceMgr &SM,
                         raw_ostream &Out);

  static int disassembleEnhanced(const std::string &tripleString,
                                 MemoryBuffer &buffer,
                                 SourceMgr &SM,
                                 raw_ostream &Out);
};

} // namespace llvm

#endif

redpajama_set_name: RedPajamaGithub


text:
package org.rpwf;

import org.rpwf.model.ORM;

/**
 * The interface through which the user can interact with the framework.
 */
public interface FrameworkContext {

  /**
   * gets the configured and initialized ORM.
   * @return the ORM
   */
  public ORM getORM();

  /**
   * can asked for dev Mode
   * @return true if dev Mode is set
   */
  public boolean isDevMode();

}


text:
// U3.W9:JQuery

// I worked on this challenge [by myself, with: ].
// This challenge took me [#] hours.

$(document).ready(function(){

//RELEASE 0:
  //link the image

//RELEASE 1:

  //Link this script and the jQuery library to the jQuery_example.html file and analyze what this code does.

$('body').css({'background-color': 'pink'})

//RELEASE 2:
  //Add code here to select elements of the DOM
bodyElement = $("body");

//RELEASE 3:
  // Add code here to modify the css and html of DOM elements
$("body > h1").css({"color": "#6666ff"})
$("body > h1").css({"border": "solid 1px black"})
$("body > h1").css({"visibility": "hidden"})

//RELEASE 4: Event Listener
  // Add the code for the event listener here
 $('img').on('mouseover', function(e){
    e.preventDefault()
    $(this).attr('src', 'http://www.virginiaherpetologicalsociety.com/reptiles/snakes/northern-copperhead/nch_page_copperhead02.jpg')
  })
 $('img').on('mouseout', function(e) {
    e.preventDefault()
    $(this).attr('src', 'dbc_logo.png')
 })

//RELEASE 5: Experiment on your own
$('img').on('click', function() {
  $(this).css({"border": "solid 4px black"})
  $(this).animate({"padding": "20px"}, "1000")
})
$('img').on('dblclick', function() {
  $(this).animate({height: "toggle"}, "2000");
})

})  // end of the document.ready function: do not remove or write DOM manipulation below this.
/*
=====Reflection=====
What is jQuery?

  jQuery is a JavaScript framework designed to make websites more interactive
  and responsive. Basically, it's a collection of functions that make it much
  easier for developers to add user events, animate things, etc.

What does jQuery do for you?

  jQuery makes it possible to make a lot of user events, animations, etc.
  without deep technical knowledge of JS. Everything in jQuerey is built
  using JS code, so theoretically it should be possible to replicate the same
  effects without jQuery. That said, from my experience, even something so
  simple as moving a div to the left by 10 pixels is a rather complicated
  affair in simple JavaScript.

What did you learn about the DOM while working on this challenge?

  I'd already been messing around with the DOM prior to this challenge, but
  it was really interesting to see all thing things that jQuery can do.
  It's an amazing tool and I'm actually pretty excited to try and use it
  in my own site.

*/


text:
[YES]

### Which distribution are you using ?

[ARCH]

### Are you a noob ?

[YES]


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

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="tr<caret>"/>
</selector>


text:
var win = Titanium.UI.currentWindow;
var twitterApi = Ti.App.twitterApi;
win.barColor = '#79D448';

var sourceSelect = Titanium.UI.createOptionDialog({
    options:['撮影する', 'アルバムから選ぶ', 'キャンセル'],
    cancel:2,
    title:'アゲアゲを激写'
});

sourceSelect.addEventListener('click', function(e) {
    switch( e.index ) {
        case 0:
            startCamera();
            break;
        case 1:
            selectFromPhotoGallery();
            break;
        default:
            win.close();
            break;
    }
});
sourceSelect.show();

function startCamera() {
    Titanium.Media.showCamera({
        success: function(event) {
            var image = event.media;
            var uploadWindow = Titanium.UI.createWindow({
                url: "uploadWindow.js",
                media: image,
                title: "Newあげあげ",
            });
            uploadWindow.open({
                transition:Titanium.UI.iPhone.AnimationStyle.CURL_UP
            });
            // win.close();
        },
        //cancel:function(){},
        error: function(error) {
            if (error.code == Titanium.Media.NO_CAMERA) {
                alert('カメラがありません');
            }
        },
        saveToPhotoGallery:true,
        allowEditing:true,
        mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO]
    });
}

function selectFromPhotoGallery() {
    Ti.Media.openPhotoGallery({
        success: function(event) {
            var image = event.media;
            var uploadWindow = Titanium.UI.createWindow({
                url: "uploadWindow.js",
                media: image,
                title: "Newあげあげ"
            });
            uploadWindow.open({
                transition:Titanium.UI.iPhone.AnimationStyle.CURL_UP
            });
            //			Titanium.UI.currentTab.open(uploadWindow);
            // win.close();
        },
        // error:  function(error) { },
        // cancel: function() { },
        allowEditing: true,
        mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO]
    });
}


text:
<?php

class usuarioDAOExt extends usuarioDAO {

}


text:
"""
Django settings for aclarknet project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', 'tt$q#-ee*p+th4(o_zc#u-s2ts(6jl=boi60xu1^s^ei4s7i1v')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django_admin_bootstrapped',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'aclarknet.aclarknet',
    'cumulus',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'aclarknet.urls'

WSGI_APPLICATION = 'aclarknet.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Parse database configuration from $DATABASE_URL
if os.getenv('DATABASE_URL'):
    import dj_database_url
    DATABASES['default'] = dj_database_url.config()

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'

# django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
STATIC_ROOT = os.path.join(BASE_DIR, 'aclarknet', 'aclarknet', 'static')

# Send mail with sendgrid
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 587
EMAIL_HOST_USER = os.environ.get('SENDGRID_USERNAME')
EMAIL_HOST_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'Alex Clark <aclark@aclark.net>'
MANAGERS = (
    'aclark@aclark.net',
)

# Admin uploaded files e.g. team member pics
CUMULUS = {
    'USERNAME': 'aclark4life',
    'API_KEY': os.environ.get('CLOUDFILES_API_KEY'),
    'CONTAINER': 'aclarknet-django',
    'PYRAX_IDENTITY_TYPE': 'rackspace',
}
DEFAULT_FILE_STORAGE = 'cumulus.storage.SwiftclientStorage'


text:
package com.github.vbauer.houdini.service.impl;

import com.github.vbauer.houdini.model.ObjectConverterInfoValue;
import com.github.vbauer.houdini.service.ObjectConverterRegistry;
import com.github.vbauer.houdini.service.ObjectConverterService;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * {@link ObjectConverterService}.
 *
 * @author Vladislav Bauer
 */

public class ObjectConverterServiceImpl implements ObjectConverterService {

    private final ObjectConverterRegistry converterRegistry;

    public ObjectConverterServiceImpl() {
        this(new ObjectConverterRegistryImpl());
    }

    public ObjectConverterServiceImpl(final ObjectConverterRegistry converterRegistry) {
        this.converterRegistry = converterRegistry;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ObjectConverterRegistry getConverterRegistry() {
        return converterRegistry;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <R> R convert(final Class<R> resultClass, final Object... sources) {
        final ObjectConverterRegistry registry = getConverterRegistry();
        final ObjectConverterInfoValue<R> converterInfo = registry.findConverter(resultClass, sources);
        return processObject(converterInfo, sources);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <R, S> Set<R> convert(final Class<R> resultClass, final Set<S> sources) {
        return processObjects(sources, resultClass, new HashSet<>());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <R, S> List<R> convert(final Class<R> resultClass, final List<S> sources) {
        return processObjects(sources, resultClass, new ArrayList<>());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <R, S> Object convertToOneOrList(final Class<R> resultClass, final List<S> sources) {
        return oneOrMany(processObjects(sources, resultClass, new ArrayList<>()));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <R, S> Object convertToOneOrSet(final Class<R> resultClass, final Set<S> sources) {
        return oneOrMany(processObjects(sources, resultClass, new HashSet<>()));
    }

    /*
     * Internal API.
     */

    private <R, C extends Collection<R>> C processObjects(
        final Collection<?> sources, final Class<R> resultClass, final C result
    ) {
        for (final Object source : sources) {
            final ObjectConverterRegistry registry = getConverterRegistry();
            final ObjectConverterInfoValue<R> converterInfo = registry.findConverter(resultClass, source);

            result.add(processObject(converterInfo, source));
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    private <R> R processObject(
        final ObjectConverterInfoValue<R> converterInfo, final Object... sources
    ) {
        final Method method = converterInfo.getMethod();
        final Object object = converterInfo.getObject();

        try {
            return (R) method.invoke(object, sources);
        } catch (final Exception ex) {
            ReflectionUtils.handleReflectionException(ex);
            return null;
        }
    }

    private Object oneOrMany(final Collection<?> collection) {
        final int size = collection == null ? 0 : collection.size();
        switch (size) {
            case 0:
                return null;
            case 1:
                return collection.iterator().next();
            default:
                return collection;
        }
    }

}


text:
Docker Python Development Image
============

Provides an environment for doing development on python based projects.

### Installed Python Versions

* python2.6
* python2.7
* python3.2
* python3.3
* python3.4
* pypy

Also included is nginx to support web app front-end, REST APIs, or viewing generated project documentation.

### Base Image

    FROM ubuntu:trusty

### TODO

* Shrink overall image size (docker squash)


text:
RSpec.describe Showoff::Compiler::I18n do
  before(:each) do
    Showoff::Config.load(File.join(fixtures, 'i18n', 'showoff.json'))
  end

  it "selects the correct language" do
    content = <<-EOF
# This is a simple markdown slide

~~~LANG:en~~~
Hello, world!
~~~ENDLANG~~~

~~~LANG:fr~~~
Bonjour tout le monde!
~~~ENDLANG~~~
EOF

    Showoff::Locale.setContentLocale(:fr)

    # This call mutates the passed in object
    Showoff::Compiler::I18n.selectLanguage!(content)

    expect(content).to be_a(String)
    expect(content).to match(/Bonjour tout le monde!/)
    expect(content).not_to match(/Hello, world!/)
    expect(content).not_to match(/~~~LANG:[\w-]+~~~/)
    expect(content).not_to match(/~~~ENDLANG~~~/)
  end

  it "includes no languages if they don't match" do
    content = <<-EOF
# This is a simple markdown slide

~~~LANG:en~~~
Hello, world!
~~~ENDLANG~~~

~~~LANG:fr~~~
Bonjour tout le monde!
~~~ENDLANG~~~
EOF

    Showoff::Locale.setContentLocale(:js)

    # This call mutates the passed in object
    Showoff::Compiler::I18n.selectLanguage!(content)

    expect(content).to be_a(String)
    expect(content).not_to match(/Bonjour tout le monde!/)
    expect(content).not_to match(/Hello, world!/)
    expect(content).not_to match(/~~~LANG:[\w-]+~~~/)
    expect(content).not_to match(/~~~ENDLANG~~~/)
  end

  it "includes no languages if local is unset" do
    content = <<-EOF
# This is a simple markdown slide

~~~LANG:en~~~
Hello, world!
~~~ENDLANG~~~

~~~LANG:fr~~~
Bonjour tout le monde!
~~~ENDLANG~~~
EOF

    # This call mutates the passed in object
    Showoff::Compiler::I18n.selectLanguage!(content)

    expect(content).to be_a(String)
    expect(content).not_to match(/Bonjour tout le monde!/)
    expect(content).not_to match(/Hello, world!/)
    expect(content).not_to match(/~~~LANG:[\w-]+~~~/)
    expect(content).not_to match(/~~~ENDLANG~~~/)
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="title_tutorial_0">Welcome to Open Link With</string>
  <string name="description_tutorial_0">I come to rescue you whenever you get stuck in browsers.</string>
  <string name="title_tutorial_1">Did it ever happen to you?</string>
  <string name="description_tutorial_1">You click a short-link and somehow you end up being stuck in web page instead of watching the video directly.</string>
  <string name="title_tutorial_2">Share it!</string>
  <string name="description_tutorial_2">Just share it with me and I will switch apps for you.</string>
  <string name="title_tutorial_3" translatable="false">@string/title_preferred_apps</string>
  <string name="description_tutorial_3"><![CDATA[
    Select ALWAYS to tell me to open that link always with a specific app.
  ]]></string>
  <string name="title_tutorial_4" translatable="false">@string/add_to_homescreen</string>
  <string name="description_tutorial_4"><![CDATA[
    Add to Home screen to quickly access your fav links with your fav apps.
  ]]></string>
  <string name="title_tutorial_5">Usage Access</string>
  <string name="description_tutorial_5"><![CDATA[
    Give access to USAGE ACCESS and I will work better. I will detect the browser you are sharing from to act accordingly.
  ]]></string>
  <string name="usage_access_give_access">Give Access</string>
  <string name="title_preferred_apps">Preferred Apps</string>
</resources>


text:
<component name="InspectionProjectProfileManager">
  <profile version="1.0" is_locked="false">
    <option name="myName" value="Project Default" />
    <option name="myLocal" value="false" />
    <inspection_tool class="CloneDeclaresCloneNotSupported" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="EmptyCatchBlock" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="m_includeComments" value="true" />
      <option name="m_ignoreTestCases" value="true" />
      <option name="m_ignoreIgnoreParameter" value="true" />
    </inspection_tool>
    <inspection_tool class="EqualsWhichDoesntCheckParameterClass" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="FieldCanBeLocal" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlDeprecatedTag" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlUnknownAttribute" enabled="true" level="WARNING" enabled_by_default="true">
      <option name="myValues">
        <value>
          <list size="6">
            <item index="0" class="java.lang.String" itemvalue="type" />
            <item index="1" class="java.lang.String" itemvalue="wmode" />
            <item index="2" class="java.lang.String" itemvalue="src" />
            <item index="3" class="java.lang.String" itemvalue="width" />
            <item index="4" class="java.lang.String" itemvalue="height" />
            <item index="5" class="java.lang.String" itemvalue="autocomplete" />
          </list>
        </value>
      </option>
      <option name="myCustomValuesEnabled" value="true" />
    </inspection_tool>
    <inspection_tool class="IgnoreResultOfCall" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="m_reportAllNonLibraryCalls" value="false" />
      <option name="callCheckString" value="java.io.InputStream,read,java.io.InputStream,skip,java.lang.StringBuffer,toString,java.lang.StringBuilder,toString,java.lang.String,.*,java.math.BigInteger,.*,java.math.BigDecimal,.*,java.net.InetAddress,.*,java.io.File,.*" />
    </inspection_tool>
    <inspection_tool class="OctalLiteral" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="PointlessArithmeticExpression" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="m_ignoreExpressionsContainingConstants" value="false" />
    </inspection_tool>
    <inspection_tool class="SimplifiableConditionalExpression" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SimplifiableIfStatement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ThrowableResultOfMethodCallIgnored" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TrivialIf" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TrivialIfJS" enabled="false" level="WARNING" enabled_by_default="false" />
  </profile>
</component>


text:
namespace NTL {
    class ZZ;
}

namespace CryptoHelpers
{
    void Encrypt(const NTL::ZZ& source, NTL::ZZ& target,const NTL::ZZ* key = nullptr);

    void Encrypt(const unsigned long long& source, unsigned long long& target, const unsigned long long* key = nullptr);

    void ResetKey();

}


text:
package org.apache.flink.configuration.description;

import org.apache.flink.annotation.PublicEvolving;

/** Part of description that represents a block e.g. some text, linebreak or a list. */
@PublicEvolving
public interface BlockElement extends DescriptionElement {}


text:
package com.emitrom.touch4j.client.ui;

import java.util.Iterator;

import com.emitrom.touch4j.client.core.Component;
import com.emitrom.touch4j.client.core.Ext;
import com.emitrom.touch4j.client.core.Icons;
import com.emitrom.touch4j.client.core.JsoHelper;
import com.emitrom.touch4j.client.core.config.Attribute;
import com.emitrom.touch4j.client.layout.AbstractLayout;
import com.emitrom.touch4j.client.layout.FitLayout;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

/**
 * A basic implemetation for a TabItem to be used with {@link TabPanel}
 */
public class TabItem extends Composite implements HasWidgets {

    private Widget widget;
    private final JavaScriptObject jsObj;
    private String id;
    private TabPanel parent;
    private int index;

    protected TabItem(JavaScriptObject jso) {
        jsObj = jso;
    }

    public JavaScriptObject getJsObj() {
        return jsObj;
    }

    public TabItem() {
        jsObj = JavaScriptObject.createObject();
        id = Ext.generateId("ext-container-");
        JsoHelper.setAttribute(jsObj, Attribute.ID.getValue(), id);
        initWidget(new Container());
        setLayout(new FitLayout());
    }

    public TabItem(String title) {
        this();
        setTitle(title);
    }

    public void setTitle(String title) {
        JsoHelper.setAttribute(jsObj, Attribute.TITLE.getValue(), title);
    }

    public void setIconCls(Icons iconCls) {
        JsoHelper.setAttribute(jsObj, Attribute.ICON_CLS.getValue(), iconCls.getValue());
    }

    public void setIconCls(String iconCls) {
        JsoHelper.setAttribute(jsObj, Attribute.ICON_CLS.getValue(), iconCls);
    }

    public void setHtml(String html) {
        JsoHelper.setAttribute(jsObj, Attribute.HTML.getValue(), html);
    }

    public void setCls(String cls) {
        JsoHelper.setAttribute(jsObj, Attribute.CLS.getValue(), cls);
    }

    public void setStyle(String cls) {
        JsoHelper.setAttribute(jsObj, Attribute.STYLE.getValue(), cls);
    }

    public String getTitle() {
        return JsoHelper.getAttribute(jsObj, Attribute.TITLE.getValue());
    }

    public String getIconCls() {
        return JsoHelper.getAttribute(jsObj, Attribute.ICON_CLS.getValue());
    }

    public String getHtml() {
        return JsoHelper.getAttribute(jsObj, Attribute.HTML.getValue());
    }

    public void setLayout(AbstractLayout layout) {
        JsoHelper.setAttribute(jsObj, Attribute.LAYOUT.getValue(), layout.getJSO());
    }

    public void setBadgeText(String badgeText) {
        if (this.parent == null) {
            JsoHelper.setAttribute(jsObj, Attribute.BADGE_TEXT.getValue(), badgeText);
        } else {
            this.parent.updateBadget(this.index, badgeText);
        }
    }

    public void add(Component component) {
        if (getWidget() != null) {
            throw new IllegalStateException("TabItem can only contain one child widget");
        }
        JavaScriptObject componentJS = component.isCreated() ? component.getOrCreateJsObj() : component.getConfig();
        _setItems(componentJS);
        widget = component;
    }

    /**
     * @return the widget
     */
    public Widget getWidget() {
        return widget;
    }

    /**
     * @param widget
     *            the widget to set
     */
    public void setWidget(Widget widget) {
        this.widget = widget;
    }

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id
     *            the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    private void _setItems(JavaScriptObject component) {
        JsoHelper.setAttribute(jsObj, Attribute.ITEMS.getValue(), component);
    }

    @Override
    public void add(Widget w) {
        if (!(w instanceof Component)) {
            throw new IllegalStateException(
                            "TabItem can only contain a child of typecom.emitrom.gwt4.touch.client.core.Component ");
        }
        add((Component) w);
    }

    @Override
    public void clear() {
    }

    @Override
    public Iterator<Widget> iterator() {
        return null;
    }

    @Override
    public boolean remove(Widget w) {
        return false;
    }

    public void setParent(TabPanel parent) {
        if (this.parent != null) {
            throw new IllegalStateException(
                            "TabItem can only be added to one parent. Have you already added this TabItem to a container ?");
        }
        this.parent = parent;
        this.index = parent.getNextChildIndex();
    }

    /**
     * Returns the position at which this TabItem was added to his parent
     *
     * @return
     */
    public int getIndex() {
        return this.index;
    }

}


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

import java.util.Random;

/**
 *
 * @author 2016 - Adrián
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Random rnd = new Random();
        double niveles;
        final int NIV_MIN = 0;
        final int NIV_MAX = 100;

        for (int i=1;i<5;i++){
            niveles = rnd.nextDouble()* (NIV_MAX - NIV_MIN) + NIV_MIN;
            System.out.printf("Estación %d ...: %.2f mcg NO2\n",i, niveles);
        }
    }

}


text:
from jsonschema import _utils
from jsonschema.exceptions import ValidationError

def ignore_ref_siblings(schema):
    """
    Ignore siblings of ``$ref`` if it is present.

    Otherwise, return all validators.

    Suitable for use with `create`'s ``applicable_validators`` argument.
    """
    ref = schema.get("$ref")
    if ref is not None:
        return [("$ref", ref)]
    else:
        return schema.items()

def dependencies_draft3(validator, dependencies, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for property, dependency in dependencies.items():
        if property not in instance:
            continue

        if validator.is_type(dependency, "object"):
            yield from validator.descend(
                instance, dependency, schema_path=property,
            )
        elif validator.is_type(dependency, "string"):
            if dependency not in instance:
                message = f"{dependency!r} is a dependency of {property!r}"
                yield ValidationError(message)
        else:
            for each in dependency:
                if each not in instance:
                    message = f"{each!r} is a dependency of {property!r}"
                    yield ValidationError(message)

def dependencies_draft4_draft6_draft7(
    validator,
    dependencies,
    instance,
    schema,
):
    """
    Support for the ``dependencies`` validator from pre-draft 2019-09.

    In later drafts, the validator was split into separate
    ``dependentRequired`` and ``dependentSchemas`` validators.
    """
    if not validator.is_type(instance, "object"):
        return

    for property, dependency in dependencies.items():
        if property not in instance:
            continue

        if validator.is_type(dependency, "array"):
            for each in dependency:
                if each not in instance:
                    message = f"{each!r} is a dependency of {property!r}"
                    yield ValidationError(message)
        else:
            yield from validator.descend(
                instance, dependency, schema_path=property,
            )

def disallow_draft3(validator, disallow, instance, schema):
    for disallowed in _utils.ensure_list(disallow):
        if validator.evolve(schema={"type": [disallowed]}).is_valid(instance):
            message = f"{disallowed!r} is disallowed for {instance!r}"
            yield ValidationError(message)

def extends_draft3(validator, extends, instance, schema):
    if validator.is_type(extends, "object"):
        yield from validator.descend(instance, extends)
        return
    for index, subschema in enumerate(extends):
        yield from validator.descend(instance, subschema, schema_path=index)

def items_draft3_draft4(validator, items, instance, schema):
    if not validator.is_type(instance, "array"):
        return

    if validator.is_type(items, "object"):
        for index, item in enumerate(instance):
            yield from validator.descend(item, items, path=index)
    else:
        for (index, item), subschema in zip(enumerate(instance), items):
            yield from validator.descend(
                item, subschema, path=index, schema_path=index,
            )

def items_draft6_draft7_draft201909(validator, items, instance, schema):
    if not validator.is_type(instance, "array"):
        return

    if validator.is_type(items, "array"):
        for (index, item), subschema in zip(enumerate(instance), items):
            yield from validator.descend(
                item, subschema, path=index, schema_path=index,
            )
    else:
        for index, item in enumerate(instance):
            yield from validator.descend(item, items, path=index)

def minimum_draft3_draft4(validator, minimum, instance, schema):
    if not validator.is_type(instance, "number"):
        return

    if schema.get("exclusiveMinimum", False):
        failed = instance <= minimum
        cmp = "less than or equal to"
    else:
        failed = instance < minimum
        cmp = "less than"

    if failed:
        message = f"{instance!r} is {cmp} the minimum of {minimum!r}"
        yield ValidationError(message)

def maximum_draft3_draft4(validator, maximum, instance, schema):
    if not validator.is_type(instance, "number"):
        return

    if schema.get("exclusiveMaximum", False):
        failed = instance >= maximum
        cmp = "greater than or equal to"
    else:
        failed = instance > maximum
        cmp = "greater than"

    if failed:
        message = f"{instance!r} is {cmp} the maximum of {maximum!r}"
        yield ValidationError(message)

def properties_draft3(validator, properties, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for property, subschema in properties.items():
        if property in instance:
            yield from validator.descend(
                instance[property],
                subschema,
                path=property,
                schema_path=property,
            )
        elif subschema.get("required", False):
            error = ValidationError(f"{property!r} is a required property")
            error._set(
                validator="required",
                validator_value=subschema["required"],
                instance=instance,
                schema=schema,
            )
            error.path.appendleft(property)
            error.schema_path.extend([property, "required"])
            yield error

def type_draft3(validator, types, instance, schema):
    types = _utils.ensure_list(types)

    all_errors = []
    for index, type in enumerate(types):
        if validator.is_type(type, "object"):
            errors = list(validator.descend(instance, type, schema_path=index))
            if not errors:
                return
            all_errors.extend(errors)
        else:
            if validator.is_type(instance, type):
                return
    else:
        reprs = []
        for type in types:
            try:
                reprs.append(repr(type["name"]))
            except Exception:
                reprs.append(repr(type))
        yield ValidationError(
            f"{instance!r} is not of type {', '.join(reprs)}",
            context=all_errors,
        )

def contains_draft6_draft7(validator, contains, instance, schema):
    if not validator.is_type(instance, "array"):
        return

    if not any(
        validator.evolve(schema=contains).is_valid(element)
        for element in instance
    ):
        yield ValidationError(
            f"None of {instance!r} are valid under the given schema",
        )

def recursiveRef(validator, recursiveRef, instance, schema):
    lookup_url, target = validator.resolver.resolution_scope, validator.schema

    for each in reversed(validator.resolver._scopes_stack[1:]):
        lookup_url, next_target = validator.resolver.resolve(each)
        if next_target.get("$recursiveAnchor"):
            target = next_target
        else:
            break

    fragment = recursiveRef.lstrip("#")
    subschema = validator.resolver.resolve_fragment(target, fragment)
    yield from validator.descend(instance, subschema)


text:
define([
  './table'
],
function (TableView) {

  var TableViewFallback = TableView.extend({

     initialize: function (options) {

      this.options = options || {};
      var existingCollection = this.options.collection || this.collection;

      this.collection = new existingCollection.constructor(existingCollection.toJSON(), existingCollection.options);

      this.valueAttr = this.options.valueAttr;
      this.period = this.collection.getPeriod();

      if (this.collection.models.length > 0) {
        this.collection.models = this.collection.last(6);
        this.collection.length = this.collection.models.length;
        this.listenTo(this.collection, 'reset add remove', this.render);
        this.initSort();
      }
    }

  });

   _.extend(TableViewFallback.prototype);

  return TableViewFallback;

});


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Work</title>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta property="og:image" content="assets/images/ahs.png">

    <link rel="author" type="text/plain" href="/humans.txt">

    <link rel="dns-prefetch" href="//cdnjs.cloudflare.com">
    <link rel="dns-prefetch" href="//code.jquery.com">
    <link rel="dns-prefetch" href="//maxcdn.bootstrapcdn.com">

    <link rel="stylesheet" media="all" href="vendor/normalize/normalize.css">

    <link rel="stylesheet" media="all" href="css/fonts.css">
    <link rel="stylesheet" media="all" href="css/main.css">
    <link rel="stylesheet" media="all" href="css/grid.css">
    <link rel="stylesheet" media="all" href="css/work.css">

                        com'bo

WHAT WE DO

WHO WE ARE

PORTFOLIO

JOBS

CONTACT

 PORTFOLIO

 Onze realisaties

Project 10

Ontwerpen poster elektroshop

com'bo © 2017 door Vanherck Bo


text:
#ifndef CONF_SLEEPMGR_H
#define CONF_SLEEPMGR_H

#ifdef __cplusplus
extern "C" {
#endif

#define CONFIG_SLEEPMGR_ENABLE ///< Sleep manager options

#ifdef __cplusplus
}
#endif

#endif /* CONF_SLEEPMGR_H */


text:
package org.qsardb.cargo.map;

import org.qsardb.model.*;

public class ValuesCargo extends MapCargo<Parameter> {

	protected ValuesCargo(Descriptor descriptor){
		super(ValuesCargo.ID, descriptor);
	}

	protected ValuesCargo(Prediction prediction){
		super(ValuesCargo.ID, prediction);
	}

	protected ValuesCargo(Property property){
		super(ValuesCargo.ID, property);
	}

	@Override
	protected String keyName(){
		return "Compound Id";
	}

	@Override
	protected String valueName(){
		return getContainer().getName();
	}

	public static final String ID = "values";
}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: java.net.NetPermission
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_NET_NETPERMISSION_HPP_DECL
#define J2CPP_JAVA_NET_NETPERMISSION_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace security { class BasicPermission; } } }

#include <java/lang/String.hpp>
#include <java/security/BasicPermission.hpp>

namespace j2cpp {

namespace java { namespace net {

	class NetPermission;
	class NetPermission
		: public object<NetPermission>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)

		explicit NetPermission(jobject jobj)
		: object<NetPermission>(jobj)
		{
		}

		operator local_ref<java::security::BasicPermission>() const;

		NetPermission(local_ref< java::lang::String > const&);
		NetPermission(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);
	}; //class NetPermission

} //namespace net
} //namespace java

} //namespace j2cpp

#endif //J2CPP_JAVA_NET_NETPERMISSION_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_NET_NETPERMISSION_HPP_IMPL
#define J2CPP_JAVA_NET_NETPERMISSION_HPP_IMPL

namespace j2cpp {

java::net::NetPermission::operator local_ref<java::security::BasicPermission>() const
{
	return local_ref<java::security::BasicPermission>(get_jobject());
}

java::net::NetPermission::NetPermission(local_ref< java::lang::String > const &a0)
: object<java::net::NetPermission>(
	call_new_object<
		java::net::NetPermission::J2CPP_CLASS_NAME,
		java::net::NetPermission::J2CPP_METHOD_NAME(0),
		java::net::NetPermission::J2CPP_METHOD_SIGNATURE(0)
	>(a0)
)
{
}

java::net::NetPermission::NetPermission(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1)
: object<java::net::NetPermission>(
	call_new_object<
		java::net::NetPermission::J2CPP_CLASS_NAME,
		java::net::NetPermission::J2CPP_METHOD_NAME(1),
		java::net::NetPermission::J2CPP_METHOD_SIGNATURE(1)
	>(a0, a1)
)
{
}

J2CPP_DEFINE_CLASS(java::net::NetPermission,"java/net/NetPermission")
J2CPP_DEFINE_METHOD(java::net::NetPermission,0,"<init>","(Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(java::net::NetPermission,1,"<init>","(Ljava/lang/String;Ljava/lang/String;)V")

} //namespace j2cpp

#endif //J2CPP_JAVA_NET_NETPERMISSION_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
@interface ZHSeaResultController : UITableViewController

@end


text:
namespace SharpNeat.Genomes.Neat
{
    /// <summary>
    /// Defines types of weight perturbation.
    /// </summary>
    public enum ConnectionPerturbanceType
    {
        /// <summary>
        /// Reset weight.
        /// </summary>
        Reset,
        /// <summary>
        /// Jiggle weight using deltas from a uniform distribution.
        /// </summary>
        JiggleUniform,
        /// <summary>
        /// Jiggle weight using deltas from a Gaussian distribution.
        /// </summary>
        JiggleGaussian

        // TODO: Replace Gaussian with a fatter tailed distribution.
    }
}


text:
"""This module is intended to contain methods specific
to Networking v2 API and its extensions.
"""

from cliff import columns as cliff_columns

class AdminStateColumn(cliff_columns.FormattableColumn):
    def human_readable(self):
        return 'UP' if self._value else 'DOWN'


text:
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;

namespace Nez.Farseer
{
	internal class FSBodyDef
	{
		public BodyType BodyType = BodyType.Static;
		public Vector2 LinearVelocity;
		public float AngularVelocity;
		public float LinearDamping;
		public float AngularDamping;

		public bool IsBullet;
		public bool IsSleepingAllowed = true;
		public bool IsAwake = true;
		public bool FixedRotation;
		public bool IgnoreGravity;
		public float GravityScale = 1;
		public float Mass;
		public float Inertia;
	}
}


text:
class Node

	attr_accessor :name, :runs, :children, :data, :options

	def initialize(name, runs = 1, children = [], options = {})
		@name = name
		@runs = Integer(runs)
		@children = children
		@options = options
		@data = {}
	end

	def is_buildable?
		false
	end

	def accept(visitor)
		clone.tap do |copy|
			copy.data = @data.clone
			copy.children = @children.map { |c| c.accept(visitor) }
			visitor.visit(copy)
		end
	end

	def each(direction = :top_down, &block)
		yield self if direction == :top_down
		@children.each { |c| c.each(&block) }
		yield self if direction == :bottom_up
	end

	def each_with_depth(depth = 0, direction = :top_down, &block)
		yield(self, depth) if direction == :top_down
		@children.each { |c| c.each_with_depth(depth + 1, direction, &block) } if @children
		yield(self, depth) if direction == :bottom_up
	end

	def sort_by(&block)
		clone.tap do |copy|
			copy.data = @data.clone
			copy.children = @children.sort_by(&block)
		end
	end

	def select(&block)
		clone.tap do |copy|
			copy.data = @data.clone
			copy.children = @children.select(&block)
		end
	end
end


text:
package org.apache.hadoop.ozone.web.ozShell.bucket;

import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.hadoop.ozone.client.OzoneBucket;
import org.apache.hadoop.ozone.client.OzoneClientException;
import org.apache.hadoop.ozone.client.OzoneClientUtils;
import org.apache.hadoop.ozone.client.OzoneVolume;
import org.apache.hadoop.ozone.client.rest.response.BucketInfo;
import org.apache.hadoop.ozone.web.ozShell.Handler;
import org.apache.hadoop.ozone.web.ozShell.Shell;
import org.apache.hadoop.ozone.web.utils.JsonUtils;

import picocli.CommandLine.Command;
import picocli.CommandLine.Help.Visibility;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;

/**
 * Executes List Bucket.
 */
@Command(name = "list",
    aliases = "ls",
    description = "lists the buckets in a volume.")
public class ListBucketHandler extends Handler {

  @Parameters(arity = "1..1", description = Shell.OZONE_VOLUME_URI_DESCRIPTION)
  private String uri;

  @Option(names = {"--length", "-l"},
      description = "Limit of the max results",
      defaultValue = "100",
      showDefaultValue = Visibility.ALWAYS)
  private int maxBuckets;

  @Option(names = {"--start", "-s"},
      description = "The first bucket to start the listing")
  private String startBucket;

  @Option(names = {"--prefix", "-p"},
      description = "Prefix to filter the buckets")
  private String prefix;
  /**
   * Executes the Client Calls.
   */
  @Override
  public Void call() throws Exception {

    URI ozoneURI = verifyURI(uri);
    Path path = Paths.get(ozoneURI.getPath());
    int pathNameCount = path.getNameCount();
    if (pathNameCount != 1) {
      String errorMessage;
      if (pathNameCount < 1) {
        errorMessage = "volume is required in listBucket";
      } else {
        errorMessage = "Invalid volume name. Delimiters (/) not allowed in " +
            "volume name";
      }
      throw new OzoneClientException(errorMessage);
    }

    if (maxBuckets < 1) {
      throw new IllegalArgumentException(
          "the length should be a positive number");
    }

    String volumeName = path.getName(0).toString();

    if (isVerbose()) {
      System.out.printf("Volume Name : %s%n", volumeName);
    }

    OzoneVolume vol = client.getObjectStore().getVolume(volumeName);
    Iterator<? extends OzoneBucket> bucketIterator =
        vol.listBuckets(prefix, startBucket);
    List<BucketInfo> bucketList = new ArrayList<>();
    while (maxBuckets > 0 && bucketIterator.hasNext()) {
      BucketInfo bucketInfo =
          OzoneClientUtils.asBucketInfo(bucketIterator.next());
      bucketList.add(bucketInfo);
      maxBuckets -= 1;
    }

    if (isVerbose()) {
      System.out.printf("Found : %d buckets for volume : %s ",
          bucketList.size(), volumeName);
    }
    System.out.println(JsonUtils.toJsonStringWithDefaultPrettyPrinter(
        JsonUtils.toJsonString(bucketList)));
    return null;
  }
}


text:
title: "Recursion"
date: 2018-11-13T11:57:00-06:00
tags: ["functional programming","Javascript","Scala"]
draft: false
---
A recursive process is one that refers to itself in its own definition{{< footref 1 "" >}}. If you're looking for some intuition, [search for recursion on Google](https://www.google.com/search?q=recursion) and try the _Did you mean [recursion](https://www.google.com/search?q=recursion)_ link. Clearer yet, consider this function:

```scala
def endless: Nothing = endless
```

You don't need to understand lambda calculus{{< footref 2 "" >}} or evaluation-by-substitution to understand that a call to `endless` will never terminate. The first call makes a second call, which makes a third call, ad infinitum. But of course all other recursive functions are more complex than this one, so we must ask the question:  how _does_ a recursive function evaluate?

### Substitution

Without discussing details like compiler optimizations, we can think of code evaluation in a functional paradigm as the substitution of a statement with its definition. Substitution only works for so-called "purely functional" code, where any two identical expressions always evaluate to the same result. Many examples of non-functional code would fail such an equivalence test. For example, consider constructions involving the current date time, or _any_ two invocations of the same constructor, which look identical but create distinct, distinguishable instances of the same class.

As an example to demonstrate substitution-based evaluation, we will consider two canonical algorithms: factorial and greatest common divisor. Here are naïve definitions:

```scala
// factorial computes n! = n * (n-1) * (n-2) * ... * 1
def factorial(n: Int): Long =
  if (n == 1) 1
  else n * factorial(n - 1)
```

```scala
// gcd computes the greatest integer that divides both a and b, using the
// Euclidean Algorithm, which works on the basis that:
// a == c (mod b) => gcd(a, b) == gcd(b, c)
def gcd(a: Int, b: Int): Int =
  if (b == 0) a
  else gcd(b, a % b)
```

These definitions are considered to be functional, in that they do not involve state mutations (i.e. no variables, no constructors for complex objects that track state). As such, we can apply a substitution model of expression evaluation, replacing each function call to `factorial` or `gcd` with the given definitions.

The idea seems obvious, but it is powerful because it complies with mathematical intuition. After all, there is no "external" or "mutable" state lurking in a mathematical proof, capable of derailing the process; there is only a sequence of claims, one following the next by virtue of a legal substitution. In the context of functional programming, a legal substitution will generally mean substituting a function call with its definition, replacing parameter names with the corresponding values provided in the call.

As an example, let's first use substitution to evaluate a simple instance of `factorial`:

```scala
factorial(3)
```
```scala
if (3 == 1) 1 else 3 * factorial(3 - 1)
```
```scala
3 * factorial(3 - 1)
```
```scala
3 * factorial(2)
```
```scala
3 * (if (2 == 1) 1 else 2 * factorial(2 - 1))
```
```scala
3 * (2 * factorial(2 - 1))
```
```scala
3 * (2 * factorial(1))
```
```scala
3 * (2 * (if (1 == 1) 1 else 1 * factorial(1 - 1)))
```
```scala
3 * (2 * (1))
```
```scala
3 * (2)
```
```scala
6
```

Take note of the shape of this substitutive process, how the expression grows and shrinks with respect to the parameter, `n`. Contrast it with the example of a simple `gcd` call:

```scala
gcd(9, 6)
```
```scala
if (6 == 0) 9 else gcd(6, 9 % 6)
```
```scala
gcd(6, 9 % 6)
```
```scala
gcd(6, 3)
```
```scala
if (3 == 0) 6 else gcd(3, 6 % 3)
```
```scala
gcd(3, 6 % 3)
```
```scala
gcd(3, 0)
```
```scala
if (0 == 0) 3 else gcd(0, 3 % 0)
```
```scala
3
```

You will notice that the `factorial` expressions grows with `n`; that is, a new operation is appended with each recursive call, which does not collapse until the recursion completes and the multiplicative chain is rolled up, whereas the `gcd` expressions do not grow with respect to `a` and `b` because each recursive call simply replaces the previous call with different values. Thus, we can call `gcd` **tail-recursive**. And the fact that `factorial` is not tail recursive will quickly become a serious problem.

### Stack overflow

If you search for "tail recursion" on Google, you will likely see a post entitled _[algorithm - What is tail recursion?](https://stackoverflow.com/questions/33923/what-is-tail-recursion)_ on [StackOverflow](https://stackoverflow.com/). Fittingly, if you do not understand tail recursion, you are likely to cause an error called **stack overflow**.

First, we must first understand the basic idea of the call stack, which is the mechanism a process uses to manage constituent sub-processes. Think of the process as your program and each function call as a sub-process, no matter how shallowly- or deeply-nested. Consider this example:

```scala
def process = {
  println("process starts")
  sub1
  println("process ends")
}

def sub1 = {
  println("sub1 starts")
  sub2
  println("sub1 ends")
}

def sub2 = {
  println("sub2 starts")
  println("sub2 ends")
}
```
```scala
> process starts
> sub1 starts
> sub2 starts
> sub2 ends
> sub1 ends
> process ends
```

Think of the call stack as, literally, a stack, which is last-in-first-out (LIFO) data structure. As each process is pushed onto the stack, the stack grows. Only when a process returns a value does it get popped off the stack. The call stack has a static allocation of memory, so when it runs out the program will report a stack overflow error and crash.

Now, recall the evaluation of factorial. How many calls can get pushed onto the stack before it runs out of memory? That depends on the environment in which the code is running, but in general, the stack will overflow relatively quickly. Factorial is not a good example because its value grows with `n` at such a pace the stack _might_ survive long enough to first exhaust the maximum `Int` or `Long` value, but we can consider an example demonstrating how pernicious stack overflows can be.

```scala
// altSum computes the sum of -1 + 2 - 3 + 4 ... for n steps, starting at step 1
// e.g. altSum(4) = -1 + 2 - 3 + 4 = 2
def altSum(n: Long): Long = {
  if (n == 0) 0
  else {
    val sign = (if (n % 2 == 0) 1 else -1).toLong
    (n * sign) + altSum(n - 1)
  }
}
```

_Thanks to [Brilliant.org](https://brilliant.org/) for the {{< footref 4 "inspiration" >}} for this example!_

Of course, there are proofs that can describe the behavior of this function as `n` goes to infinity, but what if we want to poke around computationally, possibly taking some action at each iterative step? Let's give it a shot:

```scala
altSum(10)
> 5

altSum(11)
> -6

altSum(100)
> 50

altSum(101)
> -51

altSum(1000)
> 500

altSum(1001)
> -501

altSum(10000)
> java.lang.StackOverflowError
    at recursion.A$A11$A$A11.f1(sum.sc:54)
    at recursion.A$A11$A$A11.f1(sum.sc:54)
    at recursion.A$A11$A$A11.f1(sum.sc:54)
    at recursion.A$A11$A$A11.f1(sum.sc:54)
    ...
```

Pretty quickly, at that last example, we get a `java.lang.StackOverflowError` error, even though we suspect that the answer is `5000`, which doesn't even come close to the maximum `Int` value of `2147483647`, not to mention the maximum `Long` value of `9223372036854775807`.

Can we fix `altSum` to avoid stack overflows, pushing the results closer to the boundaries of these maximum values?

### Tail recursion

If the problem is a growing call stack, how can we restructure our code to exist in a bounded stack space? Ideally, the return value of the function should be a single recursive function call; in other words, the function needs to encapsulate and evaluate the dangling operations that would otherwise accrue. As we've already mentioned, this pattern is called **tail recursion**.

```scala
def altSum(n: Long): Long = {
  def asAcc(n: Long, acc: Long): Long = {
    if (n == 0) acc
    else {
      val sign = (if (n % 2 == 0) 1 else -1).toLong
      asAcc(n - 1, acc + (n * sign))
    }
  }
  asAcc(n, 0)
}
```

```scala
altSum(10000)
> 5000

altSum(10001)
> -5001

altSum(10000000)
> 5000000

altSum(10000001)
> -5000001

altSum(1000000000)
> 500000000

altSum(1000000001)
> -500000001
```

That's better! To see this in action, and to make _extremely_ clear why it works, let's step through a smaller call, as we did for `factorial` and `gcd`:

```scala
altSum(3)
```
```scala
asAcc(3, 0)
```
```scala
if (3 == 0) 0
else {
  val sign = (if (3 % 2 == 0) 1 else -1).toLong
  asAcc(3 - 1, 0 + (3 * sign))
}
```
```scala
val sign = (if (3 % 2 == 0) 1 else -1).toLong
asAcc(3 - 1, 0 + (3 * sign))
```
```scala
val sign = -1
asAcc(3 - 1, 0 + (3 * sign))
```
```scala
asAcc(3 - 1, 0 + (3 * -1))
```
```scala
asAcc(2, -3)
```

At this point, we've only made it through one complete cycle, but that's all we need to see that **the compounding operation must be evaluated for it to be passed as a parameter, known as the accumulator, into the recursive call**. That way, the stack flushes after a relatively small number of operations. It's subtle, but we can be convinced that this new version of the function will operate in bounded stack space.

#### Access to acc

Notice that there's a side-effect, which is really the primary effect:  **we have access to the accumulator** within the function. What else can we do with it? In this case, we can see that the function oscillates and diverges, but we can also [show via algebraic manipulation](#alternating-sum) that the infinite sum evaluates to -1/4. Does having access to `acc` give us the ability to glean any insights about how the -1/4 could make intuitive sense?

For instance, we can compute a running average of the accumulating `sum` by turning `acc` into a tuple that records both at each iteration.

```scala
def altSum(n: Long): (Long, Double) = {
  def asAcc(i: Long, n: Long, acc: (Long, Double)): (Long, Double) = {
    if (i > n) acc
    else {
      val sign = (if (i % 2 == 0) 1 else -1).toLong
      val sum = acc._1 + (i * sign)
      val avg = ((acc._2 * (i-1)) + sum) / i
      asAcc(i + 1, n, (sum, avg))
    }
  }
  asAcc(1, n, (0, 0))
}
```

```scala
altSum(1)
> (-1,-1.0)

altSum(2)
> (1,0.0)

altSum(3)
> (-2,-0.6666666666666666)

altSum(4)
> (2,0.0)

altSum(100)
> (50,-2.842170943040401E-16)

altSum(101)
> (-51,-0.5049504950495052)

altSum(1000)
> (500,5.684341886080802E-17)

altSum(1001)
> (-501,-0.5004995004995004)

altSum(1000000)
> (500000,-1.0419171303510665E-14)

altSum(1000001)
> (-500001,-0.5000004999995105)
```

Thanks to our accumulator's running average, we are able to gain an important insight. The running average oscillates between 0 and -1/2, lending some supporting intuition to the algebraic outcome of -1/4.

### To forget loops...

We've now seen a few recursive examples that could have been represented with loops. Can we convert _any_ loop into a recursive call? There are certainly academic arguments, like the {{< footref 6 "Church-Turing thesis" >}}, but let's instead attempt to build a simple implementation. For instance, what is a functional way of looking at a simple `for` loop in Javascript that increments and logs a counter?

```js
for (x = 1; x <= 3; x++) {
  console.log(x)
  console.log("hello")
  console.log('hello')
}
```
```js
> 1
> 2
> 3
```

Functional design preaches to **parameterize everything**---after all, if we can't mutate state, then the only way to generate new values is to feed what we have into a function as parameters, then return the new value(s). Here, the parameter `x` is obvious. But what else can we pull out? How about `console.log(x)`? Most functional languages will support functions as first-class citizens, meaning a function is a value that can be passed along, so we can abstract everything that happens in the for loop closure as a parameter called `action`.

If we're going to parameterize functions, we must also capture the for loop's condition and final expression. Otherwise, without a breaking condition and a way to get there, our recursive function will run forever. We can call those `condition` and `next`, respectively.

Putting the parts together, we can mimic {{< footref 7 "Javascript, in which a for loop" >}} is evaulated thusly:

1. initialization (`params`)
2. condition (`condition`)
3. statement (`action`)
4. final expression (`next`)

```js
const loop = (params, condition, action, next) => {
  if (condition(params)) {
    action(params);
    return loop(next(params), condition, action, next);
  }
};

const params = { x: 1 };
const condition = (params) => params.x <= 3;
const action = (params) => console.log(params.x);
const next = (params) => ({ x: params.x + 1 });

loop(params, condition, action, next);
```
```js
> 1
> 2
> 3
```

### ...or not to forget loops

Just because we _can_ replace loops with recursion whenever we like, doesn't mean we should. In fact, there's a sense in which all of our anti-loop efforts are just a delusion, given that as our code gets compiled and run it may be rewritten into equivalent but non-recursive forms. For an example of when loops may be more beneficial to use, consider Scala's own implementation of [`foldLeft`](https://github.com/scala/scala/blob/d96b8eb48e83d400c03663a05b66ec218ead9c14/src/library/scala/collection/LinearSeqOptimized.scala#L118) and [`foldRight`](https://github.com/scala/scala/blob/d96b8eb48e83d400c03663a05b66ec218ead9c14/src/library/scala/collection/LinearSeqOptimized.scala#L129).

_This example was brought to my attention by Matt Malone on his blog,_ {{< footref 8 "Old Fashioned Software" >}}_._

```Scala
def foldLeft[B](z: B)(@deprecatedName('f) op: (B, A) => B): B = {
  var acc = z
  var these = this
  while (!these.isEmpty) {
    acc = op(acc, these.head)
    these = these.tail
  }
  acc
}
```

```Scala
def foldRight[B](z: B)(@deprecatedName('f) op: (A, B) => B): B =
  if (this.isEmpty) z
  else op(head, tail.foldRight(z)(op))
```

At first glance, the functional programmer gasps! (Oh, the horror of `var`.) But the pragmatic programmer thinks, tests, and determines (like Matt Malone) that for very long lists, `foldLeft` is likely to succeed while `foldRight` is likely to cause a stack overflow. In fact, the best way to `foldRight` safely is to `reverse.foldLeft`!

The bottom line is that as often as recursion compact, elegant, and exciting, it is difficult, inefficient, and impractical. Knowing why (or, better, knowing how and when to use it) is an essential tool for any functional programmer.

### Proofs

#### Euclid's algorithm for greatest common divisor

See [WolframMathWorld: Euclidean Algorithm](http://mathworld.wolfram.com/EuclideanAlgorithm.html) for more{{< footref 9 "" >}}.

```
a == c (mod b)
(a - c) == 0 (mod b)
b | (a - c)
exists y : by == a - c
c == a - by
if d|c, then d|a and d|b
d == gcd(a, b) == gcd(b, c)
```
```
gcd(10, 4)
10 = 2 (mod 4)
(10 - 2) = 0 (mod 4)
4y = (10 - 2)
2 = (10 - 4y)
=> gcd(10, 4) = gcd(4, 2)
```
```
gcd(4, 10 % 4 = 2)
gcd(2, 4 % 2 = 0)
> 2
```

#### Alternating sum

See the [original Brilliant.org problem](https://brilliant.org/practice/sequences-and-series-level-1-challenges/?problem=one-for-you-two-for-me-three-for-you) for several explanations{{< footref 4 "" >}}.

```
S = - 1 + 2 - 3 + 4 ...

define T as:
T = + 1 - 1 + 1 - 1 ...

T - 1     = - 1 + 1 - 1 + 1 ...

T + T - 1 = + 1 - 1 + 1 - 1 ...
            - 1 + 1 - 1 + 1 ...
          = 0

T + T - 1 = 0
2T        = 1
T         = 1/2

S + T = - 1 + 2 - 3 + 4 ...
        + 1 - 1 + 1 - 1 ...
      =   0 + 1 - 2 + 3 ...
      = - S

2S    = -T
      = -1/2

S = -1/4
```

### Credit, Reference, and Related Reading

1. {{< footnote 1 "Recursion (computer science) - Wikipedia" "https://en.wikipedia.org/wiki/Recursion_(computer_science)" >}}

1. {{< footnote 2 "Lambda calculus - Wikipedia" "https://en.wikipedia.org/wiki/Lambda_calculus" >}}

1. {{< footnote 3 "Arithmetic Series -- from Wolfram MathWorld" "http://mathworld.wolfram.com/ArithmeticSeries.html" >}}

1. {{< footnote 4 "Sequences and Series: Level 1 Challenges | Brilliant" "https://brilliant.org/practice/sequences-and-series-level-1-challenges/?problem=one-for-you-two-for-me-three-for-you" >}}

1. {{< footnote 5 "Can every recursion be turned into iteration - Stack Overflow" "https://stackoverflow.com/questions/931762/can-every-recursion-be-converted-into-iteration/933979#933979" >}}

1. {{< footnote 6 "Church-Turing thesis - Wikipedia" "https://en.wikipedia.org/wiki/Church%E2%80%93Turing_thesis" >}}

1. {{< footnote 7 "for - Javascript | MDN" "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for#Syntax" >}}

1. {{< footnote 8 "Scala Code Review: foldLeft and foldRight « Matt Malone's Old-Fashioned Software Development Blog" "https://oldfashionedsoftware.com/2009/07/10/scala-code-review-foldleft-and-foldright/" >}}

1. {{< footnote 9 "Euclidean Algorithm --- from WolframMathWorld" "http://mathworld.wolfram.com/EuclideanAlgorithm.html" >}}


text:
package org.springframework.cloud.stream.app.task.launcher.local.sink.configuration;

import org.springframework.cloud.deployer.spi.core.AppDeploymentRequest;
import org.springframework.cloud.deployer.spi.task.LaunchState;
import org.springframework.cloud.deployer.spi.task.TaskLauncher;
import org.springframework.cloud.deployer.spi.task.TaskStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Glenn Renfro
 */
@Configuration
public class TaskSinkConfiguration {

	@Bean
	public TaskLauncher taskLauncher() {
		return new TestTaskLauncher();
	}

	public class TestTaskLauncher implements TaskLauncher {

		public static final String LAUNCH_ID = "TEST_LAUNCH_ID";

		private LaunchState state = LaunchState.unknown;

		@Override
		public String launch(AppDeploymentRequest request) {
			state = LaunchState.complete;
			return null;
		}

		@Override
		public void cancel(String id) {

		}

		@Override
		public TaskStatus status(String id) {
			String taskLaunchId = LAUNCH_ID;
			TaskStatus taskStatus = new TaskStatus(taskLaunchId, state, null);
			return taskStatus;
		}
	}

}


text:
package com.haulmont.cuba.web.app.ui.jmxcontrol.inspect.operation;

import com.haulmont.cuba.core.global.TimeSource;
import com.haulmont.cuba.gui.UiComponents;
import com.haulmont.cuba.gui.WindowParam;
import com.haulmont.cuba.gui.components.AbstractWindow;
import com.haulmont.cuba.gui.components.Label;
import com.haulmont.cuba.gui.components.ScrollBoxLayout;
import com.haulmont.cuba.gui.export.ByteArrayDataProvider;
import com.haulmont.cuba.gui.export.ExportDisplay;
import com.haulmont.cuba.web.jmx.JmxControlException;
import com.haulmont.cuba.web.jmx.entity.AttributeHelper;
import com.vaadin.shared.ui.ContentMode;
import org.apache.commons.lang3.exception.ExceptionUtils;

import javax.inject.Inject;
import javax.management.MBeanException;
import java.lang.reflect.UndeclaredThrowableException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Map;

public class OperationResultWindow extends AbstractWindow {
    @Inject
    protected Label<String> resultLabel;

    @Inject
    protected ScrollBoxLayout resultContainer;

    @Inject
    protected ExportDisplay exportDisplay;

    @Inject
    protected TimeSource timeSource;

    @WindowParam
    protected Object result;

    @WindowParam
    protected Throwable exception;

    @WindowParam
    protected String methodName;

    @WindowParam
    protected String beanName;

    @Inject
    protected UiComponents uiComponents;

    @Override
    public void init(Map<String, Object> params) {
        super.init(params);

        if (exception != null) {
            Label<String> traceLabel = uiComponents.create(Label.NAME);
            traceLabel.setValue(getExceptionMessage(exception));

            com.vaadin.ui.Label vaadinLbl = traceLabel.unwrap(com.vaadin.ui.Label.class);
            vaadinLbl.setContentMode(ContentMode.PREFORMATTED);

            resultLabel.setValue(getMessage("operationResult.exception"));
            resultContainer.add(traceLabel);
        } else if (result != null) {
            Label<String> valueHolder = uiComponents.create(Label.NAME);
            valueHolder.setValue(AttributeHelper.convertToString(result));

            com.vaadin.ui.Label vaadinLbl = valueHolder.unwrap(com.vaadin.ui.Label.class);
            vaadinLbl.setContentMode(ContentMode.PREFORMATTED);

            resultLabel.setValue(getMessage("operationResult.result"));
            resultContainer.add(valueHolder);
        } else {
            resultLabel.setValue(getMessage("operationResult.void"));
        }
    }

    protected String getExceptionMessage(Throwable exception) {
        if (exception instanceof UndeclaredThrowableException)
            exception = exception.getCause();

        if (exception instanceof JmxControlException) {
            exception = exception.getCause();

            if (exception instanceof MBeanException) {
                exception = exception.getCause();
            }
        }

        String msg;
        if (exception != null) {
            msg = String.format("%s: \n%s\n%s",
                    exception.getClass().getName(),
                    exception.getMessage(),
                    ExceptionUtils.getStackTrace(exception));
        } else {
            msg = "";
        }
        return msg;
    }

    public void close() {
        close(CLOSE_ACTION_ID);
    }

    public void exportToFile() {
        if (result != null || exception != null) {
            String exportResult = String.format("JMX Method %s : %s result\n", beanName, methodName);

            if (result != null) {
                exportResult += AttributeHelper.convertToString(result);
            }
            if (exception != null) {
                exportResult += getExceptionMessage(exception);
            }

            byte[] bytes = exportResult.getBytes(StandardCharsets.UTF_8);
            exportDisplay.show(new ByteArrayDataProvider(bytes),
                    String.format("jmx.%s-%s-%s.log",
                            beanName,
                            methodName,
                            new SimpleDateFormat("HH:mm:ss").format(
                                    timeSource.currentTimestamp())));
        } else {
            showNotification(getMessage("operationResult.resultIsEmpty"), NotificationType.HUMANIZED);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
    <settings pass="generalize">
        <component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <SkipRearm>0</SkipRearm>
        </component>
        <!--
        <component name="Microsoft-Windows-PnpSysprep" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <PersistAllDeviceInstalls>false</PersistAllDeviceInstalls>
            <DoNotCleanUpNonPresentDevices>false</DoNotCleanUpNonPresentDevices>
        </component>
        -->
    </settings>
    <settings pass="oobeSystem">
        <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <OOBE>
                <HideEULAPage>true</HideEULAPage>
                <ProtectYourPC>3</ProtectYourPC>
                <NetworkLocation>Work</NetworkLocation>
                <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
                <SkipUserOOBE>true</SkipUserOOBE>
                <SkipMachineOOBE>true</SkipMachineOOBE>
            </OOBE>
            <AutoLogon>
                <Password>
                    <Value>vagrant</Value>
                    <PlainText>true</PlainText>
                </Password>
                <Enabled>true</Enabled>
                <LogonCount>1</LogonCount>
                <Username>vagrant</Username>
            </AutoLogon>
        </component>
    </settings>
    <settings pass="specialize">
        <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <ComputerName>vagrant</ComputerName>
            <CopyProfile>false</CopyProfile>
        </component>
    </settings>
</unattend>