text:
[Live PubNub Presenece App](http://pubnub.s3.amazonaws.com/rally/index.html)

Click the link above to try the app live!

## More PubNub Channel Presence Links

 - [Read Blog: Announcing PubNub Channel Presence](http://blog.pubnub.com/announcing-pubnub-channel-presence/)
 - [Play Video: PubNub Channel Presence – Introduction – As seen on Hacker News](https://vimeo.com/47541092)
 - [Play Video: PubNub Channel Presence – Introduction](https://vimeo.com/47742118)
 - [Play Video: PubNub Channel Presence – Code Walkthrough](https://vimeo.com/47740670)

![PubNub Channel Presence](https://s3.amazonaws.com/pubnub/assets/pubnub-real-time-channel-presence-global.png "PubNub Channel Presence")

## Channel Presence

Go straight to the [Live Chat App Powered by PubNub Channel Presence]() and
you can also watch the videos and continue reading about
PubNub Channel Presence.  The video links are just a bit further down.
Also you can skip ahead to the code walk-through in this blog to save time if
you already know about PubNub.
Otherwise you can learn a lot more by reading through this article.

If you are looking for the full source code, you are in luck!
This app is Open Source and under the MIT License.
This means you can do anything you want or need with no obligations to
the future or past contributors/creators.
Download the source from our GitHub repository: [Download Source Code](https://github.com/pubnub/pubnub-chat-channel-presence)

## Videos: HTML5 PubNub Chat Channel Presence Series

PubNub is the first Earth Scale infrastructure to innovate
Global User Presence.
Today, PubNub is the only service on the planet that streams Channel
Connectivity and Occupancy Analytics directly to your consumer devices such
as iPhones and Android phones and tablets.
PubNub Presence is a new type of framework that never existed before;
allowing you to be notified with user discovery events
on a PubNub channel instantly.
This enables new capabilities in your app such as User Events with Join/Leave
Status Changes.
PubNub Channel Presence in essence become consumable streams of events,
strait to your device.
The number of active users connected to a PubNub channel is streamed to
you automatically as the number of users actively waiting to receive
data on a channel changes over time.

The Real-time Web for Mobile Apps and Web Apps is undoubtedly a powerful
advent following HTML5 WebSockets, WebRTl and more.
Now with PubNub you can create groups of people and one-to-one apps on all
platforms easily without having to consider technologies or transports as
discussed in Are HTML5 WebSockets the Panacea for Real-Time Data Push.
Channel Presence plays a contending role,
especially paired with PubNub Galaxy and PubNub Pulse.
PubNub Galaxy provides unlimited scale of users on a single channel
(or billions of channels) enabling you to broadcast information and updates
to unlimited number of active users.
PubNub Pulse provides fast and efficient one-to-few messaging
capabilities at a condensed price point.

With PubNub Channel Presence, you can provide Live Real-time stream of
information based on the availability of users on your channels.
You get updated timelines which provide a peek into the past while delivering
an instant activity stream with details about a PubNub Channel at this very
moment in time.

Check it out!
PubNub has a new app to share with you, that is written
and constructed in cross-browser HTML5
and CSS3 code under the MIT License.
The App uses Twitter @Anywhere for authentication and
the user IDs provide a simple
way to join the presence experience via group chat and timeline streams.
You will also be able to see who is online and offline via their
Twitter Account Name and Account Photo.
The MIT App provides a new and elegant interface with quick accessible group
functionality with an inviting streamline appearance rendered in HTML5 and
CSS3 for your Mobile and Web Apps.

## New Dev Console V2

![Live PubNub Presenece App](https://s3.amazonaws.com/pubnub/assets/pubnub-dev-console-v2.png)

As we launch PubNub Channel Presence, we needed to provide a way for you to
debug and learn about the Presence Event Delivery Format.
That's why we've created for you a new and improve Developer Console V2 with
Presence Events built directly into the console interface.
Now you can easily see the data in JSON format as you build your app.
As a bonus your app will become an anonymous user and count as a real person
on your channel to help you debug presence events and occupancy counters.
Learn more by checkout out the new PubNub Developer Console V2.
Also you can see a demonstration of the Developer Console V2
in use in this video: PubNub Channel Presence -
Code Walk-through video on Vimeo.

## Real-time Mobile Apps and Web Apps

Getting devices to communicate with each other is practially free with PubNub
because it is so simple for your team to use our two function SDK.
Yes, you really only need just two functions!
Now that your app is able communicate efficiently, you simply need to answer
the question: "What to do when communication occurs?"
With PubNub you pretty much focus on the User Interaction and in most cases
you are driving UI - User Interface -Updates on a Mobile Phone or Web App.

Real-time allows you to strike a visual appeal creating powerful capabilities
through a user interface experience. Without the interface,
it is hard to understand what Real-time Web really means,
especially in the context of mobile.
The best way to understand Real-time is by producing an actively animating
user interface, constantly changing and updating in real-time as information
becomes available.
This is what PubNub enables.
Coming up Next is our walkthrough of the new MIT
open source app we built for you.

## Walkthrough of How it Works

When something changes someplace on Earth,
you want to be notified the instant this happens.
A trigger is invoked and anyone who is interested in the notification
instantly receives a PubNub message, and this message can be used to update
an interface or log records or make a phone ring or flicker a blinking light
or update text on the screen.

A lot can happen and the possibilities are seemingly endless.
We are going to talk about the app we made and what you can do with it.

## HTML5 and CSS3 Interfaces with Websockets and Real-time Web

You get to do some pretty amazing things with PubNub when
pairing with a User Interface.
We'll go over the code used to create the free app we provided for you to use
any way you need.
You should watch the video: [Play Video: PubNub Channel Presence – Code Walkthrough (SHORT)](https://vimeo.com/47740670)

## Customizing The Interface

Display styling is located in the `default.css` CSS3 file.
You can modify this file to change the appearance.
Some notable sections include the background image:

```css
#main {
    z-index: 50;
    margin: 0;
    border: 0;
    padding: 0;

    position: relative;
    overflow: hidden;

    width: 1024px;
    height: 768px;

    background: #fefef2 url(chat-bg.jpg) no-repeat;

    color: #ffe;
    font-size: 15px;
    font-family: "Open Sans";
    font-weight: 400;
    text-shadow: 1px 1px 1px rgba(0,0,0,0.2);
}
```

This section includes the main background image `url(chat-bg.jpg)`
that is used to set the tone of the chat experience.
You may want to modify this to fit your needs.
The CSS File itself is larger and there is a lot to see.
Thankfully all design elements and styles in the User Interface considerations
have been properly abstracted into the CSS file.

## Main Index File

The `index.html` file will contain information regarding the primary content
and components pieced together such as the Fonts, CSS and JavaScript.
The default Twitter user is defined in this file as well
as all language content.
You can internationalize this file by updating the english
words with replacement variables.

## JavaScript Source Code Intro

We'll discuss the important aspects to the source code here pertinent
to PubNub Channel Presence.
There are two aspects to obtaining Presence Events.
You can stream presence events as they occur directly to your target device
with the PubNub Presence Callback located inside the
PubNub Subscribe Function call.
You can also invoke a "Here Now" call which returns information about the
current state.
Note that the "Here Now" function will give you the full state information of
the channel where the Presence Callback would only stream new events to your
mobile app or web app.

## PubNub Channel Presence Callback

The Presence Callback is located inside the PubNub Subscribe Function as an
optional paramater.
When included in the subscribe function, you will automatically receive
presence events streamed to the specified callback.
Note that we will be using JavaScript as the language to demonstrate PubNub
Channel Presence; PubNub Channel Presence is available
in many other languages.
This is a sample usage in JavaScript of Channel Presence:

```javascript
// Open Bidirectional Socket Connection
PUBNUB.subscribe({
    channel  : "my_channel", // Channel Name
    connect  : connect, // OnConnect Callback
    callback : chat,  // Received Message Callback
    presence : presence // Presence Callback
});
```

As you can see the Presence Callback refers to a
JavaScript Function Reference.
The event information will pass to you in the following Format when
a User Joins the Channel:

```javascript
{
   "action":"join",
   "timestamp":1345546797,
   "uuid":"175c2c67-b2a9-470d-8f4b-1db94f90e39e",
   "occupancy":2
}
```

Next you need to know about the format when a User Leaves a Channel:

```javascript
{
   "action":"leave",
   "timestamp":1345549797,
   "uuid":"175c2c67-b2a9-470d-8f4b-1db94f90e39e",
   "occupancy":1
}
```

Notice that the occupancy number updates as expected.
The uuid section is a programmable ID that is associated with each user.
You can set this to whatever you need it to be in order
to identify your user.
When you init the PubNub instance,
you can set the UUID as an optional paramater.
The default value is a random UUID.

```javascript
// Setup Connection Based on User Data
// This will provide Connectivity References
var PUBNUB = PUBNUB.init({
    publish_key   : 'demo',
    subscribe_key : 'demo',
    ssl           : false,
    cipher_key    : '',
    uuid          : "YOUR UNIQUE USER ID HERE!"
});
```

With this example you see that you can set the UUID to anything you need.
This UUID value will be transmitted on Join/Leave events;
and also the here_now function.

## PubNub Channel Presence Here Now Function

The PubNub Channel Presence Here Now function provides you the ability
to answer the question: "Who is here right now?".
You will receive a list of UUIDs as well as an Occupancy number.
Here is an example of how to use the Here Now function:

```javascript
// Get List of Occupants and Occupancy Count.
function connect() {
    p.here_now({
        channel  : channel,
        callback : presence
    });
}
```

You pass in the channel name and the callback function to be used to send
the data to.
The Here Now data response will look like this:

```javascript
{
   "uuids":[
      "UUID1",
      "UUID2",
      "UUID3"
   ],
   "occupancy":0
}
```

As you can see you get a list of UUIDs of your users.
The UUIDs will either be randomly generated for anonymous users or will be
the UUIDs you supplied when you initialized the PubNub instance.

And now you know the basics for the PubNub Channel Presence with JavaScript.
Note that other Language SDKs wil provide similar interfaces with easy
copy/paste documentation on our GitHub Repository.
Checkout your source code for the PubNub API GitHub Repository.

Check us out at
[DevLink this August, 2012](http://devlink.net/Conference/Sessions.aspx)
where we will talk about PubNub Presence
and other amazing Real-time solutions:

## Building Real-Time Apps for Mobile and Web

You will Learn to build Real-time Messaging for Business Class Apps using
the best technologies available.
Live App under MIT Open Source License will be revealed.
We will cover DIY options and ready-made solutions for building applications
that communicate on the real-time web for mobile and tablet apps.
You will discover the intended use cases for AJAX, WebSockets and
Long Polling as we build an application in this session.
You get to understand the ubiquity of HTML5 and CSS3 on Mobile and Web for
interface development.
You will leave this session with a cookbook on making interactive
applications that communicate using the Best Mobile and Web Technologies
Available including PubNub and HTML5.


text:
import { applyMiddleware, compose, createStore } from 'redux';
import * as immutableState from 'redux-immutable-state-invariant';

import { reducers } from './reducers';

const middlewareEnhancer = process.env.NODE_ENV !== 'production' ? applyMiddleware(immutableState()) : undefined;
const devToolsEnhancer = (process.env.NODE_ENV !== 'production' && (window as any).devToolsExtension) ? (window as any).devToolsExtension() : undefined;
const storeEnhancer = devToolsEnhancer ? compose(middlewareEnhancer, devToolsEnhancer) : middlewareEnhancer;

const factory = storeEnhancer ? storeEnhancer(createStore) : createStore;
export const store = factory(reducers);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ClickNow\Checker\Exception;

class CommandNotFoundException extends CommandException
{
    /**
     * Command not found exception.
     *
     * @param string      $commandName
     * @param null|string $message
     */
    public function __construct($commandName, $message = null)
    {
        $msg = $message;

        if ($msg === null) {
            $msg = sprintf('Command `%s` was not found.', $commandName);
        }

        parent::__construct($commandName, $msg);
    }
}


text:
<?php

namespace Podio\Tests;

use PHPUnit\Framework\TestCase;
use PodioProgressItemField;

class PodioProgressItemFieldTest extends TestCase
{
    /**
     * @var \PodioProgressItemField
     */
    private $object;

    /**
     * @var \PodioProgressItemField
     */
    private $empty_values;

    /**
     * @var \PodioProgressItemField
     */
    private $zero_value;

    public function setUp(): void
    {
        parent::setUp();

        $this->object = new PodioProgressItemField([
            '__api_values' => true,
            'field_id' => 123,
            'values' => [
                ['value' => 55],
            ],
        ]);
        $this->empty_values = new PodioProgressItemField(['field_id' => 1]);
        $this->zero_value = new PodioProgressItemField([
            '__api_values' => true,
            'field_id' => 2,
            'values' => [['value' => 0]],
        ]);
    }

    public function test_can_construct_from_simple_value(): void
    {
        $object = new PodioProgressItemField([
            'field_id' => 123,
            'values' => 75,
        ]);
        $this->assertSame(75, $object->values);
    }

    public function test_can_provide_value(): void
    {
        $this->assertNull($this->empty_values->values);
        $this->assertSame(55, $this->object->values);
        $this->assertSame(0, $this->zero_value->values);
    }

    public function test_can_set_value(): void
    {
        $this->object->values = 75;
        $this->assertSame([['value' => 75]], $this->object->__attribute('values'));

        $this->object->values = 0;
        $this->assertSame(0, $this->zero_value->values);
    }

    public function test_can_humanize_value(): void
    {
        $this->assertSame('', $this->empty_values->humanized_value());
        $this->assertSame('55%', $this->object->humanized_value());
        $this->assertSame('0%', $this->zero_value->humanized_value());
    }

    public function test_can_convert_to_api_friendly_json(): void
    {
        $this->assertSame('null', $this->empty_values->as_json());
        $this->assertSame('55', $this->object->as_json());
        $this->assertSame('0', $this->zero_value->as_json());
    }
}


text:
/*************************************************************************/
/*  spatial_sample_player.cpp                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "spatial_sample_player.h"

#include "servers/audio_server.h"
#include "camera.h"
#include "servers/spatial_sound_server.h"
#include "scene/scene_string_names.h"

bool SpatialSamplePlayer::_set(const StringName& p_name, const Variant& p_value) {

	String name=p_name;

	if (name==SceneStringNames::get_singleton()->play_play) {
		if (library.is_valid()) {

			String what=p_value;
			if (what=="")
				stop_all();
			else
				play(what);

			played_back=what;
		}
		return true;

	}

	return false;
}

bool SpatialSamplePlayer::_get(const StringName& p_name,Variant &r_ret) const {

	String name=p_name;

	if (name==SceneStringNames::get_singleton()->play_play) {
		r_ret=played_back;
		return true;
	}

	return false;
}

void SpatialSamplePlayer::_get_property_list(List<PropertyInfo> *p_list) const {

	String en="";
	if (library.is_valid()) {
		List<StringName> samples;
		Ref<SampleLibrary> ncl=library;
		ncl->get_sample_list(&samples);
		for (List<StringName>::Element *E=samples.front();E;E=E->next()) {

			en+=",";
			en+=E->get();
		}
	}

	p_list->push_back( PropertyInfo( Variant::STRING, "play/play", PROPERTY_HINT_ENUM, en,PROPERTY_USAGE_EDITOR));

}
void SpatialSamplePlayer::_notification(int p_what) {

	switch(p_what) {

		case NOTIFICATION_ENTER_WORLD: {

			SpatialSoundServer::get_singleton()->source_set_polyphony(get_source_rid(),polyphony);

		} break;
	}

}

void SpatialSamplePlayer::set_sample_library(const Ref<SampleLibrary>& p_library) {

	library=p_library;
	_change_notify();
}

Ref<SampleLibrary> SpatialSamplePlayer::get_sample_library() const {

	return library;
}

void SpatialSamplePlayer::set_polyphony(int p_voice_count) {

	ERR_FAIL_COND(p_voice_count<0 || p_voice_count>64);
	polyphony=p_voice_count;
	if (get_source_rid().is_valid())
		SpatialSoundServer::get_singleton()->source_set_polyphony(get_source_rid(),polyphony);

}

int SpatialSamplePlayer::get_polyphony() const {

	return polyphony;
}

SpatialSamplePlayer::VoiceID SpatialSamplePlayer::play(const String& p_sample,int p_voice) {

	if (!get_source_rid().is_valid())
		return INVALID_VOICE;
	if (library.is_null())
		return INVALID_VOICE;
	if (!library->has_sample(p_sample))
		return INVALID_VOICE;
	Ref<Sample> sample = library->get_sample(p_sample);
	float vol_change = library->sample_get_volume_db(p_sample);
	float pitch_change = library->sample_get_pitch_scale(p_sample);

	VoiceID vid = SpatialSoundServer::get_singleton()->source_play_sample(get_source_rid(),sample->get_rid(),sample->get_mix_rate()*pitch_change,p_voice);
	if (vol_change)
		SpatialSoundServer::get_singleton()->source_voice_set_volume_scale_db(get_source_rid(),vid,vol_change);

	return vid;

}
//voices
void SpatialSamplePlayer::voice_set_pitch_scale(VoiceID p_voice, float p_pitch_scale) {

	if (!get_source_rid().is_valid())
		return;

	SpatialSoundServer::get_singleton()->source_voice_set_pitch_scale(get_source_rid(),p_voice,p_pitch_scale);

}

void SpatialSamplePlayer::voice_set_volume_scale_db(VoiceID p_voice, float p_volume_db) {

	if (!get_source_rid().is_valid())
		return;
	SpatialSoundServer::get_singleton()->source_voice_set_volume_scale_db(get_source_rid(),p_voice,p_volume_db);

}

bool SpatialSamplePlayer::is_voice_active(VoiceID p_voice) const {

	if (!get_source_rid().is_valid())
		return false;
	return SpatialSoundServer::get_singleton()->source_is_voice_active(get_source_rid(),p_voice);

}

void SpatialSamplePlayer::stop_voice(VoiceID p_voice) {

	if (!get_source_rid().is_valid())
		return;
	SpatialSoundServer::get_singleton()->source_stop_voice(get_source_rid(),p_voice);

}

void SpatialSamplePlayer::stop_all() {

	if (!get_source_rid().is_valid())
		return;

	for(int i=0;i<polyphony;i++) {

		SpatialSoundServer::get_singleton()->source_stop_voice(get_source_rid(),i);
	}
}

void SpatialSamplePlayer::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("set_sample_library","library:SampleLibrary"),&SpatialSamplePlayer::set_sample_library);
	ObjectTypeDB::bind_method(_MD("get_sample_library:SampleLibrary"),&SpatialSamplePlayer::get_sample_library);

	ObjectTypeDB::bind_method(_MD("set_polyphony","voices"),&SpatialSamplePlayer::set_polyphony);
	ObjectTypeDB::bind_method(_MD("get_polyphony"),&SpatialSamplePlayer::get_polyphony);

	ObjectTypeDB::bind_method(_MD("play","sample","voice"),&SpatialSamplePlayer::play,DEFVAL(NEXT_VOICE));
	//voices,DEV
	ObjectTypeDB::bind_method(_MD("voice_set_pitch_scale","voice","ratio"),&SpatialSamplePlayer::voice_set_pitch_scale);
	ObjectTypeDB::bind_method(_MD("voice_set_volume_scale_db","voice","db"),&SpatialSamplePlayer::voice_set_volume_scale_db);

	ObjectTypeDB::bind_method(_MD("is_voice_active","voice"),&SpatialSamplePlayer::is_voice_active);
	ObjectTypeDB::bind_method(_MD("stop_voice","voice"),&SpatialSamplePlayer::stop_voice);
	ObjectTypeDB::bind_method(_MD("stop_all"),&SpatialSamplePlayer::stop_all);

	BIND_CONSTANT( INVALID_VOICE );
	BIND_CONSTANT( NEXT_VOICE );

	ADD_PROPERTY( PropertyInfo( Variant::INT, "config/polyphony", PROPERTY_HINT_RANGE, "1,64,1"),_SCS("set_polyphony"),_SCS("get_polyphony"));
	ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "config/samples", PROPERTY_HINT_RESOURCE_TYPE,"SampleLibrary"),_SCS("set_sample_library"),_SCS("get_sample_library"));

}

SpatialSamplePlayer::SpatialSamplePlayer() {

	polyphony=1;

}

SpatialSamplePlayer::~SpatialSamplePlayer() {

}


text:
package org.ofbiz.widget.renderer;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;

import com.ilscipio.scipio.ce.util.servlet.ServletMapAdapter;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.ScriptUtil;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.MapStack;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntity;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.security.Security;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.control.LoginWorker;
import org.ofbiz.webapp.control.RequestHandler;
import org.ofbiz.webapp.event.JsonEventUtil;
import org.ofbiz.webapp.renderer.FtlContextFetcher;
import org.ofbiz.webapp.renderer.RenderContextFetcher;
import org.ofbiz.webapp.renderer.RendererInfo;
import org.ofbiz.webapp.renderer.SimpleContextFetcher;
import org.ofbiz.webapp.website.WebSiteWorker;
import org.ofbiz.widget.WidgetWorker;
import org.ofbiz.widget.cache.GenericWidgetOutput;
import org.ofbiz.widget.cache.ScreenCache;
import org.ofbiz.widget.cache.WidgetContextCacheKey;
import org.ofbiz.widget.model.AbstractModelAction;
import org.ofbiz.widget.model.ModelAction;
import org.ofbiz.widget.model.ModelLocation;
import org.ofbiz.widget.model.ModelScreen;
import org.ofbiz.widget.model.ModelWidget;
import org.ofbiz.widget.model.ScreenFactory;
import org.xml.sax.SAXException;

import freemarker.ext.jsp.TaglibFactory;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.ext.servlet.HttpSessionHashModel;
import freemarker.ext.servlet.ServletContextHashModel;

/**
 * Widget Library - Screen model class
 */
public class ScreenRenderer implements RenderContextFetcher, RendererInfo { // SCIPIO: interfaces

    private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());

    // SCIPIO: these get set in context to indicate render init has been run for the context.
    public static final String WEBAPP_RENDER_INIT_GUARD = "_scpRdrInitWebappRun"; // stored as Boolean
    public static final String LOCAL_RENDER_INIT_GUARDS = "_scpRdrInitLocalRuns"; // stored as a Set

    protected RenderContextFetcher contextFetcher; // SCIPIO: 2017-03-09: NEW: this can now attempt to fetch context and writer dynamically, if programmed
    protected ScreenStringRenderer screenStringRenderer;
    protected int renderFormSeqNumber = 0;

    public ScreenRenderer(Appendable writer, MapStack<String> context, ScreenStringRenderer screenStringRenderer) {
        this.contextFetcher = new SimpleContextFetcher(writer, context);
        this.screenStringRenderer = screenStringRenderer;
    }

    /**
     * SCIPIO: new constructor that fetches context dynamically.
     */
    public ScreenRenderer(RenderContextFetcher contextFetcher, ScreenStringRenderer screenStringRenderer) {
        this.contextFetcher = contextFetcher;
        this.screenStringRenderer = screenStringRenderer;
    }

    /**
     * SCIPIO: creates a renderer that uses FtlContextFetcher to get the output writer,
     * in other words gets the writer from the currently executing FTL environment if there is one,
     * or using the passed writer otherwise.
     * This prevents errors in template usage of screens.render (known ofbiz flaw).
     * FIXME: CURRENTLY ONLY SUPPORT FTL ENV.
     */
    public static ScreenRenderer makeWithEnvAwareFetching(Appendable writer, MapStack<String> context, ScreenStringRenderer screenStringRenderer) {
        return new ScreenRenderer(new FtlContextFetcher.FtlWriterOnlyFetcher(writer, context), screenStringRenderer);
    }

    public static RenderContextFetcher makeEnvAwareContextFetcher(Appendable writer, MapStack<String> context) {
        // FIXME: CURRENTLY ONLY SUPPORT FTL ENV
        return new FtlContextFetcher.FtlWriterOnlyFetcher(writer, context);
    }

    /**
     * Renders the named screen using the render environment configured when this ScreenRenderer was created.
     *

     * SCIPIO: modified for asString boolean which returns as string instead of going straight to writer.
     *
     * @param combinedName A combination of the resource name/location for the screen XML file and the name of the screen within that file, separated by a pound sign ("#"). This is the same format that is used in the view-map elements on the controller.xml file.
     * @param asString If true, returns content as string; otherwise goes direct to writer (stock behavior)
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public String render(String combinedName, boolean asString) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        String resourceName = ScreenFactory.getResourceNameFromCombined(combinedName);
        String screenName = ScreenFactory.getScreenNameFromCombined(combinedName);
        // SCIPIO: return proper
        return this.render(resourceName, screenName, asString, getContext(), getWriter());
        //return "";
    }

    protected String render(String combinedName, boolean asString, MapStack<String> context, Appendable writer) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        String resourceName = ScreenFactory.getResourceNameFromCombined(combinedName);
        String screenName = ScreenFactory.getScreenNameFromCombined(combinedName);
        // SCIPIO: return proper
        return this.render(resourceName, screenName, asString, context, writer);
        //return "";
    }

    /**
     * Renders the named screen using the render environment configured when this ScreenRenderer was created.
     *

     * SCIPIO: now delegating. Renders directly to writer.
     *
     * @param combinedName A combination of the resource name/location for the screen XML file and the name of the screen within that file, separated by a pound sign ("#"). This is the same format that is used in the view-map elements on the controller.xml file.
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public String render(String combinedName) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        String resourceName = ScreenFactory.getResourceNameFromCombined(combinedName);
        String screenName = ScreenFactory.getScreenNameFromCombined(combinedName);
        // SCIPIO: return proper
        return this.render(resourceName, screenName, false);
        //return "";
    }

    /**
     * SCIPIO: Renders the named screen using the render environment configured when this ScreenRenderer was created,
     * and returns the result as a string (instead of directly to writer).
     *
     * @param combinedName A combination of the resource name/location for the screen XML file and the name of the screen within that file, separated by a pound sign ("#"). This is the same format that is used in the view-map elements on the controller.xml file.
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public String renderAsString(String combinedName) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        String resourceName = ScreenFactory.getResourceNameFromCombined(combinedName);
        String screenName = ScreenFactory.getScreenNameFromCombined(combinedName);
        // SCIPIO: return proper
        return this.render(resourceName, screenName, true);
        //return "";
    }

    /**
     * Renders the named screen using the render environment configured when this ScreenRenderer was created.
     *

     * SCIPIO: now delegating. Renders directly to writer.
     *
     * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs
     * @param screenName The name of the screen within the XML file specified by the resourceName.
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public String render(String resourceName, String screenName) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        return render(resourceName, screenName, false);
    }

    /**
     * SCIPIO: Renders the named screen using the render environment configured when this ScreenRenderer was created,
     * and returns the result as a string (instead of directly to writer).
     *
     * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs
     * @param screenName The name of the screen within the XML file specified by the resourceName.
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public String renderAsString(String resourceName, String screenName) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        return render(resourceName, screenName, true);
    }

    /**
     * Renders the named screen using the render environment configured when this ScreenRenderer was created.
     *

     * SCIPIO: modified for asString boolean which returns as string instead of going straight to writer.
     *
     * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs
     * @param screenName The name of the screen within the XML file specified by the resourceName.
     * @param asString If true, returns content as string; otherwise goes direct to writer (stock behavior)
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public String render(String resourceName, String screenName, boolean asString) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        return render(resourceName, screenName, asString, getContext(), getWriter());
    }

    /**
     * Renders the named screen using the render environment configured when this ScreenRenderer was created.
     *

     * SCIPIO: modified for asString boolean which returns as string instead of going straight to writer.
     *
     * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs
     * @param screenName The name of the screen within the XML file specified by the resourceName.
     * @param asString If true, returns content as string; otherwise goes direct to writer (stock behavior)
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    protected String render(String resourceName, String screenName, boolean asString, MapStack<String> context, Appendable writer) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        ModelScreen modelScreen = ScreenFactory.getScreenFromLocation(resourceName, screenName);
        if (modelScreen.getUseCache()) {
            // if in the screen definition use-cache is set to true
            // then try to get an already built screen output from the cache:
            // 1) if we find it then we get it and attach it to the passed in writer
            // 2) if we can't find one, we create a new StringWriter,
            //    and pass it to the renderScreenString;
            //    then we wrap its content and put it in the cache;
            //    and we attach it to the passed in writer
            WidgetContextCacheKey wcck = new WidgetContextCacheKey(context);
            String screenCombinedName = resourceName + ":" + screenName;
            ScreenCache screenCache = new ScreenCache();
            GenericWidgetOutput gwo = screenCache.get(screenCombinedName, wcck);
            if (gwo == null) {
                checkRunRenderInit(resourceName, context); // SCIPIO: new hooks
                Writer sw = new StringWriter();
                modelScreen.renderScreenString(sw, context, screenStringRenderer);
                gwo = new GenericWidgetOutput(sw.toString());
                screenCache.put(screenCombinedName, wcck, gwo);
                // SCIPIO: may render to string
                if (asString) {
                    return gwo.toString();
                } else {
                    writer.append(gwo.toString());
                }
            } else {
                // SCIPIO: may render to string
                if (asString) {
                    return gwo.toString();
                } else {
                    writer.append(gwo.toString());
                }
            }
        } else {
            checkRunRenderInit(resourceName, context); // SCIPIO: new hooks
            context.put("renderFormSeqNumber", String.valueOf(renderFormSeqNumber));
            // SCIPIO: may render to string
            if (asString) {
                Writer sw = new StringWriter();
                modelScreen.renderScreenString(sw, context, screenStringRenderer);
                return sw.toString();
            } else {
                modelScreen.renderScreenString(writer, context, screenStringRenderer);
            }
        }
        return "";
    }

    /**
     * SCIPIO: Renders the named screen using the render environment configured when this ScreenRenderer was created,
     * and (unlike the other methods) by default protects the context by pushing it before/after the render,
     * with optional boolean to bypass it.
     *

     * Additionally, this method automatically handles the case where screenName is empty and included in resourceName.
     *
     * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs
     * @param screenName The name of the screen within the XML file specified by the resourceName. THIS METHOD ONLY: if empty, extracts it from resource
     * @param asString If true, returns content as string; otherwise goes direct to writer (stock behavior)
     * @param shareScope If false (default for this method - only), protects scope by pushing the context stack
     * @param ctxVars variables to dump into the context after it is pushed
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public String renderScoped(String resourceName, String screenName, Boolean asString, Boolean shareScope, Map<String, ?> ctxVars) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        if (asString == null) {
            asString = Boolean.FALSE;
        }
        MapStack<String> context = getContext();
        if (!Boolean.TRUE.equals(shareScope)) { // default is FALSE for this method (only!)
            context.push();
            if (ctxVars != null) {
                context.putAll(ctxVars);
            }
            try {
                if (UtilValidate.isNotEmpty(screenName)) {
                    return render(resourceName, screenName, asString, context, getWriter());
                } else {
                    return render(resourceName, asString, context, getWriter());
                }
            } finally {
                context.pop();
            }
        } else { // if (shareScope == Boolean.TRUE)
            if (ctxVars != null) {
                context.putAll(ctxVars);
            }
            if (UtilValidate.isNotEmpty(screenName)) {
                return render(resourceName, screenName, asString, context, getWriter());
            } else {
                return render(resourceName, asString, context, getWriter());
            }
        }
    }

    public String renderScoped(String resourceName, String screenName, Boolean asString, Boolean shareScope) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        return renderScoped(resourceName, screenName, asString, shareScope, null);
    }

    /**
     * SCIPIO: Renders the named screen using the render environment configured when this ScreenRenderer was created,
     * and (unlike the other methods) by default protects the context by pushing it before/after the render,
     * with optional boolean to bypass it, generic type/ftl friendly version.
     *

     * Additionally, this method automatically handles the case where screenName is empty and included in resourceName.
     *

     * This overload accepts Objects instead of Booleans, for FTL support.
     *
     * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs
     * @param screenName The name of the screen within the XML file specified by the resourceName. THIS METHOD ONLY: if empty, extracts it from resource
     * @param asString If true, returns content as string; otherwise goes direct to writer (stock behavior)
     * @param shareScope If false (default for this method - only), protects scope by pushing the context stack
     * @param ctxVars variables to dump into the context after it is pushed
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public String renderScopedGen(String resourceName, String screenName, Object asString, Object shareScope, Map<String, ?> ctxVars) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        return renderScoped(resourceName, screenName, UtilMisc.booleanValue(asString), UtilMisc.booleanValue(shareScope), ctxVars);
    }

    public String renderScopedGen(String resourceName, String screenName, Object asString, Object shareScope) throws GeneralException, IOException, SAXException, ParserConfigurationException {
        return renderScoped(resourceName, screenName, UtilMisc.booleanValue(asString), UtilMisc.booleanValue(shareScope));
    }

    /**
     * SCIPIO: SPECIAL INITIAL/TOP SCREEN INITIALIZATION.
     *

     * Should be run at the beginning of every screen render, just at the moment the top screen
     * render is about to start.
     */
    public void checkRunRenderInit(String resourceName) {
        checkRunRenderInit(resourceName, getContext());
    }

    /**
     * SCIPIO: SPECIAL INITIAL/TOP SCREEN INITIALIZATION.
     *

     * Should be run at the beginning of every screen render, just at the moment the top screen
     * render is about to start.
     */
    protected void checkRunRenderInit(String resourceName, MapStack<String> context) {
        if (!Boolean.TRUE.equals(context.get(WEBAPP_RENDER_INIT_GUARD))) {
            // run webapp init first (more general)
            runWebappRenderInitActions(context, resourceName);

            context.put(WEBAPP_RENDER_INIT_GUARD, Boolean.TRUE);
        }

        Set<String> localRunGuards = UtilGenerics.checkSet(context.get(LOCAL_RENDER_INIT_GUARDS));
        if (localRunGuards == null || !localRunGuards.contains(resourceName)) {
            // run local screens init last (more specific)
            runLocalRenderInitActions(context, resourceName);

            if (localRunGuards == null) {
                localRunGuards = new HashSet<>();
                localRunGuards.add(resourceName);
                context.put(LOCAL_RENDER_INIT_GUARDS, localRunGuards);
            }
        }
    }

    /**
     * setRenderFormUniqueSeq.
     * SCIPIO: TODO: REVIEW: Currently this is as good as unused as only a few form renderer forms were setting it... pointless for now
     */
    public void setRenderFormUniqueSeq(int renderFormSeqNumber) {
        this.renderFormSeqNumber = renderFormSeqNumber;
    }

    public ScreenStringRenderer getScreenStringRenderer() {
        return this.screenStringRenderer;
    }

    public void populateBasicContext(Map<String, Object> parameters, Delegator delegator, LocalDispatcher dispatcher, Security security, Locale locale, GenericValue userLogin) {
        populateBasicContext(getContext(), this, parameters, delegator, dispatcher, security, locale, userLogin);
    }

    // SCIPIO: new overload
    protected void populateBasicContext(MapStack<String> context, Map<String, Object> parameters, Delegator delegator, LocalDispatcher dispatcher, Security security, Locale locale, GenericValue userLogin) {
        populateBasicContext(context, this, parameters, delegator, dispatcher, security, locale, userLogin);
    }

    public static void populateBasicContext(MapStack<String> context, ScreenRenderer screens, Map<String, Object> parameters, Delegator delegator, LocalDispatcher dispatcher, Security security, Locale locale, GenericValue userLogin) {
        // ========== setup values that should always be in a screen context
        // include an object to more easily render screens
        context.put("screens", screens);

        // make a reference for high level variables, a global context
        Map<String, Object> globalContext = context.standAloneStack();
        context.put("globalContext", globalContext);

        // make sure the "nullField" object is in there for entity ops; note this is nullField and not null because as null causes problems in FreeMarker and such...
        context.put("nullField", GenericEntity.NULL_FIELD);

        context.put("parameters", parameters);
        context.put("delegator", delegator);
        context.put("dispatcher", dispatcher);
        context.put("security", security);
        context.put("locale", locale);
        context.put("userLogin", userLogin);
        context.put("nowTimestamp", UtilDateTime.nowTimestamp());
        try {
            Map<String, Object> result = dispatcher.runSync("getUserPreferenceGroup", UtilMisc.toMap("userLogin", userLogin, "userPrefGroupTypeId", "GLOBAL_PREFERENCES"));
            context.put("userPreferences", result.get("userPrefMap"));
        } catch (GenericServiceException e) {
            Debug.logError(e, "Error while getting user preferences: ", module);
        }

        globalContext.put("uiLabelMap", UtilProperties.getGlobalResourceBundleMap(locale, context)); // SCIPIO: 2.1.0: Now include global uiLabelMap as base
    }

    /**
     * This method populates the context for this ScreenRenderer based on the HTTP Request and Response objects and the ServletContext.
     * It leverages various conventions used in other places, namely the ControlServlet and so on, of OFBiz to get the different resources needed.
     *
     * @param request
     * @param response
     * @param servletContext
     */
    public void populateContextForRequest(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
        populateContextForRequest(getContext(), this, request, response, servletContext);
    }

    public static void populateContextForRequest(MapStack<String> context, ScreenRenderer screens, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
        populateContextForRequest(context, true, screens, request, response, servletContext);
    }

    // SCIPIO: Added overload with protectScope (default: true)
    public static void populateContextForRequest(MapStack<String> context, boolean protectScope, ScreenRenderer screens, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
        HttpSession session = request.getSession();

        // attribute names to skip for session and application attributes; these are all handled as special cases, duplicating results and causing undesired messages
        Set<String> attrNamesToSkip = UtilMisc.toSet("delegator", "dispatcher", "security", "webSiteId",
                "org.apache.catalina.jsp_classpath");
        Map<String, Object> parameterMap = UtilHttp.getCombinedMap(request, attrNamesToSkip);

        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");

        populateBasicContext(context, screens, parameterMap, (Delegator) request.getAttribute("delegator"),
                (LocalDispatcher) request.getAttribute("dispatcher"),
                (Security) request.getAttribute("security"), UtilHttp.getLocale(request), userLogin);

        context.put("autoUserLogin", session.getAttribute("autoUserLogin"));
        context.put("person", session.getAttribute("person"));
        context.put("partyGroup", session.getAttribute("partyGroup"));

        // some things also seem to require this, so here it is:
        request.setAttribute("userLogin", userLogin);

        // set up the user's time zone
        context.put("timeZone", UtilHttp.getTimeZone(request));

        // ========== setup values that are specific to OFBiz webapps

        context.put("request", request);
        context.put("response", response);
        context.put("session", session);
        context.put("application", servletContext);
        context.put("webappName", session.getAttribute("_WEBAPP_NAME_"));

        if (servletContext != null) {
            String rootDir = (String) context.get("rootDir");
            String webSiteId = (String) context.get("webSiteId");
            String https = (String) context.get("https");
            if (UtilValidate.isEmpty(rootDir)) {
                rootDir = servletContext.getRealPath("/");
                context.put("rootDir", rootDir);
            }
            if (UtilValidate.isEmpty(webSiteId)) {
                webSiteId = WebSiteWorker.getWebSiteId(request);
                context.put("webSiteId", webSiteId);
            }
            if (UtilValidate.isEmpty(https)) {
                https = (String) servletContext.getAttribute("https");
                context.put("https", https);
            }
        }
        context.put("javaScriptEnabled", UtilHttp.isJavaScriptEnabled(request));

        // SCIPIO: 2.1.0: Use Java types for use from anywhere; the ObjectWrapper then wraps them with SimpleMapAdapter.
        //// these ones are FreeMarker specific and will only work in FTL templates, mainly here for backward compatibility
        //context.put("sessionAttributes", new HttpSessionHashModel(session, FreeMarkerWorker.getDefaultOfbizWrapper()));
        //context.put("requestAttributes", new HttpRequestHashModel(request, FreeMarkerWorker.getDefaultOfbizWrapper()));
        context.put("applicationAttributes", ServletMapAdapter.wrapAttributes(servletContext)); // SCIPIO: new
        context.put("sessionAttributes", ServletMapAdapter.wrapAttributes(session));
        context.put("requestAttributes", ServletMapAdapter.wrapAttributes(request));

        TaglibFactory JspTaglibs = new TaglibFactory(servletContext);
        context.put("JspTaglibs", JspTaglibs);
        context.put("requestParameters",  UtilHttp.getParameterMap(request));

        ServletContextHashModel ftlServletContext = (ServletContextHashModel) request.getAttribute("ftlServletContext");
        context.put("Application", ftlServletContext);
        // SCIPIO: backward-compat
        //context.put("Request", context.get("requestAttributes"));
        context.put("Request", new HttpRequestHashModel(request, FreeMarkerWorker.getDefaultOfbizWrapper()));

        // this is a dummy object to stand-in for the JPublish page object for backward compatibility
        // SCIPIO: DEPRECATED - TODO: REMOVE: this is long deprecated (NOTE: if remove here, should remove all other references throughout renderer)
        context.put("page", new HashMap<String, Object>());

        // some information from/about the ControlServlet environment
        // SCIPIO: Use more reliable call
        //context.put("controlPath", request.getAttribute("_CONTROL_PATH_"));
        context.put("controlPath", RequestHandler.getControlPath(request));
        context.put("contextRoot", request.getAttribute("_CONTEXT_ROOT_"));
        context.put("serverRoot", request.getAttribute("_SERVER_ROOT_URL_"));
        context.put("checkLoginUrl", LoginWorker.makeLoginUrl(request));
        String externalLoginKey = LoginWorker.getExternalLoginKey(request);
        String externalKeyParam = externalLoginKey == null ? "" : "&externalLoginKey=" + externalLoginKey;
        context.put("externalLoginKey", externalLoginKey);
        context.put("externalKeyParam", externalKeyParam);

        // setup message lists
        List<Object> eventMessageList = UtilGenerics.toList(request.getAttribute("eventMessageList")); // SCIPIO: Switched to Object: List<String>
        if (eventMessageList == null) {
            eventMessageList = new ArrayList<>(); // SCIPIO: Switched to ArrayList
        }
        List<Object> errorMessageList = UtilGenerics.toList(request.getAttribute("errorMessageList")); // SCIPIO: Switched to Object: List<String>
        if (errorMessageList == null) {
            errorMessageList = new ArrayList<>(); // SCIPIO: Switched to ArrayList
        }

        if (request.getAttribute("_EVENT_MESSAGE_") != null) {
            // SCIPIO: 2018-02-27: will now be handled using correct point-of-use escaping (ftl)
            //eventMessageList.add(UtilFormatOut.replaceString((String) request.getAttribute("_EVENT_MESSAGE_"), "\n", "
"));
            eventMessageList.add(request.getAttribute("_EVENT_MESSAGE_")); // SCIPIO: Removed unnecessary cast: (String)
            request.removeAttribute("_EVENT_MESSAGE_");
        }
        List<Object> msgList = UtilGenerics.toList(request.getAttribute("_EVENT_MESSAGE_LIST_")); // SCIPIO: Switched to Object: List<String>
        if (msgList != null) {
            eventMessageList.addAll(msgList);
            request.removeAttribute("_EVENT_MESSAGE_LIST_");
        }
        if (request.getAttribute("_ERROR_MESSAGE_") != null) {
            // SCIPIO: 2018-02-27: will now be handled using correct point-of-use escaping (ftl)
            //errorMessageList.add(UtilFormatOut.replaceString((String) request.getAttribute("_ERROR_MESSAGE_"), "\n", "
"));
            errorMessageList.add(request.getAttribute("_ERROR_MESSAGE_")); // SCIPIO: Removed unnecessary cast: (String)
            request.removeAttribute("_ERROR_MESSAGE_");
        }
        if (session.getAttribute("_ERROR_MESSAGE_") != null) {
            // SCIPIO: 2018-02-27: will now be handled using correct point-of-use escaping (ftl)
            //errorMessageList.add(UtilFormatOut.replaceString((String) session.getAttribute("_ERROR_MESSAGE_"), "\n", "
"));
            errorMessageList.add(session.getAttribute("_ERROR_MESSAGE_")); // SCIPIO: Removed unnecessary cast: (String)
            session.removeAttribute("_ERROR_MESSAGE_");
        }
        msgList = UtilGenerics.toList(request.getAttribute("_ERROR_MESSAGE_LIST_"));
        if (msgList != null) {
            errorMessageList.addAll(msgList);
            request.removeAttribute("_ERROR_MESSAGE_LIST_");
        }
        context.put("eventMessageList", eventMessageList);
        context.put("errorMessageList", errorMessageList);

        if (request.getAttribute("serviceValidationException") != null) {
            context.put("serviceValidationException", request.getAttribute("serviceValidationException"));
            request.removeAttribute("serviceValidationException");
        }

        // if there was an error message, this is an error
        context.put("isError", errorMessageList.size() > 0 ? Boolean.TRUE : Boolean.FALSE);
        // if a parameter was passed saying this is an error, it is an error
        if ("true".equals(parameterMap.get("isError"))) {
            context.put("isError", Boolean.TRUE);
        }

        // SCIPIO: set the request method for easy access. it is UPPERCASE.
        context.put("requestMethod", request.getMethod().toUpperCase());

        // SCIPIO: Optimization/Security: Always put widgetVerbose in context so that:
        // 1) easier access 2) it's already a boolean 3) request parameters not consulted by ModelWidget#widgetBoundaryCommentsEnabled (security)
        ModelWidget.setWidgetBoundaryCommentsEnabledField(context, request);

        // SCIPIO: 2017-05-03: some new special request parameters/attributes for potential use by renderers
        WidgetRenderTargetExpr.populateRenderTargetVars(context);

        // SCIPIO: 2017-05-19: some new special request parameters/attributes for potential use by renderers
        JsonEventUtil.copyOutVarsToCtx(request, context);

        // SCIPIO: ensure rendererVisualThemeResources has been set (only other central place for this call would be render() method)
        VisualThemeWorker.getVisualThemeResources(context);

        // SCIPIO: General context scripts and per-webapp context scripts
        populateContextScripts(context);
        populateWebappContextScripts(context, request, response, servletContext);

        // to preserve these values, push the MapStack
        if (protectScope) { // SCIPIO: Added protectScope
            context.push();
        }
    }

    public MapStack<String> getContext() {
        return contextFetcher.getContext(); // SCIPIO: now dynamic
    }

    /**
     * SCIPIO: returns the writer used when asString is false in render calls.
     */
    public Appendable getWriter() {
        return contextFetcher.getWriter();
    }

    /**
     * SCIPIO: returns the ContextFetcher in use.
     */
    public RenderContextFetcher getContextFetcher() {
        return contextFetcher;
    }

    /**
     * SCIPIO: sets a new ContextFetcher.
     * WARN: ADVANCED USAGE ONLY.
     */
    public void setContextFetcher(RenderContextFetcher contextFetcher) {
        this.contextFetcher = contextFetcher;
    }

    public void populateContextForService(DispatchContext dctx, Map<String, Object> serviceContext) {
        MapStack<String> context = getContext();

        this.populateBasicContext(context, serviceContext, dctx.getDelegator(), dctx.getDispatcher(),
                dctx.getSecurity(), (Locale) serviceContext.get("locale"), (GenericValue) serviceContext.get("userLogin")); // SCIPIO: pass main context

        // SCIPIO: ensure rendererVisualThemeResources has been set (only other central place for this call would be render() method)
        VisualThemeWorker.getVisualThemeResources(context);

        // SCIPIO: 2018-11-01: This was wrong, but unlikely was noticed by any real code
        //populateContextScripts(serviceContext);
        populateContextScripts(context);
    }

    /**
     * SCIPIO: Calls scripts defined in widgetContextScripts.properties to help populate root context.
     *

     * Should be called after rest of context populated and scripts will fish out what they need out of the context.
     */
    public static void populateContextScripts(Map<String, Object> context) {
        // SCIPIO: runs scripts on initial render context to help populate
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> resources;
        try {
            resources = loader.getResources("widgetContextScripts.properties");
        } catch (IOException e) {
            Debug.logError(e, "Could not load list of widgetContextScripts.properties", module);
            throw UtilMisc.initCause(new InternalError(e.getMessage()), e);
        }
        while (resources.hasMoreElements()) {
            URL propertyURL = resources.nextElement();
            if (Debug.infoOn()) {
                Debug.logInfo("loading properties: " + propertyURL, module);
            }
            Properties props = UtilProperties.getProperties(propertyURL);
            if (UtilValidate.isNotEmpty(props)) {
                for (Iterator<Object> i = props.keySet().iterator(); i.hasNext();) {
                    String key = (String) i.next();
                    String scriptLocation = props.getProperty(key);
                    if (Debug.verboseOn()) {
                        Debug.logVerbose("Running widget context script " + scriptLocation, module);
                    }

                    String location = WidgetWorker.getScriptLocation(scriptLocation);
                    String method = WidgetWorker.getScriptMethodName(scriptLocation);
                    ScriptUtil.executeScript(location, method, context);
                }
            }
        }
    }

    /**
     * SCIPIO: Calls the script named by widgetContextScriptLocation init-parameter in web.xml.
     *

     * Should be called after rest of context populated and scripts will fish out what they need out of the context,
     * and after #populateContextScripts, because these are more specific.
     */
    public static void populateWebappContextScripts(Map<String, Object> context,
            HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
        // first run generic groovy/minilang script
        String fullLoc = getWebappContextScriptLocation(request, servletContext);
        if (fullLoc != null) {
            String location = WidgetWorker.getScriptLocation(fullLoc);
            String method = WidgetWorker.getScriptMethodName(fullLoc);
            ScriptUtil.executeScript(location, method, context);
        }
    }

    /**
     * SCIPIO: Return webapp-specific context script location based on web.xml configuration:
     * renderContextScriptLocation init-parameter.
     */
    public static String getWebappContextScriptLocation(HttpServletRequest request, ServletContext servletContext) {
        String res = (String) servletContext.getAttribute("widgetContextScriptLocation");
        if (res != null && !res.isEmpty()) {
            return res;
        }
        return null;
    }

    /**
     * SCIPIO: Runs webapp-specific render init actions.
     */
    public static void runWebappRenderInitActions(Map<String, Object> context, String resource) {
        HttpServletRequest request = (HttpServletRequest) context.get("request");
        if (request == null) {
            return;
        }
        ServletContext servletContext = request.getServletContext(); // SCIPIO: get context using servlet API 3.0

        // next run screen-based one
        ModelLocation modelLoc = getRenderInitScriptScreenLocation(request, servletContext);
        if (modelLoc.hasResource()) {
            ModelScreen scriptScreen;
            try {
                scriptScreen = ScreenFactory.getScreenFromLocationOrNull(modelLoc.getResource(),
                        modelLoc.getName());
            } catch (Exception e) {
                Debug.logError(e, "Could not resolve render init script screen location: " + modelLoc, module);
                scriptScreen = null;
            }
            if (scriptScreen != null) {
                try {
                    AbstractModelAction.runSubActions(scriptScreen.getSection().getActions(), context);
                } catch (Exception e) {
                    Debug.logError(e, "Error running render init screen actions [" + modelLoc.toString() + "]", module);
                }
            }
        }
    }

    /**
     * SCIPIO: Return render init script screen location based on web.xml configuration:
     * renderInitScriptScreenLocation init-parameter, with fallback on mainDecoratorLocation.
     * The default screen name is "webapp-common-actions".
     */
    public static ModelLocation getRenderInitScriptScreenLocation(HttpServletRequest request, ServletContext servletContext) {
        ModelLocation modelLoc = (ModelLocation) servletContext.getAttribute("_RIS_screenModelLoc");
        if (modelLoc != null) { // NOTE: no need for synchronization; getAttribute is thread safe and races don't matter
            return modelLoc;
        }

        String strLoc = (String) servletContext.getAttribute("renderInitScriptScreenLocation");
        if (strLoc != null && !strLoc.isEmpty()) {
            if (!strLoc.contains("#")) { // is name only
                String mainDec = (String) servletContext.getAttribute("mainDecoratorLocation");
                if (mainDec != null && !mainDec.isEmpty()) {
                    modelLoc = ModelLocation.fromResAndName(mainDec, strLoc);
                }
            } else {
                modelLoc = ModelLocation.fromAddress(strLoc);
            }
        } else {
            strLoc = (String) servletContext.getAttribute("mainDecoratorLocation");
            if (strLoc != null && !strLoc.isEmpty()) {
                modelLoc = ModelLocation.fromResAndName(strLoc, "webapp-common-actions");
            }
        }

        if (modelLoc == null) {
            modelLoc = ModelLocation.EMPTY_LOCATION;
        }
        // cache it
        servletContext.setAttribute("_RIS_screenModelLoc", modelLoc);
        return modelLoc;
    }

    /**
     * SCIPIO: Runs local render init actions. NOTE: can be more than one of these run in a request if
     * screens from multiple webapps are involved.
     */
    public static void runLocalRenderInitActions(Map<String, Object> context, String resource) {
        List<ModelAction> actions;
        try {
            actions = ScreenFactory.getScreensFromLocation(resource).getEffectiveSettings().getLocalRenderInitActions();
        } catch (Exception e) {
            Debug.logError(e, "Could not resolve render init script screen location from "
                    + "web.xml renderInitScriptScreenLocation/mainDecoratorLocation config: " + resource, module);
            actions = null;
        }
        if (actions != null) {
            try {
                AbstractModelAction.runSubActions(actions, context);
            } catch (Exception e) {
                Debug.logError(e, "Error running local render init screen actions for [" + resource + "]", module);
            }
        }
    }

    /**
     * SCIPIO: Convenience method to get the screenStringRenderer name.
     */
    @Override
    public String getRendererName() {
        return screenStringRenderer.getRendererName();
    }
}


text:
package cmd

import (
	"fmt"
	"net/url"
	"os"

	"github.com/spf13/cobra"
)

// GroupsDeleteTagCmdGroupId holds value of 'group_id' option
var GroupsDeleteTagCmdGroupId string

// GroupsDeleteTagCmdTagName holds value of 'tag_name' option
var GroupsDeleteTagCmdTagName string

func init() {
	GroupsDeleteTagCmd.Flags().StringVar(&GroupsDeleteTagCmdGroupId, "group-id", "", TRAPI("Target group ID."))

	GroupsDeleteTagCmd.Flags().StringVar(&GroupsDeleteTagCmdTagName, "tag-name", "", TRAPI("Tag name to be deleted. (This will be part of a URL path, so it needs to be percent-encoded. In JavaScript, specify the name after it has been encoded using encodeURIComponent().)"))
	GroupsCmd.AddCommand(GroupsDeleteTagCmd)
}

// GroupsDeleteTagCmd defines 'delete-tag' subcommand
var GroupsDeleteTagCmd = &cobra.Command{
	Use:   "delete-tag",
	Short: TRAPI("/groups/{group_id}/tags/{tag_name}:delete:summary"),
	Long:  TRAPI(`/groups/{group_id}/tags/{tag_name}:delete:description`) + "\n\n" + createLinkToAPIReference("Group", "deleteGroupTag"),
	RunE: func(cmd *cobra.Command, args []string) error {

		if len(args) > 0 {
			return fmt.Errorf("unexpected arguments passed => %v", args)
		}

		opt := &apiClientOptions{
			BasePath: "/v1",
			Language: getSelectedLanguage(),
		}

		ac := newAPIClient(opt)
		if v := os.Getenv("SORACOM_VERBOSE"); v != "" {
			ac.SetVerbose(true)
		}
		err := authHelper(ac, cmd, args)
		if err != nil {
			cmd.SilenceUsage = true
			return err
		}

		param, err := collectGroupsDeleteTagCmdParams(ac)
		if err != nil {
			return err
		}

		body, err := ac.callAPI(param)
		if err != nil {
			cmd.SilenceUsage = true
			return err
		}

		if body == "" {
			return nil
		}

		if rawOutput {
			_, err = os.Stdout.Write([]byte(body))
		} else {
			return prettyPrintStringAsJSON(body)
		}
		return err
	},
}

func collectGroupsDeleteTagCmdParams(ac *apiClient) (*apiParams, error) {
	var parsedBody interface{}
	var err error
	err = checkIfRequiredStringParameterIsSupplied("group_id", "group-id", "path", parsedBody, GroupsDeleteTagCmdGroupId)
	if err != nil {
		return nil, err
	}

	err = checkIfRequiredStringParameterIsSupplied("tag_name", "tag-name", "path", parsedBody, GroupsDeleteTagCmdTagName)
	if err != nil {
		return nil, err
	}

	return &apiParams{
		method: "DELETE",
		path:   buildPathForGroupsDeleteTagCmd("/groups/{group_id}/tags/{tag_name}"),
		query:  buildQueryForGroupsDeleteTagCmd(),

		noRetryOnError: noRetryOnError,
	}, nil
}

func buildPathForGroupsDeleteTagCmd(path string) string {

	escapedGroupId := url.PathEscape(GroupsDeleteTagCmdGroupId)

	path = strReplace(path, "{"+"group_id"+"}", escapedGroupId, -1)

	escapedTagName := url.PathEscape(GroupsDeleteTagCmdTagName)

	path = strReplace(path, "{"+"tag_name"+"}", escapedTagName, -1)

	return path
}

func buildQueryForGroupsDeleteTagCmd() url.Values {
	result := url.Values{}

	return result
}


text:
#include <eosio/eosio.hpp>                   /* contract, datastream, unsigned_int */
#include <vector>                            /* vector */

using namespace eosio;
using namespace std;

extern "C" {
__attribute__((eosio_wasm_import))
void set_parameters_packed( const char* params, uint32_t params_size );
__attribute__((eosio_wasm_import))
void set_action_return_value(void*, size_t);
};

class [[eosio::contract]] action_results : public contract {
  public:
      using contract::contract;

      [[eosio::action]]
      int actionresret() {
         return 10;
      }

      [[eosio::action]]
      vector<char> retoverlim() {
         return vector<char>(512, '0');
      }

      [[eosio::action]]
      vector<char> retlim() {
         //2 is for size of type unsigned_int
         return vector<char>(256 - 2, '0');
      }

      [[eosio::action]]
      vector<char> ret1overlim() {
         //2 is for size of type unsigned_int
         return vector<char>(257 - 2, '0');
      }

      /**
       * required to be called as system contract for priviledged host function call
       */
      [[eosio::action]]
      void retmaxlim() {

         char buffer[12];
         datastream<char*> ds((char*)&buffer, sizeof(buffer));
         //20mb is MAX_SIZE_OF_BYTE_ARRAYS that is defined in fc.
         //we don't use fc in contracts so using hardcode here.
         ds << unsigned_int(uint32_t(1)) << unsigned_int(uint32_t(17)) << uint32_t(20*1024*1024);
         set_parameters_packed(buffer, ds.tellp());

         vector<char> ret_vec(20*1024*1024, '1');
         //return ret_vec;
         set_action_return_value( ret_vec.data(), ret_vec.size() );
      }

      [[eosio::action]]
      void setliminv() {

         char buffer[12];
         datastream<char*> ds((char*)&buffer, sizeof(buffer));

         ds << unsigned_int(uint32_t(1)) << unsigned_int(uint32_t(17)) << uint32_t(20*1024*1024 + 1);
         //trying to set limit too large
         set_parameters_packed(buffer, ds.tellp());
      }

  private:
};


text:
from __future__ import unicode_literals

import struct

class Primitive(object):
    """
    The most basic structure of the protocol.  Subclassed, never used directly.

    Used as a building block for the various actually-used primitives outlined
    in the Zookeeper jute file:

    https://github.com/apache/zookeeper/blob/trunk/src/zookeeper.jute
    """
    fmt = None

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

    def render(self):
        """
        Returns a two-element tuple with the ``struct`` format and list value.

        The value is wrapped in a list, as there are some primitives that deal
        with multiple values.  Any caller of `render()` should expect a list.
        """
        return self.fmt, [self.value]

    @classmethod
    def parse(cls, buff, offset):
        """
        Given a buffer and offset, returns the parsed value and new offset.

        Uses the ``format`` class attribute to unpack the data from the buffer
        and determine the used up number of bytes.
        """
        primitive_struct = struct.Struct("!" + cls.fmt)

        value = primitive_struct.unpack_from(buff, offset)[0]
        offset += primitive_struct.size

        return value, offset

    def __eq__(self, other):
        """
        Basic equality method that tests equality of the ``value`` attributes.
        """
        return self.value == other.value

    def __str__(self):
        return "%s(%s)" % (self.__class__.__name__, self.value)

class VariablePrimitive(Primitive):
    """
    Base primitive for variable-length scalar primitives (strings and bytes).
    """
    size_primitive = None

    def render_value(self, value):
        raise NotImplementedError

    @classmethod
    def parse_value(cls, value):
        raise NotImplementedError

    def render(self):
        """
        Returns the ``struct`` format and list of the size and value.

        The format is derived from the size primitive and the length of the
        resulting encoded value (e.g. the format for a string of 'foo' ends
        up as 'h3s'.

        .. note ::
          The value is expected to be string-able (wrapped in ``str()``) and is
          then encoded as UTF-8.
        """
        size_format = self.size_primitive.fmt

        if self.value is None:
            return size_format, [-1]

        value = self.render_value(self.value)

        size = len(value)

        fmt = "%s%ds" % (size_format, size)

        return fmt, [size, value]

    @classmethod
    def parse(cls, buff, offset):
        """
        Given a buffer and offset, returns the parsed value and new offset.

        Parses the ``size_primitive`` first to determine how many more bytes to
        consume to extract the value.
        """
        size, offset = cls.size_primitive.parse(buff, offset)
        if size == -1:
            return None, offset

        var_struct = struct.Struct("!%ds" % size)

        value = var_struct.unpack_from(buff, offset)[0]
        value = cls.parse_value(value)
        offset += var_struct.size

        return value, offset

class Bool(Primitive):
    """
    Represents a boolean (true or false) value.

    Renders as an unsigned char (1 byte).
    """
    fmt = "?"

class Byte(Primitive):
    """
    Represents a single 8-bit byte.
    """
    fmt = "b"

class Int(Primitive):
    """
    Represents an 32-bit signed integer.
    """
    fmt = "i"

class Long(Primitive):
    """
    Represents an 64-bit signed integer.
    """
    fmt = "q"

class Float(Primitive):
    """
    Represents a single-precision floating poing conforming to IEEE 754.
    """
    fmt = "f"

class Double(Primitive):
    """
    Represents a double-precision floating poing conforming to IEEE 754.
    """
    fmt = "d"

class UString(VariablePrimitive):
    """
    Represents a unicode string value, length denoted by a 32-bit integer.
    """
    size_primitive = Int

    def render_value(self, value):
        return value.encode("utf8")

    @classmethod
    def parse_value(cls, value):
        return value.decode("utf8")

    def __str__(self):
        return self.value

class Buffer(VariablePrimitive):
    """
    Represents a bytestring value, length denoted by a 32-bit signed integer.
    """
    size_primitive = Int

    def render_value(self, value):
        return value

    @classmethod
    def parse_value(cls, value):
        return value

class Vector(Primitive):
    """
    Represents an array of any arbitrary `Primitive` or ``Part``.

    Not used directly but rather by its ``of()`` classmethod to denote an
    ``Vector.of(<something>)``.
    """
    item_class = None

    @classmethod
    def of(cls, part_class):
        """
        Creates a new class with the ``item_class`` attribute properly set.
        """
        copy = type(
            str("VectorOf%s" % part_class.__name__),
            cls.__bases__, dict(cls.__dict__)
        )
        copy.item_class = part_class

        return copy

    def render(self):
        """
        Creates a composite ``struct`` format and the data to render with it.

        The format and data are prefixed with a 32-bit integer denoting the
        number of elements, after which each of the items in the array value
        are ``render()``-ed and added to the format and data as well.
        """
        value = self.value
        if value is None:
            value = []

        fmt = [Int.fmt]
        data = [len(value)]

        for item_value in value:
            if issubclass(self.item_class, Primitive):
                item = self.item_class(item_value)
            else:
                item = item_value

            item_format, item_data = item.render()
            fmt.extend(item_format)
            data.extend(item_data)

        return "".join(fmt), data

    @classmethod
    def parse(cls, buff, offset):
        """
        Parses a raw buffer at offset and returns the resulting array value.

        Starts off by `parse()`-ing the 32-bit element count, followed by
        parsing items out of the buffer "count" times.
        """
        count, offset = Int.parse(buff, offset)

        values = []
        for _ in range(count):
            value, new_offset = cls.item_class.parse(buff, offset)

            values.append(value)
            offset = new_offset

        return values, offset

    def __str__(self):
        return "%s[%s]" % (
            self.item_class.__name__, ", ".join(map(str, self.value))
        )


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Centralbl. 45:106. 1891

#### Original name
null

### Remarks
null


text:
package xyz.zimuju.basekit.basal;

import android.content.Context;

/*
 * @description BasicView View 的基类
 * @author Nathaniel - nathanwriting@126.com
 * @time 2017/06/08 - 23:14
 * @version 1.0.0
 */
public interface BasalView {
    void showToast(String message);

    Context getContext();

    // void showLoading();

    // void hideLoading();
}


text:
package com.actian.services.dataflow.aggregators;

import java.util.List;

import com.pervasive.datarush.DRException;
import com.pervasive.datarush.operators.group.Aggregator;
import com.pervasive.datarush.operators.group.AggregatorFactory;
import com.pervasive.datarush.operators.group.InvalidArgumentCountException;
import com.pervasive.datarush.types.ScalarTokenType;

public final class ConcatFactory implements AggregatorFactory {

	public ConcatFactory() {
	}

	public String getKey() {
		return "concat";
	}

	public Aggregator newAggregator(List<String> inputNames, ScalarTokenType[] inputs) {
		if (inputs.length != 2) {
			throw new InvalidArgumentCountException(getKey(),2, inputs.length);
		}

		ScalarTokenType valueType = inputs[0];

		if (valueType.isScalar()) {
			return new ConcatString(inputNames.get(1));
		} else {
			throw new DRException("concat is unsupported for token type " + valueType + " for field " + inputNames.get(0));
		}
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<plugin>
	<documentation>
    Use this plugin to setup the android platform. It downloads the SDK, NDK and ant. It also installs the necessary android packages for basic usage.
	</documentation>
	<configuration>
	</configuration>
</plugin>


text:
var util = require('util')
  , Bot = require('../lib').Bot

function MyBot(options) {
  Bot.call(this, options)
}
Bot.extend(MyBot)

MyBot.prototype.startup = startup
function startup(callback) {
  var self = this

  console.log('+', this.id, 'Started.')

  setTimeout(function () {
    self.stop()
  }, 500)

  Bot.prototype.startup.call(this, callback)
}

MyBot.prototype.tick = tick
function tick(callback) {
  console.log(this.id, 'Ticked.')
  callback()
}

MyBot.prototype.shutdown = shutdown
function shutdown(callback) {
  console.log('-', this.id, 'Stopped.')

  Bot.prototype.shutdown.call(this, callback)
}

module.exports = MyBot


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.devkit.dom.index;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.DataInputOutputUtilRt;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.Processor;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.ID;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.DataInputOutputUtil;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.devkit.dom.*;
import org.jetbrains.idea.devkit.dom.index.RegistrationEntry.RegistrationType;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.*;

/**
 * Class FQN or ID -> entry in {@code plugin.xml}.
 *

 *

 *
Application/Project/Module-component class - {@link Component#getImplementationClass()}

 *
Action/ActionGroup class - {@link Action#getClazz()}/{@link Group#getClazz()}

 *
Action/ActionGroup ID - {@link ActionOrGroup#getId()}

 *
Application/Project Listener class - {@link Listeners.Listener#getListenerClassName()}

 *

 */
public class IdeaPluginRegistrationIndex extends PluginXmlIndexBase<String, List<RegistrationEntry>> {

  private static final int INDEX_VERSION = 4;

  private static final ID<String, List<RegistrationEntry>> NAME = ID.create("IdeaPluginRegistrationIndex");

  private final DataExternalizer<List<RegistrationEntry>> myValueExternalizer = new DataExternalizer<>() {

    @Override
    public void save(@NotNull DataOutput out, List<RegistrationEntry> values) throws IOException {
      DataInputOutputUtilRt.writeSeq(out, values, entry -> {
        DataInputOutputUtil.writeINT(out, entry.getRegistrationType().ordinal());
        DataInputOutputUtil.writeINT(out, entry.getOffset());
      });
    }

    @Override
    public List<RegistrationEntry> read(@NotNull DataInput in) throws IOException {
      return DataInputOutputUtilRt.readSeq(in, () -> {
        RegistrationType type = RegistrationType.values()[DataInputOutputUtil.readINT(in)];
        int offset = DataInputOutputUtil.readINT(in);
        return new RegistrationEntry(type, offset);
      });
    }
  };

  @NotNull
  @Override
  public ID<String, List<RegistrationEntry>> getName() {
    return NAME;
  }

  @Override
  protected Map<String, List<RegistrationEntry>> performIndexing(IdeaPlugin plugin) {
    return new RegistrationIndexer(plugin).indexFile();
  }

  @NotNull
  @Override
  public KeyDescriptor<String> getKeyDescriptor() {
    return EnumeratorStringDescriptor.INSTANCE;
  }

  @NotNull
  @Override
  public DataExternalizer<List<RegistrationEntry>> getValueExternalizer() {
    return myValueExternalizer;
  }

  @Override
  public int getVersion() {
    return INDEX_VERSION;
  }

  public static boolean isRegisteredApplicationComponent(PsiClass psiClass, GlobalSearchScope scope) {
    return isRegistered(psiClass, scope, RegistrationType.APPLICATION_COMPONENT);
  }

  public static boolean isRegisteredProjectComponent(PsiClass psiClass, GlobalSearchScope scope) {
    return isRegistered(psiClass, scope, RegistrationType.PROJECT_COMPONENT);
  }

  public static boolean isRegisteredModuleComponent(PsiClass psiClass, GlobalSearchScope scope) {
    return isRegistered(psiClass, scope, RegistrationType.MODULE_COMPONENT);
  }

  public static boolean isRegisteredAction(PsiClass psiClass, GlobalSearchScope scope) {
    return isRegistered(psiClass, scope, RegistrationType.ACTION);
  }

  public static boolean processListener(@NotNull Project project,
                                        PsiClass listenerClass,
                                        GlobalSearchScope scope,
                                        Processor<? super Listeners.Listener> processor) {
    final String key = listenerClass.getQualifiedName();
    assert key != null : listenerClass;

    List<XmlTag> tags = collectTags(project, key, scope,
                                    EnumSet.of(RegistrationType.APPLICATION_LISTENER, RegistrationType.PROJECT_LISTENER));

    return ContainerUtil.process(tags, tag -> {
      final DomElement domElement = DomManager.getDomManager(project).getDomElement(tag);

      if (!(domElement instanceof Listeners.Listener)) return true;
      return processor.process((Listeners.Listener)domElement);
    });
  }

  private static boolean isRegistered(PsiClass psiClass, GlobalSearchScope scope, RegistrationType type) {
    final String qualifiedName = psiClass.getQualifiedName();
    if (qualifiedName == null) {
      return false;
    }

    return !FileBasedIndex.getInstance()
      .processValues(NAME, qualifiedName, null,
                     (file, value) -> ContainerUtil.process(value, entry -> !(entry.getRegistrationType() == type)),
                     scope);
  }

  public static boolean processAllActionOrGroup(@NotNull Project project,
                                                GlobalSearchScope scope,
                                                Processor<? super ActionOrGroup> processor) {
    Set<String> keys = new HashSet<>();
    FileBasedIndex.getInstance().processAllKeys(NAME, s -> keys.add(s), scope, null);
    return ContainerUtil.process(keys, s -> processActionOrGroup(project, s, scope, processor));
  }

  public static boolean processActionOrGroup(@NotNull Project project,
                                             @NotNull String actionOrGroupId,
                                             GlobalSearchScope scope,
                                             Processor<? super ActionOrGroup> processor) {
    return doProcessActionOrGroup(project, actionOrGroupId, scope,
                                  EnumSet.of(RegistrationType.ACTION_ID, RegistrationType.ACTION_GROUP_ID),
                                  processor);
  }

  public static boolean processAction(@NotNull Project project,
                                      @NotNull String actionId,
                                      GlobalSearchScope scope,
                                      Processor<? super ActionOrGroup> processor) {
    return doProcessActionOrGroup(project, actionId, scope, EnumSet.of(RegistrationType.ACTION_ID), processor);
  }

  public static boolean processGroup(@NotNull Project project,
                                     @NotNull String actionGroupId,
                                     GlobalSearchScope scope,
                                     Processor<? super ActionOrGroup> processor) {
    return doProcessActionOrGroup(project, actionGroupId, scope, EnumSet.of(RegistrationType.ACTION_GROUP_ID), processor);
  }

  private static boolean doProcessActionOrGroup(@NotNull Project project,
                                                @NotNull String actionOrGroupId,
                                                GlobalSearchScope scope,
                                                EnumSet<RegistrationType> types,
                                                Processor<? super ActionOrGroup> processor) {
    List<XmlTag> tags = collectTags(project, actionOrGroupId, scope, types);

    return ContainerUtil.process(tags, tag -> {
      final DomElement domElement = DomManager.getDomManager(project).getDomElement(tag);

      if (!(domElement instanceof ActionOrGroup)) return true;
      return processor.process((ActionOrGroup)domElement);
    });
  }

  @NotNull
  private static List<XmlTag> collectTags(@NotNull Project project,
                                          @NotNull String key,
                                          GlobalSearchScope scope,
                                          EnumSet<RegistrationType> types) {
    List<XmlTag> tags = new SmartList<>();
    FileBasedIndex.getInstance().processValues(NAME, key, null, (file, value) -> {
      for (RegistrationEntry entry : value) {
        if (!types.contains(entry.getRegistrationType())) {
          continue;
        }

        final PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
        if (!(psiFile instanceof XmlFile)) continue;

        PsiElement psiElement = psiFile.findElementAt(entry.getOffset());
        XmlTag xmlTag = PsiTreeUtil.getParentOfType(psiElement, XmlTag.class, false);
        tags.add(xmlTag);
      }
      return true;
    }, scope);
    return tags;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yargon.Parsing;

namespace Yargon.Parser
{
    /// <summary>
    /// Extension methods for the <see cref="IParseTreeBuilder{TToken,TTree}"/> interface.
    /// </summary>
    public static class ParseTreeUtils
    {
        /// <summary>
        /// Merges alternatives into a new parse tree node.
        /// </summary>
        /// <typeparam name="TToken">The type of tokens.</typeparam>
        /// <typeparam name="TTree">The type of tree.</typeparam>
        /// <param name="parseTreeBuilder">The parse tree builder.</param>
        /// <param name="alternatives">The alternatives to merge.</param>
        /// <returns>The merged alternatives.</returns>
        public static TTree Merge<TToken, TTree>(this IParseTreeBuilder<TToken, TTree> parseTreeBuilder,
            IReadOnlyCollection<TTree> alternatives)
            where TToken : IToken
        {
            #region Contract
            if (parseTreeBuilder == null)
                throw new ArgumentNullException(nameof(parseTreeBuilder));
            if (alternatives == null)
                throw new ArgumentNullException(nameof(alternatives));
            if (alternatives.Count == 0)
                throw new ArgumentException("There must be at least one alternative.", nameof(alternatives));
            #endregion

            if (alternatives.Count == 1)
            {
                return alternatives.Single();
            }
            else if (alternatives.Count > 1)
            {
                return parseTreeBuilder.BuildAmbiguity(alternatives);
            }
            else
                throw new InvalidOperationException();
        }
    }
}


text:
#pragma strict

public var requireKey : boolean;                    // Whether or not a key is required.
public var doorSwishClip : AudioClip;               // Clip to play when the doors open or close.
public var accessDeniedClip : AudioClip;            // Clip to play when the player doesn't have the key for the door.

private var anim : Animator;                        // Reference to the animator component.
private var hash : HashIDs;                     // Reference to the HashIDs script.
private var player : GameObject;                    // Reference to the player GameObject.
private var playerInventory : PlayerInventory;  // Reference to the PlayerInventory script.
private var count : int;                            // The number of colliders present that should open the doors.

function Awake ()
{
    // Setting up the references.
    anim = GetComponent(Animator);
    hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(HashIDs);
    player = GameObject.FindGameObjectWithTag(Tags.player);
    playerInventory = player.GetComponent(PlayerInventory);
}

function OnTriggerEnter (other : Collider)
{
    // If the triggering gameobject is the player...
    if(other.gameObject == player)
    {
        // ... if this door requires a key...
        if(requireKey)
        {
            // ... if the player has the key...
            if(playerInventory.hasKey)
                // ... increase the count of triggering objects.
                count++;
            else
            {
                // If the player doesn't have the key play the access denied audio clip.
                audio.clip = accessDeniedClip;
                audio.Play();
            }
        }
        else
            // If the door doesn't require a key, increase the count of triggering objects.
            count++;
    }
    // If the triggering gameobject is an enemy...
    else if(other.gameObject.tag == Tags.enemy)
    {
        // ... if the triggering collider is a capsule collider...
        if(typeof(other) == CapsuleCollider)
            // ... increase the count of triggering objects.
            count++;
    }
}

function OnTriggerExit (other : Collider)
{
    // If the leaving gameobject is the player or an enemy and the collider is a capsule collider...
    if(other.gameObject == player || (other.gameObject.tag == Tags.enemy && typeof(other) == CapsuleCollider))
        // decrease the count of triggering objects.
        count = Mathf.Max(0, count-1);
}

function Update ()
{
    // Set the open parameter.
    anim.SetBool(hash.openBool,count > 0);

    // If the door is opening or closing...
    if(anim.IsInTransition(0) && !audio.isPlaying)
    {
        // ... play the door swish audio clip.
        audio.clip = doorSwishClip;
        audio.Play();
    }
}


text:
function my_func(number, string) {
}


text:
package goriak

import (
	riak "github.com/basho/riak-go-client"

	"crypto/tls"
	"crypto/x509"
	"errors"
	"io/ioutil"
	"strconv"
	"strings"
)

// Session holds the connection to Riak
type Session struct {
	riak *riak.Cluster
	opts ConnectOpts
}

// ConnectOpts are the available options for connecting to your Riak instance
type ConnectOpts struct {
	// Both Address and Addresses should be on the form HOST|IP[:PORT]
	Address   string   // Address to a single Riak host. Will be used in case Addresses is empty
	Addresses []string // Addresses to all Riak hosts.

	// Username and password for connection to servers with secirity enabled
	User     string
	Password string

	// Path to root CA certificate. Required if security is used
	CARootCert string

	// Option to override port. Is set to 8087 by default
	Port uint32
}

// Connect creates a new Riak connection. See ConnectOpts for the available options.
func Connect(opts ConnectOpts) (*Session, error) {
	client := Session{
		opts: opts,
	}

	err := client.connect()

	if err != nil {
		return nil, err
	}

	return &client, nil
}

func (c *Session) connect() error {
	if len(c.opts.Addresses) == 0 {
		c.opts.Addresses = []string{c.opts.Address}
	}

	var authOptions *riak.AuthOptions

	// Build auth options
	if c.opts.User != "" {
		rootCertPemData, err := ioutil.ReadFile(c.opts.CARootCert)
		if err != nil {
			return errors.New("Opening CARootCert: " + err.Error())
		}

		rootCertPool := x509.NewCertPool()
		if !rootCertPool.AppendCertsFromPEM(rootCertPemData) {
			return errors.New("Invalid PEM certificate file")
		}

		tlsConf := &tls.Config{
			InsecureSkipVerify: true,
			RootCAs:            rootCertPool,
		}

		authOptions = &riak.AuthOptions{
			User:      c.opts.User,
			Password:  c.opts.Password,
			TlsConfig: tlsConf,
		}
	}

	var nodes []*riak.Node

	// Set to default port if not provided
	port := c.opts.Port
	if port == 0 {
		port = 8087
	}

	for _, address := range c.opts.Addresses {
		if !strings.Contains(address, ":") {
			// Add port if not set in the user config
			address = address + ":" + strconv.FormatUint(uint64(port), 10)
		}

		// Set ServerName based on the address we're connecting to
		if authOptions != nil {
			addressWithoutPort := address[0:strings.Index(address, ":")]
			authOptions.TlsConfig.ServerName = addressWithoutPort
		}

		node, err := riak.NewNode(&riak.NodeOptions{
			RemoteAddress: address,
			AuthOptions:   authOptions,
		})
		if err != nil {
			return err
		}

		nodes = append(nodes, node)
	}

	con, err := riak.NewCluster(&riak.ClusterOptions{
		Nodes: nodes,
	})
	if err != nil {
		return err
	}

	err = con.Start()
	if err != nil {
		return err
	}

	c.riak = con

	return nil
}


text:
package swift.crdt;

import java.util.Set;

import swift.clocks.TripleTimestamp;
import swift.crdt.core.CRDTUpdate;

public class AddWinsSetRemoveUpdate<V, T extends AbstractAddWinsSetCRDT<V, T>> implements CRDTUpdate<T> {
    private V val;
    // WISHME: represent it more efficiently using vectors if possible.
    // That would require some substantial API chances, since it's not as easy
    // as using dependenceClock (for example, it can be overapproximated), there
    // are holes in here as well.
    private Set<TripleTimestamp> removedInstances;

    // required for kryo
    public AddWinsSetRemoveUpdate() {
    }

    public AddWinsSetRemoveUpdate(V val, Set<TripleTimestamp> ids) {
        this.val = val;
        this.removedInstances = ids;
    }

    public V getVal() {
        return this.val;
    }

    public Set<TripleTimestamp> getIds() {
        return this.removedInstances;
    }

    @Override
    public void applyTo(T crdt) {
        crdt.applyRemove(val, removedInstances);
    }

    @Override
    public Object getValueWithoutMetadata() {
        return val;
    }
}