text:
"""
Standard container-class for easy multiple-inheritance.
Try to inherit from the ndarray instead of using this class as this is not
complete.
"""

from numpy.core import array, asarray, absolute, add, subtract, multiply, \
     divide, remainder, power, left_shift, right_shift, bitwise_and, \
     bitwise_or, bitwise_xor, invert, less, less_equal, not_equal, equal, \
     greater, greater_equal, shape, reshape, arange, sin, sqrt, transpose

class container(object):
    def __init__(self, data, dtype=None, copy=True):
        self.array = array(data, dtype, copy=copy)

    def __repr__(self):
        if len(self.shape) > 0:
            return self.__class__.__name__+repr(self.array)[len("array"):]
        else:
            return self.__class__.__name__+"("+repr(self.array)+")"

    def __array__(self,t=None):
        if t: return self.array.astype(t)
        return self.array

    # Array as sequence
    def __len__(self): return len(self.array)

    def __getitem__(self, index):
        return self._rc(self.array[index])

    def __getslice__(self, i, j):
        return self._rc(self.array[i:j])

    def __setitem__(self, index, value):
        self.array[index] = asarray(value,self.dtype)
    def __setslice__(self, i, j, value):
        self.array[i:j] = asarray(value,self.dtype)

    def __abs__(self):
        return self._rc(absolute(self.array))
    def __neg__(self):
        return self._rc(-self.array)

    def __add__(self, other):
        return self._rc(self.array+asarray(other))
    __radd__ = __add__

    def __iadd__(self, other):
        add(self.array, other, self.array)
        return self

    def __sub__(self, other):
        return self._rc(self.array-asarray(other))
    def __rsub__(self, other):
        return self._rc(asarray(other)-self.array)
    def __isub__(self, other):
        subtract(self.array, other, self.array)
        return self

    def __mul__(self, other):
        return self._rc(multiply(self.array,asarray(other)))
    __rmul__ = __mul__
    def __imul__(self, other):
        multiply(self.array, other, self.array)
        return self

    def __div__(self, other):
        return self._rc(divide(self.array,asarray(other)))
    def __rdiv__(self, other):
        return self._rc(divide(asarray(other),self.array))
    def __idiv__(self, other):
        divide(self.array, other, self.array)
        return self

    def __mod__(self, other):
        return self._rc(remainder(self.array, other))
    def __rmod__(self, other):
        return self._rc(remainder(other, self.array))
    def __imod__(self, other):
        remainder(self.array, other, self.array)
        return self

    def __divmod__(self, other):
        return (self._rc(divide(self.array,other)),
                self._rc(remainder(self.array, other)))
    def __rdivmod__(self, other):
        return (self._rc(divide(other, self.array)),
                self._rc(remainder(other, self.array)))

    def __pow__(self,other):
        return self._rc(power(self.array,asarray(other)))
    def __rpow__(self,other):
        return self._rc(power(asarray(other),self.array))
    def __ipow__(self,other):
        power(self.array, other, self.array)
        return self

    def __lshift__(self,other):
        return self._rc(left_shift(self.array, other))
    def __rshift__(self,other):
        return self._rc(right_shift(self.array, other))
    def __rlshift__(self,other):
        return self._rc(left_shift(other, self.array))
    def __rrshift__(self,other):
        return self._rc(right_shift(other, self.array))
    def __ilshift__(self,other):
        left_shift(self.array, other, self.array)
        return self
    def __irshift__(self,other):
        right_shift(self.array, other, self.array)
        return self

    def __and__(self, other):
        return self._rc(bitwise_and(self.array, other))
    def __rand__(self, other):
        return self._rc(bitwise_and(other, self.array))
    def __iand__(self, other):
        bitwise_and(self.array, other, self.array)
        return self

    def __xor__(self, other):
        return self._rc(bitwise_xor(self.array, other))
    def __rxor__(self, other):
        return self._rc(bitwise_xor(other, self.array))
    def __ixor__(self, other):
        bitwise_xor(self.array, other, self.array)
        return self

    def __or__(self, other):
        return self._rc(bitwise_or(self.array, other))
    def __ror__(self, other):
        return self._rc(bitwise_or(other, self.array))
    def __ior__(self, other):
        bitwise_or(self.array, other, self.array)
        return self

    def __neg__(self):
        return self._rc(-self.array)
    def __pos__(self):
        return self._rc(self.array)
    def __abs__(self):
        return self._rc(abs(self.array))
    def __invert__(self):
        return self._rc(invert(self.array))

    def _scalarfunc(self, func):
        if len(self.shape) == 0:
            return func(self[0])
        else:
            raise TypeError, "only rank-0 arrays can be converted to Python scalars."

    def __complex__(self): return self._scalarfunc(complex)
    def __float__(self): return self._scalarfunc(float)
    def __int__(self): return self._scalarfunc(int)
    def __long__(self): return self._scalarfunc(long)
    def __hex__(self): return self._scalarfunc(hex)
    def __oct__(self): return self._scalarfunc(oct)

    def __lt__(self,other): return self._rc(less(self.array,other))
    def __le__(self,other): return self._rc(less_equal(self.array,other))
    def __eq__(self,other): return self._rc(equal(self.array,other))
    def __ne__(self,other): return self._rc(not_equal(self.array,other))
    def __gt__(self,other): return self._rc(greater(self.array,other))
    def __ge__(self,other): return self._rc(greater_equal(self.array,other))

    def copy(self): return self._rc(self.array.copy())

    def tostring(self): return self.array.tostring()

    def byteswap(self): return self._rc(self.array.byteswap())

    def astype(self, typecode): return self._rc(self.array.astype(typecode))

    def _rc(self, a):
        if len(shape(a)) == 0: return a
        else: return self.__class__(a)

    def __array_wrap__(self, *args):
        return self.__class__(args[0])

    def __setattr__(self,attr,value):
        if attr == 'array':
            object.__setattr__(self, attr, value)
            return
        try:
            self.array.__setattr__(attr, value)
        except AttributeError:
            object.__setattr__(self, attr, value)

    # Only called after other approaches fail.
    def __getattr__(self,attr):
        if (attr == 'array'):
            return object.__getattribute__(self, attr)
        return self.array.__getattribute__(attr)

#############################################################
# Test of class container
#############################################################
if __name__ == '__main__':
    temp=reshape(arange(10000),(100,100))

    ua=container(temp)
    # new object created begin test
    print dir(ua)
    print shape(ua),ua.shape # I have changed Numeric.py

    ua_small=ua[:3,:5]
    print ua_small
    ua_small[0,0]=10  # this did not change ua[0,0], which is not normal behavior
    print ua_small[0,0],ua[0,0]
    print sin(ua_small)/3.*6.+sqrt(ua_small**2)
    print less(ua_small,103),type(less(ua_small,103))
    print type(ua_small*reshape(arange(15),shape(ua_small)))
    print reshape(ua_small,(5,3))
    print transpose(ua_small)


text:
/*!
	@file
	@author		Albert Semenov
	@date		09/2010
*/
#include "Precompiled.h"
#include "ColourManager.h"
#include "CommandManager.h"
#include "SettingsManager.h"

template <> tools::ColourManager* MyGUI::Singleton<tools::ColourManager>::msInstance = nullptr;
template <> const char* MyGUI::Singleton<tools::ColourManager>::mClassTypeName("ColourManager");

namespace tools
{

	ColourManager::ColourManager() :
		mColourPanel(nullptr)
	{
		CommandManager::getInstance().registerCommand("Command_ChangeColourBackground", MyGUI::newDelegate(this, &ColourManager::commandChangeColourBackground));
		CommandManager::getInstance().registerCommand("Command_ChangeColourSelector", MyGUI::newDelegate(this, &ColourManager::commandChangeColourSelector));
		CommandManager::getInstance().registerCommand("Command_ChangeColourSelectorInactive", MyGUI::newDelegate(this, &ColourManager::commandChangeColourSelectorInactive));
	}

	ColourManager::~ColourManager()
	{
	}

	void ColourManager::initialise()
	{
		mColourPanel = new ColourPanel();
		mColourPanel->eventEndDialog = MyGUI::newDelegate(this, &ColourManager::notifyEndDialog);
		mColourPanel->eventPreviewColour = MyGUI::newDelegate(this, &ColourManager::notifyPreviewColour);
	}

	void ColourManager::shutdown()
	{
		delete mColourPanel;
		mColourPanel = nullptr;
	}

	void ColourManager::commandChangeColourBackground(const MyGUI::UString& _commandName, bool& _result)
	{
		mCurrentColourType = "ColourBackground";
		showColourDialog();

		_result = true;
	}

	void ColourManager::commandChangeColourSelector(const MyGUI::UString& _commandName, bool& _result)
	{
		mCurrentColourType = "ColourSelector";
		showColourDialog();

		_result = true;
	}

	void ColourManager::commandChangeColourSelectorInactive(const MyGUI::UString& _commandName, bool& _result)
	{
		mCurrentColourType = "ColourSelectorInactive";
		showColourDialog();

		_result = true;
	}

	void ColourManager::notifyEndDialog(Dialog* _sender, bool _result)
	{
		mColourPanel->endModal();

		if (_result)
			setColour(mColourPanel->getColour());
		else
			setColour(mPreviewColour);
	}

	void ColourManager::notifyPreviewColour(const MyGUI::Colour& _value)
	{
		setColour(_value);
	}

	void ColourManager::showColourDialog()
	{
		mPreviewColour = getColour();
		mColourPanel->setColour(mPreviewColour);
		mColourPanel->doModal();
	}

	void ColourManager::setColour(const MyGUI::Colour& _color)
	{
		SettingsManager::getInstance().getSector("Settings")->setPropertyValue(mCurrentColourType, _color);
	}

	MyGUI::Colour ColourManager::getColour()
	{
		return SettingsManager::getInstance().getSector("Settings")->getPropertyValue<MyGUI::Colour>(mCurrentColourType);
	}

} // namespace tools

redpajama_set_name: RedPajamaGithub


text:
@implementation AWFTableViewObservationRowCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
	self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
	AWFStyledHeaderView *headerView = [AWFStyledHeaderView new];
	headerView.translatesAutoresizingMaskIntoConstraints = NO;
	headerView.layout = AWFLayoutVertical;
	[self.contentView addSubview:headerView];
	self.headerView = headerView;

	// weather
	UIImageView *iconView = [UIImageView new];
	iconView.translatesAutoresizingMaskIntoConstraints = NO;
	iconView.contentMode = UIViewContentModeScaleAspectFit;
	[self.contentView addSubview:iconView];
	self.iconImageView = iconView;

	UILabel *weatherLabel = [UILabel new];
	weatherLabel.translatesAutoresizingMaskIntoConstraints = NO;
	weatherLabel.font = [UIFont systemFontOfSize:11.0];
	weatherLabel.textColor = [UIColor lightGrayColor];
	weatherLabel.textAlignment = NSTextAlignmentLeft;
	weatherLabel.minimumScaleFactor = 0.8;
	weatherLabel.numberOfLines = 3;
	weatherLabel.lineBreakMode = NSLineBreakByWordWrapping;
	weatherLabel.backgroundColor = [UIColor clearColor];
	weatherLabel.text = @"--";
	[self.contentView addSubview:weatherLabel];
	self.weatherTextLabel = weatherLabel;

	UILabel *tempLabel = [UILabel new];
	tempLabel.translatesAutoresizingMaskIntoConstraints = NO;
	tempLabel.font = [UIFont systemFontOfSize:34.0];
	tempLabel.textColor = [UIColor whiteColor];
	tempLabel.textAlignment = NSTextAlignmentRight;
	tempLabel.backgroundColor = [UIColor clearColor];
	tempLabel.text = @"--";
	[self.contentView addSubview:tempLabel];
	self.tempTextLabel = tempLabel;

	// layout
	UILayoutGuide *layoutGuides = self.contentView.layoutMarginsGuide;
	[NSLayoutConstraint activateConstraints:@[[headerView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor],
											  [headerView.leftAnchor constraintEqualToAnchor:self.contentView.leftAnchor],
											  [headerView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor],
											  [headerView.widthAnchor constraintEqualToConstant:75.0],
											  [iconView.centerYAnchor constraintEqualToAnchor:layoutGuides.centerYAnchor],
											  [iconView.leftAnchor constraintEqualToAnchor:headerView.rightAnchor constant:10.0],
											  [iconView.widthAnchor constraintEqualToConstant:45.0],
											  [iconView.heightAnchor constraintEqualToConstant:45.0],
											  [tempLabel.centerYAnchor constraintEqualToAnchor:layoutGuides.centerYAnchor],
											  [tempLabel.rightAnchor constraintEqualToAnchor:layoutGuides.rightAnchor constant:-10.0],
											  [weatherLabel.centerYAnchor constraintEqualToAnchor:layoutGuides.centerYAnchor],
											  [weatherLabel.leftAnchor constraintEqualToAnchor:iconView.rightAnchor constant:10.0],
											  [weatherLabel.rightAnchor constraintEqualToAnchor:tempLabel.leftAnchor constant:-10.0]]];
}

- (void)applyStyle:(AWFCascadingStyle *)style {
	[style.detailTextStyle applyToLabel:self.weatherTextLabel withFontSize:self.weatherTextLabel.font.pointSize];
	[style.defaultTextStyle applyToLabel:self.tempTextLabel withFontSize:self.tempTextLabel.font.pointSize];

	[self.headerView applyStyle:style];
}

@end


text:
ASGI
====

`ASGI <https://asgi.readthedocs.io>`_, or the
Asynchronous Server Gateway Interface, is the specification which
Channels and Daphne are built upon, designed to untie Channels apps from a
specific application server and provide a common way to write application
and middleware code.

It's a spiritual successor to WSGI, designed not only run in an asynchronous
fashion via ``asyncio``, but also supporting multiple protocols.

The full ASGI spec can be found at https://asgi.readthedocs.io

Summary
-------

ASGI is structured as a single asynchronous callable, which takes a dict ``scope``
and two callables ``receive`` and ``send``:

.. code-block:: python

    async def application(scope, receive, send):
        event = await receive()
        ...
        await send({"type": "websocket.send", ...})

The ``scope`` dict defines the properties of a connection, like its remote IP (for
HTTP) or username (for a chat protocol), and the lifetime of a connection.
Applications are *instantiated* once per scope - so, for example, once per
HTTP request, or once per open WebSocket connection.

Scopes always have a ``type`` key, which tells you what kind of connection
it is and what other keys to expect in the scope (and what sort of messages
to expect).

The ``receive`` awaitable provides events as dicts as they occur, and the
``send`` awaitable sends events back to the client in a similar dict format.

A *protocol server* sits between the client and your application code,
decoding the raw protocol into the scope and event dicts and encoding anything
you send back down onto the protocol.

Composability
-------------

ASGI applications, like WSGI ones, are designed to be composable, and this
includes Channels' routing and middleware components like ``ProtocolTypeRouter``
and ``SessionMiddleware``. These are just ASGI applications that take other
ASGI applications as arguments, so you can pass around just one top-level
application for a whole Django project and dispatch down to the right consumer
based on what sort of connection you're handling.

Protocol Specifications
-----------------------

The basic ASGI spec only outlines the interface for an ASGI app - it does not
specify how network protocols are encoded to and from scopes and event dicts.
That's the job of protocol specifications:

* HTTP and WebSocket: https://github.com/django/asgiref/blob/master/specs/www.rst


text:
import VectorLayer from 'ol/layer/Vector.js';
import {Circle, Fill, Icon, Stroke, Style} from 'ol/style.js';

function shouldShowVessel(vessel) {
    const now = new Date();
    return (now - vessel.lastUpdate) < 1000*60*30;
}

// Style for non-moving vessels.
const defaultVesselStyle = new Style({
    image: new Circle({
      radius: 6,
      fill: new Fill({color: 'rgba(255,255,255,0.4)'}),
      stroke: new Stroke({
        color: '#3399CC', width: 1.25
      })
    })
});

function getVesselStyle(feature, resolution) {
    const vessel = feature.get('data');

    if (!shouldShowVessel(vessel))
        return null;

    let heading = null;
    if ('heading' in vessel && vessel.heading != 511) {
        heading = vessel.heading;
    } else if ('course' in vessel) {
        heading = vessel.course;
    }
    if (heading == null)
        return defaultVesselStyle;

    heading = heading / 180 * Math.PI;
    let color = '#000000';
    if (vessel.shiptype >= 50 && vessel.shiptype < 60)
        color = '#ff9200';
    else if (vessel.shiptype >= 60 && vessel.shiptype < 70)
        color = '#0000ff';
    let scale = 0.3;
    if ('to_bow' in vessel && 'to_stern' in vessel) {
        let length = vessel.to_bow + vessel.to_stern;
        if (length > 40)
            scale = 0.35;
        if (length > 100)
            scale = 0.4;
        if (length > 200)
            scale = 0.45;
    }
    let opacity = 0.8;
    const now = new Date();
    if (now - vessel.lastUpdate > 1000*60*5)
        opacity = 0.5;
    else if (now - vessel.lastUpdate > 1000*60*10)
        opacity = 0.2;
    else if (now - vessel.lastUpdate > 1000*60*20)
        opacity = 0.1;
    return new Style({
        image: new Icon({
            src: "vessel2.png",
            scale: scale,
            rotation: heading,
            color: color,
            opacity: opacity
        })
    });
}

export default class VesselLayer extends VectorLayer {
    constructor(options) {
        super({style: getVesselStyle, ...options});
    }
};


text:
package biz.aQute.remote;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.osgi.framework.Constants;
import org.osgi.framework.dto.FrameworkDTO;

import aQute.lib.io.IO;
import aQute.remote.api.Agent;
import aQute.remote.main.Main;
import aQute.remote.plugin.LauncherSupervisor;
import junit.framework.TestCase;

/**
 * Start the main program which will wait for requests to create a framework.
 */
public class MainTest extends TestCase {

	private Thread thread;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		thread = new Thread() {
			@Override
			public void run() {
				try {
					Main.main(new String[] {
							"-p", Agent.DEFAULT_PORT + 1 + "", "-s", "generated/storage", "-c", "generated/cache", "-n",
							"*", "-et"
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		thread.setDaemon(true);
		thread.start();

	}

	@Override
	protected void tearDown() throws Exception {
		Main.stop();
		IO.delete(IO.getFile("generated/cache"));
		IO.delete(IO.getFile("generated/storage"));
		super.tearDown();
	}

	public void testRemoteMain() throws Exception {

		//
		// Create a framework & start an agent
		//

		LauncherSupervisor supervisor = new LauncherSupervisor();
		supervisor.connect("localhost", Agent.DEFAULT_PORT + 1);

		assertEquals("not talking to an envoy", true, supervisor.getAgent().isEnvoy());

		HashMap<String,Object> configuration = new HashMap<String,Object>();
		configuration.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
		configuration.put(Constants.FRAMEWORK_STORAGE, "generated/storage");
		List<String> emptyList = Collections.emptyList();
		boolean created = supervisor.getAgent().createFramework("test", emptyList, configuration);
		assertTrue("there already was a framework, funny, since we created the main in setUp?", created);

		FrameworkDTO framework = supervisor.getAgent().getFramework();
		assertNotNull("just created it, so we should have a framework", framework);

		//
		// Create a second supervisor and ensure we do not
		// kill the primary
		//

		LauncherSupervisor sv2 = new LauncherSupervisor();
		sv2.connect("localhost", Agent.DEFAULT_PORT + 1);

		assertTrue("no second framework", supervisor.getAgent().ping());

		assertEquals("must be an envoy", true, sv2.getAgent().isEnvoy());
		assertFalse("the framework should already exist",
				sv2.getAgent().createFramework("test", emptyList, configuration));

		assertTrue("first framework is gone", supervisor.getAgent().ping());

		FrameworkDTO fw2 = sv2.getAgent().getFramework();
		assertEquals("we should not have created a new framework", framework.properties.get("org.osgi.framework.uuid"),
				fw2.properties.get("org.osgi.framework.uuid"));

		//
		// Kill the second framework
		//

		supervisor.getAgent().abort();
		Thread.sleep(500);
		assertFalse(supervisor.isOpen());

		assertTrue("should not have killed sv2", sv2.getAgent().ping());

		sv2.abort();
		Thread.sleep(500);
		assertFalse(sv2.isOpen());
	}

}


text:
var electron = require("electron");
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;

var win = null;

app.on('ready', function() {
    win = new BrowserWindow({
        webPreferences: { nodeIntegration: true}
    });

    win.loadFile('index.html');
    win.on('closed', function() {
        win = null;
    });
});

app.on('window-all-closed', function() {
    app.quit();
});


text:
namespace app {
namespace Uno {

::uDelegateType* Action__Outracks_Simulator_Bytecode_BooleanLiteral__typeof();

}}

#endif


text:
package org.apache.flink.runtime.rest.handler.job.rescaling;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.handler.RestHandlerException;
import org.apache.flink.runtime.rest.handler.async.AbstractAsynchronousOperationHandlers;
import org.apache.flink.runtime.rest.handler.async.AsynchronousOperationInfo;
import org.apache.flink.runtime.rest.handler.async.AsynchronousOperationResult;
import org.apache.flink.runtime.rest.handler.async.TriggerResponse;
import org.apache.flink.runtime.rest.handler.job.AsynchronousJobOperationKey;
import org.apache.flink.runtime.rest.messages.EmptyRequestBody;
import org.apache.flink.runtime.webmonitor.RestfulGateway;
import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever;

import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus;

import javax.annotation.Nonnull;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Rest handler to trigger and poll the rescaling of a running job.
 */
public class RescalingHandlers extends AbstractAsynchronousOperationHandlers<AsynchronousJobOperationKey, Acknowledge> {

	private static RestHandlerException featureDisabledException() {
		return new RestHandlerException("Rescaling is temporarily disabled. See FLINK-12312.", HttpResponseStatus.SERVICE_UNAVAILABLE);
	}

	/**
	 * Handler which triggers the rescaling of the specified job.
	 */
	public class RescalingTriggerHandler extends TriggerHandler<RestfulGateway, EmptyRequestBody, RescalingTriggerMessageParameters> {

		public RescalingTriggerHandler(
				GatewayRetriever<? extends RestfulGateway> leaderRetriever,
				Time timeout,
				Map<String, String> responseHeaders) {
			super(
				leaderRetriever,
				timeout,
				responseHeaders,
				RescalingTriggerHeaders.getInstance());
		}

		@Override
		public CompletableFuture<TriggerResponse> handleRequest(@Nonnull final HandlerRequest<EmptyRequestBody, RescalingTriggerMessageParameters> request, @Nonnull final RestfulGateway gateway) throws RestHandlerException {
			throw featureDisabledException();
		}

		@Override
		protected CompletableFuture<Acknowledge> triggerOperation(HandlerRequest<EmptyRequestBody, RescalingTriggerMessageParameters> request, RestfulGateway gateway) {
			throw new UnsupportedOperationException();
		}

		@Override
		protected AsynchronousJobOperationKey createOperationKey(HandlerRequest<EmptyRequestBody, RescalingTriggerMessageParameters> request) {
			throw new UnsupportedOperationException();
		}
	}

	/**
	 * Handler which reports the status of the rescaling operation.
	 */
	public class RescalingStatusHandler extends StatusHandler<RestfulGateway, AsynchronousOperationInfo, RescalingStatusMessageParameters> {

		public RescalingStatusHandler(
			GatewayRetriever<? extends RestfulGateway> leaderRetriever,
			Time timeout,
			Map<String, String> responseHeaders) {
			super(
				leaderRetriever,
				timeout,
				responseHeaders,
				RescalingStatusHeaders.getInstance());
		}

		@Override
		public CompletableFuture<AsynchronousOperationResult<AsynchronousOperationInfo>> handleRequest(@Nonnull final HandlerRequest<EmptyRequestBody, RescalingStatusMessageParameters> request, @Nonnull final RestfulGateway gateway) throws RestHandlerException {
			throw featureDisabledException();
		}

		@Override
		protected AsynchronousJobOperationKey getOperationKey(HandlerRequest<EmptyRequestBody, RescalingStatusMessageParameters> request) {
			throw new UnsupportedOperationException();
		}

		@Override
		protected AsynchronousOperationInfo exceptionalOperationResultResponse(Throwable throwable) {
			throw new UnsupportedOperationException();
		}

		@Override
		protected AsynchronousOperationInfo operationResultResponse(Acknowledge operationResult) {
			throw new UnsupportedOperationException();
		}
	}
}


text:
package com.deltadna.android.sdk.net;

import androidx.annotation.Nullable;
import android.util.Log;
import com.deltadna.android.sdk.BuildConfig;
import com.deltadna.android.sdk.DDNA;
import com.deltadna.android.sdk.consent.ConsentStatus;
import com.deltadna.android.sdk.helpers.Settings;
import com.deltadna.android.sdk.listeners.RequestListener;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 * TODO make package private after ads decoupling
 * TODO collapse functionality into event dispatcher
 */
public class NetworkManager {

    private static final String TAG = BuildConfig.LOG_TAG
            + ' '
            + NetworkManager.class.getSimpleName();

    private final String collectUrl;
    private final String engageUrl;
    private final Settings settings;

    @Nullable
    private final String hash;
    @Nullable
    private final MessageDigest md5;

    private final NetworkDispatcher dispatcher;

    public NetworkManager(
            String envKey,
            String collectUrl,
            String engageUrl,
            Settings settings,
            @Nullable String hash) {

        this.collectUrl = collectUrl + '/' + envKey;
        this.engageUrl = engageUrl + '/' + envKey;
        this.settings = settings;

        this.hash = hash;
        MessageDigest md = null;
        if (hash != null && !hash.isEmpty()) {
            try {
                md = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                Log.w(TAG, "Events will not be hashed", e);
            }
        }
        md5 = md;

        dispatcher = new NetworkDispatcher();
    }

    public CancelableRequest get(String url, @Nullable RequestListener<JSONObject> listener) {
        Request<JSONObject> request = new Request.Builder<JSONObject>()
                .get()
                .url(url)
                .maxRetries(settings.getHttpRequestMaxRetries())
                .retryDelay(settings.getHttpRequestRetryDelay() * 1000)
                .build();
        return dispatcher.enqueue(request, ResponseBodyConverter.JSON, listener);
    }

    public CancelableRequest collect(
            JSONObject payload,
            @Nullable RequestListener<Void> listener) {

        Request.Builder<Void> builder = new Request.Builder<Void>()
                .post(RequestBody.json(payload))
                .url(payload.has("eventList")
                        ? buildHashedEndpoint(collectUrl + "/bulk", payload.toString())
                        : buildHashedEndpoint(collectUrl, payload.toString()))
                .header("Accept", "application/json")
                .maxRetries(settings.getHttpRequestMaxRetries())
                .retryDelay(settings.getHttpRequestRetryDelay() * 1000)
                .connectionTimeout(settings.getHttpRequestCollectTimeout() * 1000);

        addPIPLHeadersToRequest(builder);

        return dispatcher.enqueue(builder.build(), listener);
    }

    public CancelableRequest engage(
            JSONObject payload,
            RequestListener<JSONObject> listener) {

        // TODO tweak timeouts to make engage come back within the magic 5s
        return engage(payload, listener, false);
    }

    public CancelableRequest engage(JSONObject payload,
                                    RequestListener<JSONObject> listener,
                                    boolean isConfigurationRequest){
        int timeoutInSeconds = isConfigurationRequest ? settings.getHttpRequestConfigTimeout() : settings.getHttpRequestEngageTimeout();

        Request.Builder<JSONObject> builder = new Request.Builder<JSONObject>()
                .post(RequestBody.json(payload))
                .url(buildHashedEndpoint(engageUrl, payload.toString()))
                .header("Accept", "application/json")
                .connectionTimeout(timeoutInSeconds * 1000);

        addPIPLHeadersToRequest(builder);

        return dispatcher.enqueue(
                builder.build(),
                ResponseBodyConverter.JSON,
                listener);
    }

    public CancelableRequest fetch(
            String url,
            final File dest,
            RequestListener<File> listener) {

        Request.Builder<File> builder = new Request.Builder<File>()
                .get()
                .url(url)
                .connectionTimeout(settings.getHttpRequestEngageTimeout() * 1000);

        addPIPLHeadersToRequest(builder);

        // TODO tweak timeouts as this should come back quickly as well
        return dispatcher.enqueue(
                builder.build(),
                new ResponseBodyConverter<File>() {
                    @Override
                    public File convert(byte[] input) throws Exception {
                        final FileOutputStream os = new FileOutputStream(dest);
                        os.write(input);
                        os.close();

                        return dest;
                    }
                },
                listener);
    }

    private String buildHashedEndpoint(String endpoint, String payload) {
        final StringBuilder builder = new StringBuilder(endpoint);

        if (hash != null && md5 != null) {
            builder.append("/hash/");

            final byte[] messageBytes;
            try {
                messageBytes = (payload + hash).getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new IllegalStateException(e);
            }

            final byte[] digest = md5.digest(messageBytes);
            for (final byte b : digest) {
                builder.append(String.format(Locale.US, "%02X", b));
            }
        }

        return builder.toString();
    }

    private void addPIPLHeadersToRequest(Request.Builder requestBuilder) {
        if (DDNA.instance().consentTracker.useConsentStatus == ConsentStatus.consentGiven) {
            requestBuilder.header("PIPL_CONSENT", "");
        }
        if (DDNA.instance().consentTracker.exportConsentStatus == ConsentStatus.consentGiven) {
            requestBuilder.header("PIPL_EXPORT", "");
        }
    }
}


text:
package us.kbase.fbatools;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 *
Original spec-file type: MergeMetabolicModelsIntoCommunityModelResults

 *
 *
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
    "new_fbamodel_ref"
})
public class MergeMetabolicModelsIntoCommunityModelResults {

    @JsonProperty("new_fbamodel_ref")
    private String newFbamodelRef;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("new_fbamodel_ref")
    public String getNewFbamodelRef() {
        return newFbamodelRef;
    }

    @JsonProperty("new_fbamodel_ref")
    public void setNewFbamodelRef(String newFbamodelRef) {
        this.newFbamodelRef = newFbamodelRef;
    }

    public MergeMetabolicModelsIntoCommunityModelResults withNewFbamodelRef(String newFbamodelRef) {
        this.newFbamodelRef = newFbamodelRef;
        return this;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperties(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    @Override
    public String toString() {
        return ((((("MergeMetabolicModelsIntoCommunityModelResults"+" [newFbamodelRef=")+ newFbamodelRef)+", additionalProperties=")+ additionalProperties)+"]");
    }

}


text: mvn clean install -pl :ui -Ptype-subtype-value,quick $@


text:
'''
osquery wrapper for HubbleStack Nebula

:maintainer: basepi
:maturity: 2016.10.2
:platform: All
:requires: SaltStack, osquery

Designed to run sets of osquery queries defined in pillar. These sets will have
a unique identifier, and be targeted by identifier. Usually, this identifier
will be a frequency. ('15 minutes', '1 day', etc). Identifiers are
case-insensitive.

You can then use the scheduler of your choice to run sets os queries at
whatever frequency you choose.

Sample pillar data:

nebula_osquery:
  hour:
    - crontab: query: select c.*,t.iso_8601 as _time from crontab as c join time as t;
    - query_name: suid_binaries
      query: select sb.*, t.iso_8601 as _time from suid_bin as sb join time as t;
  day:
    - query_name: rpm_packages
      query: select rpm.*, t.iso_8601 from rpm_packages as rpm join time as t;
'''
from __future__ import absolute_import

import copy
import json
import logging
import os
import sys
import yaml

import salt.utils
from salt.exceptions import CommandExecutionError

log = logging.getLogger(__name__)

__version__ = 'v2017.4.1'
__virtualname__ = 'nebula'

def __virtual__():
    return __virtualname__

def queries(query_group,
            query_file=None,
            verbose=False,
            report_version_with_day=True):
    '''
    Run the set of queries represented by ``query_group`` from the
    configuration in the file query_file

    query_group
        Group of queries to run

    query_file
        salt:// file which will be parsed for osquery queries

    verbose
        Defaults to False. If set to True, more information (such as the query
        which was run) will be included in the result.

    CLI Examples:

    .. code_block:: bash

        salt '*' nebula.queries day
        salt '*' nebula.queries hour verbose=True
        salt '*' nebula.queries hour pillar_key=sec_osqueries
    '''
    MAX_FILE_SIZE = 104857600
    if query_file is None:
        if salt.utils.is_windows():
            query_file = 'salt://hubblestack_nebula/hubblestack_nebula_win_queries.yaml'
        else:
            query_file = 'salt://hubblestack_nebula/hubblestack_nebula_queries.yaml'
    if not salt.utils.which('osqueryi'):
        if query_group == 'day':
            log.warning('osquery not installed on this host. Returning baseline data')
            # Match the formatting of normal osquery results. Not super
            #   readable, but just add new dictionaries to the list as we need
            #   more data
            ret = []
            ret.append(
                    {'fallback_osfinger': {
                         'data': [{'osfinger': __grains__.get('osfinger', __grains__.get('osfullname')),
                                   'osrelease': __grains__.get('osrelease', __grains__.get('lsb_distrib_release'))}],
                         'result': True
                    }}
            )
            if 'pkg.list_pkgs' in __salt__:
                ret.append(
                        {'fallback_pkgs': {
                             'data': [{'name': k, 'version': v} for k, v in __salt__['pkg.list_pkgs']().iteritems()],
                             'result': True
                        }}
                )
            uptime = __salt__['status.uptime']()
            if isinstance(uptime, dict):
                uptime = uptime.get('seconds', __salt__['cmd.run']('uptime'))
            ret.append(
                    {'fallback_uptime': {
                         'data': [{'uptime': uptime}],
                         'result': True
                    }}
            )
            if report_version_with_day:
                ret.append(hubble_versions())
            return ret
        else:
            log.debug('osquery not installed on this host. Skipping.')
            return None

    if salt.utils.is_windows():
        win_version = __grains__['osfullname']
        if '2008' not in win_version and '2012' not in win_version and '2016' not in win_version:
            log.error('osquery does not run on windows versions earlier than Server 2008 and Windows 7')
            if query_group == 'day':
                ret = []
                ret.append(
                        {'fallback_osfinger': {
                             'data': [{'osfinger': __grains__.get('osfinger', __grains__.get('osfullname'))}],
                             'result': True
                        }}
                )
                ret.append(
                        {'fallback_error': {
                             'data': 'osqueryi is installed but not compatible with this version of windows',
                             'result': True
                        }}
                )
                return ret
            else:
               return None

    orig_filename = query_file
    query_file = __salt__['cp.cache_file'](query_file)
    if query_file is None:
        log.error('Could not find file {0}.'.format(orig_filename))
        return None
    with open(query_file, 'r') as fh:
        query_data = yaml.safe_load(fh)

    if not isinstance(query_data, dict):
        raise CommandExecutionError('Query data is not formed as a dict {0}'
                                    .format(query_data))

    query_data = query_data.get(query_group, [])

    if not query_data:
        return None

    ret = []
    for query in query_data:
        name = query.get('query_name')
        query_sql = query.get('query')
        if not query_sql:
            continue

        # Run the osqueryi query
        query_ret = {
            'result': True,
        }

        cmd = ['osqueryi', '--read_max', MAX_FILE_SIZE, '--read_user_max', MAX_FILE_SIZE, '--json', query_sql]
        res = __salt__['cmd.run_all'](cmd)
        if res['retcode'] == 0:
            query_ret['data'] = json.loads(res['stdout'])
        else:
            queury_ret['result'] = False
            queury_ret['error'] = res['stderr']

        if verbose:
            tmp = copy.deepcopy(query)
            tmp['query_result'] = query_ret
            ret.append(tmp)
        else:
            ret.append({name: query_ret})

    if query_group == 'day' and report_version_with_day:
        ret.append(hubble_versions())

    return ret

def version():
    '''
    Report version of this module
    '''
    return __version__

def hubble_versions():
    '''
    Report version of all hubble modules as query
    '''
    versions = {}

    # Nova
    if 'hubble.version' in __salt__:
        versions['nova'] = __salt__['hubble.version']()
    else:
        versions['nova'] = None

    # Nebula
    versions['nebula'] = version()

    # Pulsar
    if salt.utils.is_windows():
        try:
            sys.path.insert(0, os.path.dirname(__salt__['cp.cache_file']('salt://_beacons/win_pulsar.py')))
            import win_pulsar
            versions['pulsar'] = win_pulsar.__version__
        except:
            versions['pulsar'] = None
    else:
        try:
            sys.path.insert(0, os.path.dirname(__salt__['cp.cache_file']('salt://_beacons/pulsar.py')))
            import pulsar
            versions['pulsar'] = pulsar.__version__
        except:
            versions['pulsar'] = None

    # Quasar
    try:
        sys.path.insert(0, os.path.dirname(__salt__['cp.cache_file']('salt://_returners/splunk_nova_return.py')))
        import splunk_nova_return
        versions['quasar'] = splunk_nova_return.__version__
    except:
        versions['quasar'] = None

    return {'hubble_versions': {'data': [versions],
                                'result': True}}


text:
class TokyoMetro::App::Renderer::Concerns::Link::Normal::MetaClass < TokyoMetro::Factory::Decorate::MetaClass

  ICON_SIZE = 1

  def initialize( request , title_ja , title_en , url , icon_name: nil , class_name_of_whole_domain: nil , class_name_of_link: :link , class_name_of_div_domain: nil , open_another_window: false , size: :normal , additional_info: nil , additional_info_position: nil , link_to_another_website: false )
    super( request )

    raise "Error" if title_ja.blank? and title_en.blank?
    raise "Error" if class_name_of_div_domain.blank?

    raise "Error" if additional_info.present? and additional_info_position.blank?
    raise "Error" if additional_info.blank? and additional_info_position.present?

    raise "Error" if link_to_another_website and !( open_another_window )

    @title_ja = title_ja
    @title_en = title_en
    @url = url
    @icon_name = icon_name
    @class_name_of_whole_domain = class_name_of_whole_domain
    @class_name_of_link = class_name_of_link
    @class_name_of_div_domain = class_name_of_div_domain
    @open_another_window = open_another_window
    @size = size

    @additional_info = additional_info
    @additional_info_position = additional_info_position

    @link_to_another_website = link_to_another_website
  end

  def render
    _h_locals = h_locals
    h.render inline: <<-HAML , type: :haml , locals: _h_locals
%li{ class: [ li_class_name , :clearfix ].flatten }<
  = v.link_to_unless( link_to_current_page , "" , url , only_path_setting: false , class: class_name_of_link , target: target )
  %div{ class: [ class_name_of_div_domain , :clearfix ].flatten }<
    - # Icon
    %div{ class: :icon }
      - if icon_name.present?
        = ::TokyoMetro::App::Renderer::Icon.send( icon_name , request , icon_size ).render
      - else
        %div{ class: :icon_img }<

    - # Title
    - if title_ja.present? and title_en.present?
      - # Title (1)
      %div{ class: [ :text , :clearfix ] }
        - if title_ja.instance_of?( ::Array )
          %div{ class: :text_ja }<
            - title_ja.each do | row |
              %p<
                = row
        - else
          %p{ class: :text_ja }<
            = title_ja
        - if title_en.instance_of?( ::Array )
          %div{ class: :text_en }<
            - title_ja.each do | row |
              %p<
                = row
        - else
          %p{ class: :text_en }<
            = title_en
      - if additional_info.present?
        = additional_info.call
    - else
      - # Title (2)
      - div_classes = [ :text_large ]
      - if title_ja.present?
        - text = title_ja
        - div_classes << :text_ja
      - elsif title_en.present?
        - text = title_en
        - div_classes << :text_en
      %div{ class: div_classes }
        - if text.instance_of?( ::Array )
          - text.each do | row |
            %p<
              = row
        - else
          %p<
            = text
      - if additional_info.present?
        = additional_info.call
    - # External Link
    - if open_another_window
      - if link_to_another_website
        %div{ class: :link_to_another_website }
          = ::TokyoMetro::App::Renderer::Icon.link_to_another_website( request , 1 ).render
      - else
        %div{ class: :open_another_window }
          = ::TokyoMetro::App::Renderer::Icon.open_another_window( request , 1 ).render
    HAML
  end

  private

  def open_another_window?
    @open_another_window
  end

  def target
    if open_another_window?
      :_blank
    else
      nil
    end
  end

  def h_locals
    super.merge( {
      title_ja: @title_ja ,
      title_en: @title_en ,
      url: @url ,
      icon_name: @icon_name ,
      class_name_of_link: [ @class_name_of_link ].flatten.uniq.sort ,
      class_name_of_div_domain: @class_name_of_div_domain ,
      li_class_name: li_class_name ,
      target: target ,
      open_another_window: open_another_window? ,
      additional_info: @additional_info ,
      additional_info_position: @additional_info_position ,
      link_to_another_website: @link_to_another_website ,
      link_to_current_page: link_to_current_page? ,
      icon_size: ICON_SIZE
    } )
  end

  def li_class_name
    if @class_name_of_whole_domain.present?
      ary = [ @class_name_of_whole_domain , @size ].flatten
    else
      ary = [ @size ]
    end
    if link_for_page_on_the_same_category?
      ary << [ :same_category ]
    end
    ary
  end

  # def link_to_page_on_the_same_host?
    # @request.host == host_of( @url )
  # end

  def link_to_current_page?
    @request.fullpath == @url
  end

  def link_for_page_on_the_same_controller?
    current_page?( controller: controller_of( @url ) )
  end

  def link_for_page_on_the_same_category?
    !( @link_to_another_website ) and link_for_page_on_the_same_controller?
  end

  def link_for_page_of_the_same_action?
    current_page?( action: action_of( @url ) )
  end

end


text:
swoole_process: read
--SKIPIF--
<?php require __DIR__ . '/../include/skipif.inc'; ?>
--FILE--
<?php
require __DIR__ . '/../include/bootstrap.php';

$proc = new Swoole\Process(function(Swoole\Process $process) {
    $r = $process->write("SUCCESS");
    Assert::same($r, 7);
});
$r = $proc->start();
Assert::assert($r > 0);

Swoole\Timer::after(10, function() use($proc) {
    echo $proc->read();
    // Swoole\Event::exit();
});

\Swoole\Process::wait(true);
?>
--EXPECT--
SUCCESS


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>westion.www.listener</title>
<meta name="date" content="2014-04-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

westion.www.listener

Àà

ContextAndRequestListener


text:
require 'dfp_api'

API_VERSION = :v201408

def associate_creative_set_to_line_item()
  # Get DfpApi instance and load configuration from ~/dfp_api.yml.
  dfp = DfpApi::Api.new

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # dfp.logger = Logger.new('dfp_xml.log')

  # Set the line item ID and creative set ID to associate.
  line_item_id = 'INSERT_LINE_ITEM_ID_HERE'.to_i
  creative_set_id = 'INSERT_CREATIVE_SET_ID_HERE'.to_i

  # Get the LineItemCreativeAssociationService.
  lica_service = dfp.service(:LineItemCreativeAssociationService, API_VERSION)

  lica = {
    :creative_set_id => creative_set_id,
    :line_item_id => line_item_id
  }

  # Create the LICAs on the server.
  return_lica = lica_service.create_line_item_creative_associations([lica])

  puts 'A LICA with line item ID %d and creative set ID %d was created.' %
      [return_lica[:line_item_id], return_lica[:creative_set_id]]
end

if __FILE__ == $0
  begin
    associate_creative_set_to_line_item()

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts 'HTTP Error: %s' % e

  # API errors.
  rescue DfpApi::Errors::ApiException => e
    puts 'Message: %s' % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end


text:
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';

import { AppState } from './app.service';
import { Io, SocketRequest, SocketResponse } from './socket.service';

// Interfaces
import { User } from '../_interfaces/user.interface';

@Injectable()
export class UserService {
  private _users$: Subject<User[]>;
  private dataStore: {
    users: User[]
  };

  constructor(
    private _io: Io,
    private _appstate: AppState
  ) {
    this.dataStore = { users: [] };
    this._users$ = <Subject<User[]>>new Subject();
    window['user'] = this;
  }

  get todos$() {
    return this._users$.asObservable();
  }

  loadAll(debug:boolean=false) {
    let r = {
      debug:debug,
      url:'/users',
      params:{me:this._appstate.get('me').id}
    };
    this._io.request$(new SocketRequest(r))
    .map(res => new SocketResponse(res).body.data)
    .subscribe(
      data => {
        this.dataStore.users = data;
        this._users$.next(this.dataStore.users);
      }
    );
  }

  load(uid: string,debug:boolean=false) {
    let r = {
      debug:debug,
      url:`/users/${uid}`,
      params:{me:this._appstate.get('me').id}
    };
    this._io.request$(new SocketRequest(r))
      .map(res => new SocketResponse(res).body.data)
      .subscribe(
        data => {
          let notFound = true;

          this.dataStore.users.forEach((item, index) => {
            if (item.id === data.id) {
              this.dataStore.users[index] = data;
              notFound = false;
            }
          });
          if (notFound) {
            this.dataStore.users.push(data);
          }
          this._users$.next(this.dataStore.users);
        }
      );
  }

  create(user: User,debug:boolean=false) {
    return alert('not implemented');
    // let r = {
    //   debug:debug,
    //   url:`/rooms`,
    //   params:{me:this._appstate.get('me').id}
    // };
    // this._io.socket.post(`/rooms`, JSON.stringify(room))
    //   .map(response => response.json()).subscribe(data => {
    //     this.dataStore.rooms.push(data);
    //     this._rooms$.next(this.dataStore.rooms);
    //   }, error => console.log('Could not create room.'));
  }

  update(room: User,debug:boolean=false) {
    return alert('not implemented');
    // let r = {
    //   debug:debug,
    //   url:`/rooms/${room.uid}`,
    //   params:{me:this._appstate.get('me').id}
    // };
    // this._io.socket.put(`/rooms/${room.id}`, JSON.stringify(room))
    //   .map(response => response.json()).subscribe(data => {
    //     this.dataStore.rooms.forEach((todo, i) => {
    //       if (todo.id === data.id) { this.dataStore.rooms[i] = data; }
    //     });
    //
    //     this._rooms$.next(this.dataStore.rooms);
    //   }, error => console.log('Could not update room.'));
  }

  remove(roomId: number) {
    return alert('not implemented');
    // this._io.socket.delete(`/rooms/${roomId}`).subscribe(response => {
    //   this.dataStore.rooms.forEach((t, i) => {
    //     if (t.id === todoId) { this.dataStore.rooms.splice(i, 1); }
    //   });
    //
    //   this._rooms$.next(this.dataStore.rooms);
    // }, error => console.log('Could not delete room.'));
  }
}


text:
<?xml version="1.0" ?>

<container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://symfony.com/schema/dic/services"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <!-- Event Subscriber -->
        <service id="neti_tool_kit.subscriber.global_data" class="NetiToolKit\Subscriber\GlobalData">
            <argument type="service" id="neti_foundation.plugin_manager_config"/>
            <argument type="service" id="neti_foundation.session"/>
            <argument type="service" id="models"/>
            <tag name="shopware.event_subscriber"/>
        </service>

        <service id="neti_tool_kit.subscriber.listing_properties" class="NetiToolKit\Subscriber\FrontendProperties">
            <argument type="service" id="shopware_storefront.context_service"/>
            <argument type="service" id="shopware_storefront.property_service"/>
            <argument type="service" id="legacy_struct_converter"/>
            <argument type="service" id="neti_foundation.plugin_manager_config"/>
            <tag name="shopware.event_subscriber"/>
        </service>

        <service id="neti_tool_kit.subscriber.frontend_detail" class="NetiToolKit\Subscriber\FrontendDetail">
            <tag name="shopware.event_subscriber"/>
        </service>

        <!-- Emotion event subscriber -->
        <service id="neti_tool_kit.emotion_view_subscriber"
                 class="Shopware\Components\Emotion\EmotionComponentViewSubscriber">
            <argument>%neti_tool_kit.plugin_dir%</argument>
            <tag name="shopware.event_subscriber"/>
        </service>
    </services>
</container>


text:
from typing import List

from mcfw.rpc import returns, arguments
from rogerthat.bizz.app import get_community_statistics
from rogerthat.bizz.service import get_and_validate_service_identity_user
from rogerthat.rpc import users
from rogerthat.rpc.service import service_api
from rogerthat.to.statistics import CommunityUserStatisticsTO

@service_api(function=u'communities.get_statistics')
@returns([CommunityUserStatisticsTO])
@arguments(community_ids=[(int, long)], service_identity=unicode)
def get_statistics(community_ids, service_identity=None):
    # type: (List[long], unicode) -> List[CommunityUserStatisticsTO]
    service_user = users.get_current_user()
    get_and_validate_service_identity_user(service_user, service_identity)
    return get_community_statistics(community_ids)


text:
#ifndef __RTC_18XX_43XX_H_
#define __RTC_18XX_43XX_H_

#ifdef __cplusplus
extern "C" {
#endif

/** @defgroup RTC_18XX_43XX CHIP: LPC18xx/43xx RTC driver
 * @ingroup CHIP_18XX_43XX_Drivers
 * @{
 */

/**
 * @brief	Initialize the RTC peripheral
 * @param	pRTC	: RTC peripheral selected
 * @return	None
 */
void Chip_RTC_Init(LPC_RTC_T *pRTC);

/**
 * @brief	De-initialize the RTC peripheral
 * @param	pRTC	: RTC peripheral selected
 * @return	None
 */
STATIC INLINE void Chip_RTC_DeInit(LPC_RTC_T *pRTC)
{
	IP_RTC_DeInit(LPC_RTC);
}

/**
 * @brief	Reset clock tick counter in the RTC peripheral
 * @param	pRTC	: RTC peripheral selected
 * @return	None
 */
STATIC INLINE void Chip_RTC_ResetClockTickCounter(LPC_RTC_T *pRTC)
{
	IP_RTC_ResetClockTickCounter(LPC_RTC);
}

/**
 * @brief	Start/Stop RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	NewState	: New State of this function, should be:
 *							- ENABLE	:The time counters are enabled
 *							- DISABLE	:The time counters are disabled
 * @return	None
 */
STATIC INLINE void Chip_RTC_Enable(LPC_RTC_T *pRTC, FunctionalState NewState)
{
	IP_RTC_Enable(LPC_RTC, NewState);
}

/**
 * @brief	Enable/Disable Counter increment interrupt for a time type
 *			in the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	cntrMask	: Or'ed bit values for time types (RTC_AMR_CIIR_IM*)
 * @param	NewState	: ENABLE or DISABLE
 * @return	None
 */
STATIC INLINE void Chip_RTC_CntIncrIntConfig(LPC_RTC_T *pRTC, uint32_t cntrMask, FunctionalState NewState)
{
	IP_RTC_CntIncrIntConfig(LPC_RTC, cntrMask, NewState);
}

/**
 * @brief	Enable/Disable Alarm interrupt for a time type
 *			in the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	alarmMask	: Or'ed bit values for ALARM types (RTC_AMR_CIIR_IM*)
 * @param	NewState	: ENABLE or DISABLE
 * @return	None
 */
STATIC INLINE void Chip_RTC_AlarmIntConfig(LPC_RTC_T *pRTC, uint32_t alarmMask, FunctionalState NewState)
{
	IP_RTC_AlarmIntConfig(LPC_RTC, alarmMask, NewState);
}

/**
 * @brief	Set current time value for a time type in the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	Timetype	: time field index type to set
 * @param	TimeValue	: Value to palce in time field
 * @return	None
 */
STATIC INLINE void Chip_RTC_SetTime(LPC_RTC_T *pRTC, IP_RTC_TIMEINDEX_T Timetype, uint32_t TimeValue)
{
	IP_RTC_SetTime(LPC_RTC, Timetype, TimeValue);
}

/**
 * @brief	Get current time value for a type time type
 * @param	pRTC		: RTC peripheral selected
 * @param	Timetype	: Time field index type to get
 * @return	Value of time field according to specified time type
 */
STATIC INLINE uint32_t Chip_RTC_GetTime(LPC_RTC_T *pRTC, IP_RTC_TIMEINDEX_T Timetype)
{
	return IP_RTC_GetTime(LPC_RTC, Timetype);
}

/**
 * @brief	Set full time in the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	pFullTime	: Pointer to full time data
 * @return	None
 */
STATIC INLINE void Chip_RTC_SetFullTime(LPC_RTC_T *pRTC, IP_RTC_TIME_T *pFullTime)
{
	IP_RTC_SetFullTime(LPC_RTC, pFullTime);
}

/**
 * @brief	Get full time from the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	pFullTime	: Pointer to full time record to fill
 * @return	None
 */
STATIC INLINE void Chip_RTC_GetFullTime(LPC_RTC_T *pRTC, IP_RTC_TIME_T *pFullTime)
{
	IP_RTC_GetFullTime(LPC_RTC, pFullTime);
}

/**
 * @brief	Set alarm time value for a time type
 * @param	pRTC		: RTC peripheral selected
 * @param	Timetype	: Time index field to set
 * @param	ALValue		: Alarm time value to set
 * @return	None
 */
STATIC INLINE void Chip_RTC_SetAlarmTime(LPC_RTC_T *pRTC, IP_RTC_TIMEINDEX_T Timetype, uint32_t ALValue)
{
	IP_RTC_SetAlarmTime(LPC_RTC, Timetype, ALValue);
}

/**
 * @brief	Get alarm time value for a time type
 * @param	pRTC		: RTC peripheral selected
 * @param	Timetype	: Time index field to get
 * @return	Value of Alarm time according to specified time type
 */
STATIC INLINE uint32_t Chip_RTC_GetAlarmTime(LPC_RTC_T *pRTC, IP_RTC_TIMEINDEX_T Timetype)
{
	return IP_RTC_GetAlarmTime(LPC_RTC, Timetype);
}

/**
 * @brief	Set full alarm time in the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	pFullTime	: Pointer to full time record to set alarm
 * @return	None
 */
STATIC INLINE void Chip_RTC_SetFullAlarmTime(LPC_RTC_T *pRTC, IP_RTC_TIME_T *pFullTime)
{
	IP_RTC_SetFullAlarmTime(LPC_RTC, pFullTime);
}

/**
 * @brief	Get full alarm time in the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	pFullTime	: Pointer to full time record to fill
 * @return	None
 */
STATIC INLINE void Chip_RTC_GetFullAlarmTime(LPC_RTC_T *pRTC, IP_RTC_TIME_T *pFullTime)
{
	IP_RTC_GetFullAlarmTime(LPC_RTC, pFullTime);
}

/**
 * @brief	Write value to General purpose registers
 * @param	pRegFile	: RegFile peripheral selected
 * @param	index		: General purpose register index
 * @param	Value		: Value to write
 * @return	None
 * @note	These General purpose registers can be used to store important
 * information when the main power supply is off. The value in these
 * registers is not affected by chip reset. These registers are
 * powered in the RTC power domain.
 */
STATIC INLINE void Chip_REGFILE_Write(LPC_REGFILE_T *pRegFile, uint8_t index, uint32_t Value)
{
	IP_REGFILE_Write(pRegFile, index, Value);
}

/**
 * @brief	Read value from General purpose registers
 * @param	pRegFile	: RegFile peripheral selected
 * @param	index		: General purpose register index
 * @return	Read Value
 * @note	TheseGeneral purpose registers can be used to store important
 * information when the main power supply is off. The value in these
 * registers is not affected by chip reset. These registers are
 * powered in the RTC power domain.
 */
STATIC INLINE uint32_t Chip_REGFILE_Read(LPC_REGFILE_T *pRegFile, uint8_t index)
{
	return IP_REGFILE_Read(pRegFile, index);
}

/**
 * @brief	Enable/Disable calibration counter in the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	NewState	: New State of this function, should be:
 *							- ENABLE	:The calibration counter is enabled and counting
 *							- DISABLE	:The calibration counter is disabled and reset to zero
 * @return	None
 */
STATIC INLINE void Chip_RTC_CalibCounterCmd(LPC_RTC_T *pRTC, FunctionalState NewState)
{
	IP_RTC_CalibCounterCmd(LPC_RTC, NewState);
}

/**
 * @brief	Configures Calibration in the RTC peripheral
 * @param	pRTC		: RTC peripheral selected
 * @param	CalibValue	: Calibration value, should be in range from 0 to 131,072
 * @param	CalibDir	: Calibration Direction, should be:
 *							- RTC_CALIB_DIR_FORWARD		:Forward calibration
 *							- RTC_CALIB_DIR_BACKWARD	:Backward calibration
 * @return	None
 */
STATIC INLINE void Chip_RTC_CalibConfig(LPC_RTC_T *pRTC, uint32_t CalibValue, uint8_t CalibDir)
{
	IP_RTC_CalibConfig(LPC_RTC, CalibValue, CalibDir);
}

/**
 * @brief	Clear specified Location interrupt pending in the RTC peripheral
 * @param	pRTC	: RTC peripheral selected
 * @param	IntType	: Interrupt location type, should be:
 *						- RTC_INT_COUNTER_INCREASE	:Clear Counter Increment Interrupt pending.
 *						- RTC_INT_ALARM				:Clear alarm interrupt pending
 * @return	None
 */
STATIC INLINE void Chip_RTC_ClearIntPending(LPC_RTC_T *pRTC, uint32_t IntType)
{
	IP_RTC_ClearIntPending(LPC_RTC, IntType);
}

/**
 * @brief	Check whether if specified location interrupt in the RTC peripheral is set or not
 * @param	pRTC	: RTC peripheral selected
 * @param	IntType	: Interrupt location type, should be:
 *						- RTC_INT_COUNTER_INCREASE: Counter Increment Interrupt block generated an interrupt.
 *						- RTC_INT_ALARM: Alarm generated an interrupt.
 * @return	New state of specified Location interrupt in RTC peripheral, SET OR RESET
 */
STATIC INLINE IntStatus Chip_RTC_GetIntPending(LPC_RTC_T *pRTC, uint32_t IntType)
{
	return IP_RTC_GetIntPending(LPC_RTC, IntType);
}

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* __RTC_18XX_43XX_H_ */


text:
package de.anormalmedia.vividswinganimations.interpolation;

public class LinearInterpolator implements Interpolator {

    @Override
    public long interpolate( long timeProgress, long duration ) {
        return timeProgress;
    }

}


text:
 #!/usr/bin/python
 # -*- coding: utf-8 -*-
"""
Simple exception wrapper class for tahmatassu-api
"""
class TassuException(Exception):

	def __init__(self, message, throwable):
		Exception.__init__(self, message)
		self.throwable = throwable


text:
from os import environ
PORT = int(environ.get('PORT'))
HOST = environ.get('HOST')
HOSTS = environ.get('HOSTS').split(',')
SERVICE_NAME = environ.get('SERVICE_NAME')

CONNECTION = f'{HOST}:{PORT}'


text:
from flexbe_core import EventState, Logger
import rospy

from dynamic_reconfigure.client import Client

"""
Created on 03/05/2015

@author: Moritz Schappler
"""

class UpdateDynamicParameterImpedanceControllerState(EventState):
	"""
	Updates a given impedance controller parameter via dynamic reconfigure

	-- controller_chain 			List()	List of names of the chains of the controllers to be set: "left_arm", "right_arm", ...
	># parameter_keys		 		dict where keys are elements are elements of controller_chain and element is a list of parameter keys for dynamic reconfigure
	># parameter_values 			dict where keys are elements are elements of controller_chain and element is a list of parameter values for dynamic reconfigure

	<= updated 						Successfully changed dynamic reconfigure parameter.
	<= failed 						error in the update.

	"""

	def __init__(self, controller_chain):
		"""Constructor"""
		super(UpdateDynamicParameterImpedanceControllerState, self).__init__(outcomes=['updated', 'failed'],
															input_keys=['parameter_keys', 'parameter_values'])

		self._controller_chain = controller_chain

		self._failed = False

	def execute(self, userdata):
		try:
			for entry in self._pending_clients:

				client = entry['client']
				param_dict = entry['parameter_dict']
				Logger.loginfo( 'UpdateDynamicParameterImpedanceControllerState: Trying client %s with parameters %s' % (client.name, str(param_dict)) )

				if param_dict is not None:

					client.update_configuration(param_dict)
					for key in param_dict.keys():
						Logger.loginfo("%s: %s new value: %f" % (str(client.name), key, param_dict[key]))

					self._pending_clients.remove(entry)

			if len(self._pending_clients) is 0:
				return 'updated'
		except Exception as e:
			Logger.logwarn('UpdateDynamicParameterImpedanceControllerState: Was unable to set parameters:\n%s' % str(e))
			self._failed = True

	def on_enter(self, userdata):
		try:
			self._parameter_keys = userdata.parameter_keys
			self._parameter_values = userdata.parameter_values

			if len(self._parameter_keys) != len(self._parameter_values):
				Logger.logwarn('UpdateDynamicParameterImpedanceControllerState: Parameter_keys has %d entries, but parameter_values has %d entries!' % (len(self._parameter_keys), len(self._parameter_values)) )

			Logger.loginfo( 'UpdateDynamicParameterImpedanceControllerState: Trying to set %d key-value paris for %s' % (len(self._parameter_keys), str(self._controller_chain)) )

			# dictionary, where the keys are the elements of controller_chain and the values are dicts with key-value-pairs for parameters
			self._parameter_dicts = dict()
			# dictionary, where the keys are the elements of controller_chain and the values are one client each
			self._clients = dict()

			# set clients and parameter dictionaries based on the controllers
			for i in range(len(self._controller_chain)):
				chain = self._controller_chain[i]
				# set controller name based on joint chain
				if chain == 'left_arm':
					controller_name = 'left_arm_joint_impedance_controller'
				elif chain == 'right_arm':
					controller_name = 'right_arm_joint_impedance_controller'
				else:
					Logger.logwarn('Chain %s not defined' % str(self._controller_chain[i]))
					return 'failed'

				self._clients[chain] = Client("/robot_controllers/"+controller_name+"/dyn_rec/"+self._controller_chain[i])

				# set parameter dictionaries
				self._parameter_dicts[chain] = dict()
				for j in range(len(self._parameter_keys[chain])):
					self._parameter_dicts[chain][self._parameter_keys[chain][j]] = self._parameter_values[chain][j]

			# List of pending clients will be filled with clients first and then emptied if clients have been processed
			self._pending_clients = []

			# add all clients and their parameters to the list of pending clients
			for i in range(len(self._controller_chain)):
				chain = self._controller_chain[i]
				self._pending_clients.append({'client': self._clients[chain], 'parameter_dict': self._parameter_dicts[chain]})
				Logger.loginfo( "UpdateDynamicParameterImpedanceControllerState:added pending client %s with %s" % (chain, str(self._parameter_dicts[chain])) )
		except Exception as e:
			Logger.logwarn('UpdateDynamicParameterImpedanceControllerState: Was unable to reach parameter server:\n%s' % str(e))
			self._failed = True


text:
package gov.nih.nci.cagrid.introduce.portal.modification.services.servicetree;

import gov.nih.nci.cagrid.introduce.common.SpecificServiceInformation;
import gov.nih.nci.cagrid.introduce.portal.common.IntroduceLookAndFeel;
import gov.nih.nci.cagrid.introduce.portal.modification.services.ModifyService;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

public class ServicePopUpMenu extends JPopupMenu {

    ServiceTypeTreeNode node;
    private JMenuItem modificationMenuItem = null;

    /**
     * This method initializes
     */
    public ServicePopUpMenu(ServiceTypeTreeNode node) {
        super();
        this.node = node;
        initialize();
    }

    /**
     * This method initializes this
     */
    private void initialize() {
        this.add(getModificationMenuItem());
    }

    /**
     * This method initializes modificationMenuItem
     *
     * @return javax.swing.JMenuItem
     */
    private JMenuItem getModificationMenuItem() {
        if (this.modificationMenuItem == null) {
            this.modificationMenuItem = new JMenuItem();
            this.modificationMenuItem.setText("Modify Service");
            this.modificationMenuItem.setIcon(IntroduceLookAndFeel.getModifyServiceSmallIcon());
            this.modificationMenuItem.addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent e) {
                    super.mousePressed(e);

                    ModifyService comp = new ModifyService(new SpecificServiceInformation(
                        ServicePopUpMenu.this.node.getInfo(), ServicePopUpMenu.this.node.getServiceType()), false);
                    comp.pack();
                    comp.setVisible(true);
                }

            });
        }
        return this.modificationMenuItem;
    }
}


text:
import * as sinon from "sinon";
import { KeyboardRules } from "../../src/keyboard-registrator/keyboard-rules/keyboard-rules";

export class KeyboardRulesStub {

  public static create(): any {
    return sinon.createStubInstance(KeyboardRules);
  }

}


text:
package org.hawkular.bus.common;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.hawkular.bus.common.consumer.ConsumerConnectionContext;
import org.hawkular.bus.common.log.MsgLogger;
import org.hawkular.bus.common.producer.ProducerConnectionContext;
import org.jboss.logging.Logger;

/**
 * Provides convenience functionality to create {@link ProducerConnectionContext producer} or
 * {@link ConsumerConnectionContext consumer} contexts. You can then pass these created contexts to
 * {@link MessageProcessor} to send and receive messages.
 *
 * This class can reuse a connection so that it is shared across multiple contexts. See
 * {@link #createOrReuseConnection(ConnectionContext, boolean)}. If this object was told not to reuse
 * its connection, it will create a new connection for each context is creates.
 *
 * When you are done with sending and receiving messages through the created contexts, you should call {@link #close()}
 * to free up resources and close the connection to the broker.
 *
 * Subclasses are free to extend this class to add or override functionality or to provide stricter type-checking.
 */
public class ConnectionContextFactory implements AutoCloseable {

    private final MsgLogger msglog = MsgLogger.LOGGER;
    private final Logger log = Logger.getLogger(ConnectionContextFactory.class);
    private boolean reuseConnection;

    protected ConnectionFactory connectionFactory;

    private Connection connection;

    /**
     * Initializes with the given factory.
     *
     * @param connectionFactory the factory that will be used to create contexts.
     *
     * @throws JMSException any error
     */
    public ConnectionContextFactory(ConnectionFactory connectionFactory) throws JMSException {
        this(false, connectionFactory);
    }

    /**
     * Initializes with the given factory.
     *
     * @param reuseConnection if true this factory will reuse its connection so contexts it creates can share it.
     *                        Use this with caution because if a shared connection is closed, all contexts created
     *                        with that connection will no longer work.
     * @param connectionFactory the factory that will be used to create contexts.
     *
     * @throws JMSException any error
     */
    public ConnectionContextFactory(boolean reuseConnection, ConnectionFactory connectionFactory) throws JMSException {
        this.reuseConnection = reuseConnection;
        this.connectionFactory = connectionFactory;
        log.debugf("%s has been created with an existing connection factory: %s", this.getClass().getSimpleName(),
                connectionFactory);
    }

    /**
     * Creates a new producer connection context, reusing any existing connection that might have already been created.
     * The destination of the connection's session will be that of the given endpoint.
     *
     * @param endpoint where the producer will send messages
     * @return the new producer connection context fully populated
     * @throws JMSException any error
     */
    public ProducerConnectionContext createProducerConnectionContext(Endpoint endpoint) throws JMSException {
        ProducerConnectionContext context = new ProducerConnectionContext();
        createOrReuseConnection(context, true);
        createSession(context);
        createDestination(context, endpoint);
        createProducer(context);
        return context;
    }

    /**
     * Creates a new consumer connection context, reusing any existing connection that might have already been created.
     * The destination of the connection's session will be that of the given endpoint.
     *
     * @param endpoint where the consumer will listen for messages
     * @return the new consumer connection context fully populated
     * @throws JMSException any error
     */
    public ConsumerConnectionContext createConsumerConnectionContext(Endpoint endpoint) throws JMSException {
        return createConsumerConnectionContext(endpoint, null);
    }

    /**
     * Creates a new consumer connection context, reusing any existing connection that might have
     * already been created. The destination of the connection's session will be that of the given endpoint.
     * The consumer will filter messages based on the given message selector expression (which may be
     * null in which case the consumer will consume all messages).
     *
     * @param endpoint where the consumer will listen for messages
     * @param messageSelector message consumer's message selector expression.
     * @return the new consumer connection context fully populated
     * @throws JMSException any error
     */
    public ConsumerConnectionContext createConsumerConnectionContext(Endpoint endpoint, String messageSelector)
            throws JMSException {
        ConsumerConnectionContext context = new ConsumerConnectionContext();
        createOrReuseConnection(context, true);
        createSession(context);
        createDestination(context, endpoint);
        createConsumer(context, messageSelector);
        return context;
    }

    /**
     * This will close its open connection that it has cached, thus freeing up resources.
     * This method should be called when this context factory is no longer needed. But realize
     * that any contexts that were created with the cached connection will be invalidated
     * since this method will close that connection.
     *
     * @throws JMSException any error
     */
    @Override
    public void close() throws JMSException {
        cacheConnection(null, true);
        log.debugf("%s has been closed", this);
    }

    /**
     * @return true if this factory will reuse its connection. Otherwise,
     *         it will always create new connections for each context it creates.
     */
    protected boolean isReuseConnection() {
        return reuseConnection;
    }

    protected ConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    /**
     * The stored connection.
     *
     * NOTE: This is not necessarily the connection created via calling {@link #createConnection(ConnectionContext)}.
     *
     * @return the connection
     *
     * @see #createConnection(ConnectionContext)
     */
    protected Connection getConnection() {
        return connection;
    }

    /**
     * To store a connection in this processor object, call this setter.
     * If there was already a cached connection, it will be closed.
     *
     * NOTE: Calling {@link #createConnection(ConnectionContext)} does
     * not set this processor's connection - that method only creates the
     * connection and puts that connection in the context. It does not save that
     * connection in this processor object. You must explicitly set the
     * connection via this method if you want that connection cached here. See
     * also {@link #createOrReuseConnection(ConnectionContext, boolean)}.
     *
     * @param connection the connection
     * @param closeExistingConnection if true, and if there was already a connection
     *                                cached, that connection will be closed. Otherwise
     *                                it will be left alone but the new connection
     *                                will take its place.
     *
     * @see #createOrReuseConnection(ConnectionContext, boolean)
     */
    protected void cacheConnection(Connection connection, boolean closeExistingConnection) {
        if (this.connection != null && closeExistingConnection) {
            try {
                // make sure it is closed to free up any resources it was using
                this.connection.close();
            } catch (JMSException e) {
                msglog.errorCannotCloseConnectionMemoryMightLeak(e);
            }
        }

        this.connection = connection;
    }

    /**
     * This method provides a way to cache and share a connection across
     * multiple contexts. It combines the creation and setting of the
     * connection. This also can optionally start the connection immediately.
     * Use this if you want to reuse any connection that may already be stored
     * in this processor object (i.e. {@link #getConnection()} is non-null). If
     * there is no connection yet, one will be created. Whether the connection
     * is created or reused, that connection will be stored in the given
     * context.
     *
     * Note that if this object was told not to cache connections, this method
     * will always create a new connection and store it in this object, overwriting
     * any previously created connection (see {@link #cacheConnection}).
     *
     * @param context the connection will be stored in this context
     * @param start if true, the created connection will be started.
     * @throws JMSException any error
     */
    protected void createOrReuseConnection(ConnectionContext context, boolean start) throws JMSException {
        Connection conn;

        if (isReuseConnection()) {
            conn = getConnection();
            if (conn != null) {
                // already have a connection cached, give it to the context
                context.setConnection(conn);
            } else {
                // there is no connection yet; create it and cache it
                createConnection(context);
                conn = context.getConnection();
                cacheConnection(conn, false);
            }
        } else {
            // we are not to cache connections - always create one
            createConnection(context);
            conn = context.getConnection();
            cacheConnection(conn, false);
        }

        if (start) {
            // Calling start on started connection is ignored.
            // But if an exception is thrown, we need to throw away the connection
            try {
                conn.start();
            } catch (JMSException e) {
                msglog.errorFailedToStartConnection(e);
                cacheConnection(null, true);
                throw e;
            }
        }
    }

    /**
     * Creates a connection using this object's connection factory and stores
     * that connection in the given context object.
     *
     * NOTE: this does not set the connection in this processor object.
     * If the caller wants the created connection cached in this processor
     * object, {@link #cacheConnection} must be passed the connection
     * found in the context after this method returns. See also
     * {@link #createOrReuseConnection(ConnectionContext, boolean)}.
     *
     * @param context the context where the new connection is stored
     * @throws JMSException any error
     * @throws IllegalStateException if the context is null
     *
     * @see #createOrReuseConnection(ConnectionContext, boolean)
     * @see #cacheConnection
     */
    protected void createConnection(ConnectionContext context) throws JMSException {
        if (context == null) {
            throw new IllegalStateException("The context is null");
        }
        ConnectionFactory factory = getConnectionFactory();
        Connection conn = factory.createConnection();
        context.setConnection(conn);
    }

    /**
     * Creates a default session using the context's connection. This implementation creates a non-transacted,
     * auto-acknowledged session. Subclasses are free to override this behavior.
     *
     * @param context the context where the new session is stored
     * @throws JMSException any error
     * @throws IllegalStateException if the context is null or the context's connection is null
     */
    protected void createSession(ConnectionContext context) throws JMSException {
        if (context == null) {
            throw new IllegalStateException("The context is null");
        }
        Connection conn = context.getConnection();
        if (conn == null) {
            throw new IllegalStateException("The context had a null connection");
        }
        Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        context.setSession(session);
    }

    /**
     * Creates a destination using the context's session. The destination correlates to the given named queue or topic.
     *
     * @param context the context where the new destination is stored
     * @param endpoint identifies the queue or topic
     * @throws JMSException any error
     * @throws IllegalStateException if the context is null or the context's session is null or endpoint is null
     */
    protected void createDestination(ConnectionContext context, Endpoint endpoint) throws JMSException {
        if (endpoint == null) {
            throw new IllegalStateException("Endpoint is null");
        }
        if (context == null) {
            throw new IllegalStateException("The context is null");
        }
        Session session = context.getSession();
        if (session == null) {
            throw new IllegalStateException("The context had a null session");
        }
        Destination dest;
        if (endpoint.getType() == Endpoint.Type.QUEUE) {
            if (endpoint.isTemporary()) {
                dest = session.createTemporaryQueue();
            } else {
                dest = session.createQueue(getDestinationName(endpoint));
            }
        } else {
            if (endpoint.isTemporary()) {
                dest = session.createTemporaryTopic();
            } else {
                dest = session.createTopic(getDestinationName(endpoint));
            }
        }
        context.setDestination(dest);
    }

    /**
     * With ActiveMQ we were passing the full JNDI name, e.g., java:/topic/HawkularInventoryChanges, to
     * Session.createTopic (or Session.createQueue). Using the full JNDI name/path does not work with Artemis.
     */
    private String getDestinationName(Endpoint endpoint) {
        int start = endpoint.getName().lastIndexOf('/') + 1;
        return endpoint.getName().substring(start);
    }

    /**
     * Creates a message producer using the context's session and destination.
     *
     * @param context the context where the new producer is stored
     * @throws JMSException any error
     * @throws IllegalStateException if the context is null or the context's session is null
     *                               or the context's destination is null
     */
    protected void createProducer(ProducerConnectionContext context) throws JMSException {
        if (context == null) {
            throw new IllegalStateException("The context is null");
        }
        Session session = context.getSession();
        if (session == null) {
            throw new IllegalStateException("The context had a null session");
        }
        Destination dest = context.getDestination();
        if (dest == null) {
            throw new IllegalStateException("The context had a null destination");
        }
        MessageProducer producer = session.createProducer(dest);
        context.setMessageProducer(producer);
    }

    /**
     * Creates a message consumer using the context's session and destination.
     *
     * @param context the context where the new consumer is stored
     * @param messageSelector the message selector expression that the consumer will use to filter messages
     * @throws JMSException any error
     * @throws IllegalStateException if the context is null or the context's session is null
     *                               or the context's destination is null
     */
    protected void createConsumer(ConsumerConnectionContext context, String messageSelector) throws JMSException {
        if (context == null) {
            throw new IllegalStateException("The context is null");
        }
        Session session = context.getSession();
        if (session == null) {
            throw new IllegalStateException("The context had a null session");
        }
        Destination dest = context.getDestination();
        if (dest == null) {
            throw new IllegalStateException("The context had a null destination");
        }
        MessageConsumer consumer = session.createConsumer(dest, messageSelector);
        context.setMessageConsumer(consumer);
    }
}


text:
package com.tmtron.greenannotations.test;

import android.support.annotation.NonNull;

class Event4Tests {
    @NonNull
    final String identifier;

    Event4Tests(@SuppressWarnings("SameParameterValue") @NonNull String identifier) {
        this.identifier = identifier;
    }

}


text:
var Task = require('./model');

module.exports = {

  // create  new task
  createTask: function(content, callback){
    new Task({
      content: content,
      update_at: Date.now()
    }).save(function(err, task, count) {
      if(!err) {
        callback();
        console.log('create successfully!');
      }else{
        console.err(err);
      }
    });
  },

  // list all tasks
  all: function(callback){
    Task.find(function(err, tasks, count) {
      if(!err) {
        callback(tasks, count);
      }else {
        console.log('Cannot retry the task list from database');
      }
    })
  },

  // delete task by id
  delete: function(id, callback){
    Task.findById(id, function(err, task) {
      if(!err) {
        task.remove();
        callback();
      }else{
        console.log(err);
      }
    });
  },

  // udpate task by id
  update: function(id, content, callback){
    Task.findById(id, function(err, task) {
      if(!err) {
        task.content = content;
        task.update_at = Date.now();
        task.save(function(err){
          console.log(err);
        });
        callback();
      }else {
        console.log('BD error');
      }
    });
  },

  // get task by id
  getTask: function(id, callback) {
    Task.findById(id, function(err, task) {
      callback(task);
    });
  }

};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class FtpServerOptions
   | FTP Server documentation </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class FtpServerOptions
   | FTP Server documentation ">
    <meta name="generator" content="docfx 2.43.2.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

    <meta property="docfx:rel" content="../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class FtpServerOptions

The FTP server options.

Inheritance

Object

FtpServerOptions

Inherited Members

      Object.Equals(Object)

      Object.Equals(Object, Object)

      Object.GetHashCode()

      Object.GetType()

      Object.MemberwiseClone()

      Object.ReferenceEquals(Object, Object)

      Object.ToString()

Namespace: FubarDev.FtpServer

Assembly: FubarDev.FtpServer.dll

Syntax

public class FtpServerOptions

Properties

    |
    Improve this Doc

    View Source

ConnectionInactivityCheckInterval

Gets or sets the interval between checks for inactive connections.

Declaration

public TimeSpan? ConnectionInactivityCheckInterval { get; set; }

Property Value

        Type
        Description

        Nullable<TimeSpan>

    |
    Improve this Doc

    View Source

MaxActiveConnections

Gets or sets the max allows active connections.

Declaration

public int MaxActiveConnections { get; set; }

Property Value

        Type
        Description

        Int32

Remarks

This will cause connections to be refused if count is exceeded.
0 (default) means no control over connection count.

    |
    Improve this Doc

    View Source

Port

Gets or sets the server port.

Declaration

public int Port { get; set; }

Property Value

        Type
        Description

        Int32

    |
    Improve this Doc

    View Source

ServerAddress

Gets or sets the address the server listens on.
Leave empty to listen on all interfaces.

Declaration

public string? ServerAddress { get; set; }

Property Value

        Type
        Description

        Nullable<String>

                    Improve this Doc

                    View Source

              Back to top

Copyright © 2018 Fubar Development Junker
Generated by DocFX
FluentMigrator Documentation by FluentMigrator Project is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.


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

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.codedeploy.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * BatchGetApplicationRevisionsRequest Marshaller
 */
public class BatchGetApplicationRevisionsRequestMarshaller
        implements
        Marshaller<Request<BatchGetApplicationRevisionsRequest>, BatchGetApplicationRevisionsRequest> {

    public Request<BatchGetApplicationRevisionsRequest> marshall(
            BatchGetApplicationRevisionsRequest batchGetApplicationRevisionsRequest) {

        if (batchGetApplicationRevisionsRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<BatchGetApplicationRevisionsRequest> request = new DefaultRequest<BatchGetApplicationRevisionsRequest>(
                batchGetApplicationRevisionsRequest, "AmazonCodeDeploy");
        request.addHeader("X-Amz-Target",
                "CodeDeploy_20141006.BatchGetApplicationRevisions");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator();

            jsonGenerator.writeStartObject();

            if (batchGetApplicationRevisionsRequest.getApplicationName() != null) {
                jsonGenerator.writeFieldName("applicationName").writeValue(
                        batchGetApplicationRevisionsRequest
                                .getApplicationName());
            }

            com.amazonaws.internal.SdkInternalList<RevisionLocation> revisionsList = (com.amazonaws.internal.SdkInternalList<RevisionLocation>) batchGetApplicationRevisionsRequest
                    .getRevisions();
            if (!revisionsList.isEmpty() || !revisionsList.isAutoConstruct()) {
                jsonGenerator.writeFieldName("revisions");
                jsonGenerator.writeStartArray();
                for (RevisionLocation revisionsListValue : revisionsList) {
                    if (revisionsListValue != null) {

                        RevisionLocationJsonMarshaller.getInstance().marshall(
                                revisionsListValue, jsonGenerator);
                    }
                }
                jsonGenerator.writeEndArray();
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", "application/x-amz-json-1.1");
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
__author__ = 'Kamo Petrosyan'
import os
import codecs
from django.conf import settings

MEDIA_ROOT = getattr(settings, 'MEDIA_ROOT', getattr(settings, 'STATIC_ROOT'))

class Logger:
    def __init__(self, filename, src):
        file = codecs.open(os.path.join(MEDIA_ROOT, 'logs', filename), 'a', 'utf-8')
        file.write(src+'\n')
        file.close()