text:
Jmol.___JSVDate="$Date: 2015-01-05 17:28:27 -0600 (Mon, 05 Jan 2015) $"
Jmol.___JSVSvnRev="$LastChangedRevision: 1681 $"
Jmol.___JSVVersion="14.2.7"
Clazz.declarePackage ("JSV.common");
c$ = Clazz.declareType (JSV.common, "JSVersion");
Clazz.defineStatics (c$,
"VERSION", null,
"VERSION_SHORT", null);
{
var tmpVersion = null;
var tmpDate = null;
var tmpSVN = null;
{
tmpVersion = Jmol.___JSVVersion; tmpDate = Jmol.___JSVDate;
tmpSVN =  Jmol.___JSVSvnRev;
}if (tmpDate != null) tmpDate = tmpDate.substring (7, 23);
tmpSVN = (tmpSVN == null ? "" : "/SVN" + tmpSVN.substring (22, 27));
JSV.common.JSVersion.VERSION_SHORT = (tmpVersion != null ? tmpVersion : "(Unknown version)");
JSV.common.JSVersion.VERSION = JSV.common.JSVersion.VERSION_SHORT + tmpSVN + "/" + (tmpDate != null ? tmpDate : "(Unknown date)");
}


text:
package io.cloudslang.content.alibaba.actions.instances;

import com.aliyuncs.IAcsClient;
import com.hp.oo.sdk.content.annotations.Action;
import com.hp.oo.sdk.content.annotations.Output;
import com.hp.oo.sdk.content.annotations.Param;
import com.hp.oo.sdk.content.annotations.Response;
import com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType;
import com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType;
import io.cloudslang.content.alibaba.utils.ClientUtil;
import io.cloudslang.content.alibaba.utils.Validator;
import io.cloudslang.content.alibaba.utils.constants.Outputs;

import java.util.Map;

import static io.cloudslang.content.alibaba.services.InstanceService.restartInstance;
import static io.cloudslang.content.alibaba.utils.constants.Commons.DEFAULT_PROXY_PORT;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.ACCESS_KEY_ID_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.ACCESS_KEY_SECRET_ID_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.EXCEPTION_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.FORCE_STOP_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.INSTANCE_ID_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.PROXY_HOST_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.PROXY_PASSWORD_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.PROXY_PORT_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.PROXY_USERNAME_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.REGION_ID_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.REQUEST_ID_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.RETURN_CODE_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.Common.RETURN_RESULT_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.RestartInstance.FAILURE_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.RestartInstance.RESTART_INSTANCE_DESC;
import static io.cloudslang.content.alibaba.utils.constants.Descriptions.RestartInstance.SUCCESS_DESC;
import static io.cloudslang.content.alibaba.utils.constants.ExceptionMessages.RESTART_INSTANCE_EXCEPTION;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.ACCESS_KEY_ID;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.ACCESS_KEY_SECRET;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.FORCE_STOP;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.INSTANCE_ID;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.PROXY_HOST;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.PROXY_PASSWORD;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.PROXY_PORT;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.PROXY_USERNAME;
import static io.cloudslang.content.alibaba.utils.constants.Inputs.REGION_ID;
import static io.cloudslang.content.alibaba.utils.constants.Outputs.REQUEST_ID;
import static io.cloudslang.content.alibaba.utils.constants.SuccessMessages.RESTART_INSTANCE_SUCCESS;
import static io.cloudslang.content.utils.OutputUtilities.getFailureResultsMap;
import static io.cloudslang.content.utils.OutputUtilities.getSuccessResultsMap;
import static java.lang.Boolean.valueOf;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;

public class RestartInstance {
    @Action(name = "Restart Instance",
            description = RESTART_INSTANCE_DESC,
            outputs = {
                    @Output(value = Outputs.RETURN_CODE, description = RETURN_CODE_DESC),
                    @Output(value = Outputs.RETURN_RESULT, description = RETURN_RESULT_DESC),
                    @Output(value = Outputs.REQUEST_ID, description = REQUEST_ID_DESC),
                    @Output(value = Outputs.EXCEPTION, description = EXCEPTION_DESC)
            },
            responses = {
                    @Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
                            matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED, description = SUCCESS_DESC),
                    @Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
                            matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, description = FAILURE_DESC)
            }
    )
    public Map<String, String> execute(@Param(value = REGION_ID, required = true, description = REGION_ID_DESC) final String regionId,
                                       @Param(value = ACCESS_KEY_ID, required = true, description = ACCESS_KEY_ID_DESC) final String accessKeyId,
                                       @Param(value = ACCESS_KEY_SECRET, required = true, encrypted = true, description = ACCESS_KEY_SECRET_ID_DESC) final String accessKeySecret,
                                       @Param(value = PROXY_HOST, description = PROXY_HOST_DESC) final String proxyHost,
                                       @Param(value = PROXY_PORT, description = PROXY_PORT_DESC) final String proxyPort,
                                       @Param(value = PROXY_USERNAME, description = PROXY_USERNAME_DESC) final String proxyUsername,
                                       @Param(value = PROXY_PASSWORD, encrypted = true, description = PROXY_PASSWORD_DESC) final String proxyPassword,
                                       @Param(value = INSTANCE_ID, required = true, description = INSTANCE_ID_DESC) final String instanceId,
                                       @Param(value = FORCE_STOP, description = FORCE_STOP_DESC) final String forceStop) {

        //Get default values and String conversions
        final String proxyHostImp = defaultIfEmpty(proxyHost, EMPTY);
        final String proxyPortImp = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT);
        final String proxyUsernameImp = defaultIfEmpty(proxyUsername, EMPTY);
        final String proxyPasswordImp = defaultIfEmpty(proxyPassword, EMPTY);
        final Boolean forceStopImp = valueOf(forceStop);

        //Validate Inputs
        Validator validator = new Validator()
                .validatePort(proxyPortImp, PROXY_PORT);

        if (validator.hasErrors()) {
            return getFailureResultsMap(validator.getErrors());
        }

        try {
            final IAcsClient client = ClientUtil.getClient(regionId, accessKeyId, accessKeySecret);
            final String requestId = restartInstance(proxyHostImp, proxyPortImp, proxyUsernameImp, proxyPasswordImp, instanceId, forceStopImp, client);

            final Map<String, String> resultMap = getSuccessResultsMap(RESTART_INSTANCE_SUCCESS);
            resultMap.put(REQUEST_ID, requestId);

            return resultMap;
        } catch (Exception e) {
            return getFailureResultsMap(RESTART_INSTANCE_EXCEPTION, e);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { reject } from 'ember-fsm';
import { module, test } from 'qunit';

module('Unit: ember-fsm/-reject', function() {
  test('is a function', function(assert) {
    assert.strictEqual(typeof reject, 'function');
  });

  test('throws an error when called', function(assert) {
    assert.throws(function() {
      reject();
    });
  });
});


text:
import hashlib
import hmac

from Crypto.Cipher import AES
from Crypto.Random.random import randrange

from pycoin.encoding import (
    public_pair_to_bitcoin_address, public_pair_to_sec,
    sec_to_public_pair, secret_exponent_to_wif)

from pycoin.ecdsa import Point, generator_secp256k1 as BasePoint

class PubKey(Point):
    """Represents the public key. Subclasses the pycoin.ecdsa's Point
    and adds several useful methods
    """
    def address(self):
        """Returns the well-known base58 bitcoin address for this PubKey"""
        return public_pair_to_bitcoin_address((self.x(), self.y()))

    def encrypt(self, s, mac=16):
        """Encrypt a message for private viewing by the holder of the
        Private Key
        """
        # nonce is essentially a secret on the encrypter's side
        # this is a secret exponent < 2^256
        nonce = randrange(1, self.curve().p())
        tmp = BasePoint * nonce
        nonce_point = PubKey(tmp.curve(), tmp.x(), tmp.y())
        tmp = self * nonce
        shared_secret = PubKey(tmp.curve(), tmp.x(), tmp.y())

        # derive a key for making a cipher and checksum using the
        # nonce point and shared secret
        key = nonce_point.kdf(shared_secret)

        # encode the nonce point into the message as the beginning
        header = nonce_point.sec()

        # encrypt the actual message using the AES cipher
        cipher = AES.new(key[:32])
        # because we're using AES block mode, we need multiples of 16
        s = s + '\x00' * (16 - len(s) % 16)
        message = cipher.encrypt(s)

        # add a checksum for validation
        checksum_maker = hmac.new(key[32:], digestmod=hashlib.sha256)
        checksum_maker.update(message)
        checksum = checksum_maker.digest()[:mac]
        return header + message + checksum

    def kdf(self, another_p):
        """Simple Key-Derivative Function given two numbers"""
        return hashlib.sha512(self.sec() + another_p.sec()).digest()

    def sec(self):
        """Take a point on the curve and encode it into sec format (33 bytes)
        """
        return public_pair_to_sec((self.x(), self.y()))

    def __repr__(self):
        return self.address()

class PrivKey:
    """Represents the private key (secret exponent) for Elliptical Curve
    Cryptography
    """
    def __init__(self, exponent):
        self.exponent = exponent
        point = BasePoint * exponent
        self.pubkey = PubKey(point.curve(), point.x(), point.y())

    def wif(self, compressed=True):
        """Return the base58 representation (WIF format) for the private
        key
        """
        return secret_exponent_to_wif(self.exponent)

    def decrypt(self, raw, mac=16):
        """Decrypt a message sent to the holder of this key.
        """
        # get the nonce-point
        x, y = sec_to_public_pair(raw[:33])
        # validation that this point lies on the curve happens in
        #  initialization
        nonce_point = PubKey(BasePoint.curve(), x, y)

        # message gives us the ciphered message
        message = raw[33:-mac]
        # checksum makes sure everything is transmitted properly
        checksum = raw[-mac:]

        # calculate the shared secret
        tmp = nonce_point * self.exponent
        shared_secret = PubKey(tmp.curve(), tmp.x(), tmp.y())

        # derive keys
        key = nonce_point.kdf(shared_secret)
        cipher = AES.new(key[:32])

        # verify the checksum
        checksum_maker = hmac.new(key[32:], digestmod=hashlib.sha256)
        checksum_maker.update(message)
        if checksum_maker.digest()[:mac] != checksum:
            raise RuntimeError("Invalid checksum on encoded message string")

        return cipher.decrypt(message)

    def __repr__(self):
        return self.wif()


text:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                 xmlns:app="http://schemas.android.com/apk/res-auto"
                                                 android:id="@+id/main_content"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:orientation="horizontal"
            android:weightSum="4">

            <TextView
                android:id="@+id/tvMadeIt"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="2"
                android:background="@color/highlight_dark"
                android:gravity="center_vertical"
                android:paddingLeft="@dimen/widget_margin"
                android:textColor="@color/primary_text_default_material_dark"
                android:textSize="16sp"/>

            <TextView
                android:id="@+id/tvPP"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@color/highlight_light"
                android:gravity="center"
                android:padding="@dimen/widget_margin"
                android:textColor="@color/primary_text_default_material_dark"
                android:textSize="16sp"/>

            <TextView
                android:id="@+id/tvKont"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@color/highlight_dark"
                android:gravity="center"
                android:padding="@dimen/widget_margin"
                android:textColor="@color/primary_text_default_material_dark"
                android:textSize="16sp"/>
        </LinearLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>


text:
import BaseError from "./BaseError";
import Promise from "./Promise";
import Trace from "./Trace";
import { getGlobal } from "./util";

// We don't want the full DOM typings, and will only use
// this event if it actually exists.
declare var PromiseRejectionEvent: any;

/**
 * Base class for errors thrown when a (possibly) rejected promise is detected.
 */
export class BaseUnhandledRejection extends BaseError {
	/**
	 * Original promise rejection reason.
	 */
	public reason: any;

	constructor(name: string, message: string, reason: any) {
		super(name, `${message}: ${reason}`) /* istanbul ignore next (TS emitted code) */;
		this.reason = reason;
		// In case we have a reason, and it has a stack: use it instead of our
		// own stack, as it's more helpful to see where the original error was
		// thrown, than where it was thrown inside the promise lib.
		// In case we don't have a stack, explicitly state so, to not let people
		// chase a problem in the promise lib that isn't there...
		let stack: string = this.reason && typeof this.reason === "object" && this.reason.stack;
		if (typeof stack !== "string") {
			stack = String(this.reason);
		}
		this.stack = `${this.name}: ${stack}`;
	}
}

/**
 * Thrown when a rejected promise is explicitly terminated with `.done()`.
 */
export class UnhandledRejection extends BaseUnhandledRejection {
	/**
	 * Trace of rejected promise or .done() handler.
	 */
	public trace: Trace;

	constructor(reason: any, trace: Trace) {
		super("UnhandledRejection", "unhandled rejection", reason) /* istanbul ignore next (TS emitted code) */;
		// TODO: Find a better way to merge the location of `.done()` in the
		// trace, because nobody will look for this property...
		this.trace = trace;
	}
}

/**
 * Emitted when a rejected promise isn't handled.
 * @see Promise.onPossiblyUnhandledRejection
 */
export class PossiblyUnhandledRejection extends BaseUnhandledRejection {
	/**
	 * Rejected promise.
	 */
	public promise: Promise<any>;

	constructor(promise: Promise<any>) {
		super(
			"PossiblyUnhandledRejection",
			"possibly unhandled rejection",
			promise.reason()
		) /* istanbul ignore next (TS emitted code) */;
		this.promise = promise;
	}
}

/**
 * Emit PromiseRejectionEvent (in browser environment).
 * Dispatches the event to all registered handlers, e.g.
 * - window.onunhandledrejection / window.onrejectionhandled
 * - window.addEventListener("unhandledrejection", (event) => { ... }), etc
 * Uses self in case of WebWorker.
 *
 * @param type Either "unhandledrejection" or "rejectionhandled"
 * @param reason Value used to reject promise
 * @param promise ts-promise instance
 * @return true when event was 'handled' (i.e. someone called preventDefault() on it), false otherwise
 */
function emitRejectionEvent(
	type: "unhandledrejection" | "rejectionhandled",
	reason: any,
	promise: Promise<any>
): boolean {
	// Browsers do a native Promise.resolve() on the promise given in PromiseRejectEvent,
	// which causes an unhandled rejection error due to that native promise not being handled,
	// and prevents the user's unhandled rejection handler from accessing the actual
	// ts-promise Promise. This would make the handled rejection handler useless, because that
	// gets another native promise.
	// So, prevent the unhandled rejection when constructing the event, then override the
	// property to return the 'real' promise.
	// MDN says it isn't cancelable, but both Chrome and Firefox do have it cancelable.
	const event = new PromiseRejectionEvent(type, {
		cancelable: true, // allow event.preventDefault()
		promise: true, // something that's not rejected
		reason,
	});
	Object.defineProperty(event, "promise", {
		value: promise,
	});
	const global = getGlobal();
	if (global.dispatchEvent && !global.dispatchEvent(event)) {
		// Someone called preventDefault()
		return true;
	}
	return false;
}

/**
 * Default handler for an`UnhandledRejection` error, which contains the
 * original reason of the rejection.
 * In Node, if you don't have an `unhandledException` event handler, that will cause your
 * program to terminate after printing the error.
 * When overriding the default handler, it is recommended to keep a similar behavior,
 * as your program is likely in an unknown state.
 */
export function defaultUnhandledRejectionHandler(reason: any, doneTrace: Trace): void {
	const unhandledRejection = new UnhandledRejection(reason, doneTrace);
	// Leave the comment after the throw: may show up in source line in node
	throw unhandledRejection; // Unhandled rejection caught by .done()
}

/**
 * Default handler for possibly unhandled rejection. It will:
 * - emit Node's `unhandledRejection` event if present, or
 * - emit an `unhandledrejection` (note small R) `PromiseRejectionEvent` on `window` or `self` if present, or
 * - log the rejection using `console.warn()`.
 *
 * Note: when attaching an `unhandledrejection` handler in the browser, make sure to
 * call `event.preventDefault()` to prevent ts-promise's default fallback logging.
 */
export function defaultPossiblyUnhandledRejectionHandler(promise: Promise<any>): void {
	let log = true;

	// First try to emit Node event
	if (typeof process !== "undefined" && typeof process.emit === "function") {
		// Have to cast promise to any, because current typings of process.emit() have specific
		// typings for arguments to "unhandledRejection", which say promise must be a Promise,
		// but that Promise is the built-in type.
		if (process.emit("unhandledRejection", promise.reason(), promise as any)) {
			// A handler was called
			log = false;
		}
	} else if (typeof PromiseRejectionEvent === "function") {
		// Then fire a browser event if supported by the browser
		if (emitRejectionEvent("unhandledrejection", promise.reason(), promise)) {
			log = false;
		}
	}

	// Fallback to log to console
	if (log) {
		const possiblyUnhandledRejection = new PossiblyUnhandledRejection(promise);
		// tslint:disable-next-line:no-console
		console.warn(possiblyUnhandledRejection.stack);
	}
}

/**
 * Default handler for handled rejections.
 * It will emit Node's `rejectionHandled` event if present, or emit a
 * `rejectionhandled` (note small R) event on `window` (or `self`) if present.
 */
export function defaultPossiblyUnhandledRejectionHandledHandler(promise: Promise<any>): void {
	// First try to emit Node event
	if (typeof process !== "undefined" && typeof process.emit === "function") {
		// Have to cast promise to any, because current typings of process.emit() have specific
		// typings for arguments to "rejectionHandled", which say promise must be a Promise,
		// but that Promise is the built-in type.
		process.emit("rejectionHandled", promise as any);
	} else if (typeof PromiseRejectionEvent === "function") {
		// Then fire a browser event if supported by the browser
		emitRejectionEvent("rejectionhandled", promise.reason(), promise);
	}
}


text:
var url = require('url')
var css = require('sheetify')
var html = require('choo/html')

module.exports = function (state, prev, send) {
  var contents = state.contents
  var prefix = css('./menu.css')

  function createMenu (contents) {
    return contents.map(function (item) {
      // TODO: figure out a better way to get current page in state based on link click
      var current
      var location

      if (state.location && state.location.pathname) {
        location = url.parse(state.location.pathname)
        var sliceBy = state.basedir.length + 1
        current = location.pathname.slice(sliceBy)
      }

      if (!current || current.length <= 1) {
        current = state.current
      }

      function onclick (e) {
        send('menu:set', { open: false })
      }

      function createTocItem (tocItem) {
        if (tocItem.level === 1) return '' // Don't put title
        var depth = item.depth + (tocItem.level - 1)
        return html`<a href="#${tocItem.slug}" class="h${depth} content-link">${tocItem.title}</a>`
      }

      if (isActive(current, item.key) && item.toc.length > 1) {
        return html`

            ${item.name}

              ${item.toc.map(function (tocItem) {
                return (tocItem.level === 2) ? createTocItem(tocItem) : ''
              })}

        `
      }

      if (item.link) {
        return html`<div><a href="${item.link}" class="content-link ${isActive(current, item.key)}" onclick=${onclick}>${item.name}</a></div>`
      }

      return html`<div class="h${item.depth}">${item.name}</div>`
    })
  }

  function isActive (current, item) {
    return current === item ? 'active' : ''
  }

  function isOpen () {
    if (typeof window !== 'undefined' && window.innerWidth > 600) return 'menu-open'
    return state.menu.open ? 'menu-open' : 'menu-closed'
  }

  function onclick (e) {
    send('menu:set', { open: !state.menu.open })
  }

  return html`

    <button class="minidocs-menu-toggle" onclick=${onclick}>Menu</button>

        ${createMenu(contents)}

`
}


text:
package cn.huaxingtan.view;

import java.util.List;

import cn.huaxingtan.player.R;
import cn.huaxingtan.util.ImageDownloader;
import cn.huaxingtan.util.ImageDownloader.Mode;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import cn.huaxingtan.model.AudioItem;
import cn.huaxingtan.model.Serial;

public class SerialAdapter extends BaseAdapter {
	private static final String TAG = SerialAdapter.class.getCanonicalName();
    private static final ImageDownloader mImageDownloader = new ImageDownloader();
    static {
    	mImageDownloader.setMode(Mode.CORRECT);
    }

	private LayoutInflater mInflater;
	private List<Serial> mData;

	public SerialAdapter(Context context, List<Serial> data) {
		this.mInflater = LayoutInflater.from(context);
		this.mData = data;
	}

	@Override
	public int getCount() {
		return mData.size();
	}

	@Override
	public Object getItem(int position) {
		return mData.get(position);
	}

	@Override
	public long getItemId(int position) {
		return mData.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null)
			convertView = mInflater.inflate(R.layout.my_item, null);
		TextView title = (TextView) convertView.findViewById(R.id.my_item_title);
		title.setText(mData.get(position).getName());
		TextView content = (TextView)convertView.findViewById(R.id.my_item_info);
		content.setText("已下载" + mData.get(position).getDownloaded() + "讲");
		ImageView imageView = (ImageView) convertView.findViewById(R.id.my_item_image);
		imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
		mImageDownloader.download(mData.get(position).getCoverUrl(), imageView);
		return convertView;
	}

}


text:
#include <verthandi/http.h>

#include <iostream>
#include <boost/regex.hpp>
#include <boost/algorithm/string/replace.hpp>

using namespace boost::asio;
using namespace boost;
using namespace std;

/**\brief Main function
 *
 * The main entry point for any programme; with verthandi this function will set
 * up the requested socket by launching an HTTP server on it that serves data
 * from the given SQLite3 database file.
 *
 * Note that this programme does not fork itself to the background.
 *
 * \param[in] argc The number of arguments in argv.
 * \param[in] argv Command line arguments.
 *
 * \returns Zero on success, nonzero on failure.
 */
int main (int argc, char* argv[])
{
    try
    {
        if (argc != 3)
        {
            std::cerr << "Usage: " << argv[0] << " <socket> <database>\n";
            return 1;
        }

        io_service io_service;

        verthandi::http::server s(io_service, argv[1], argv[2]);

        io_service.run();
    }
    catch (std::exception &e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}


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

    <title>org.gradle.sonar.runner.plugins</title>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="keywords" CONTENT="org/gradle/sonar/runner/plugins package">

    <link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="groovy.ico" type="image/x-icon" rel="icon">
    <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

    org.gradle.sonar.runner.plugins

Classes

SonarRunnerPlugin


text:
<?php

namespace League\OAuth2\Client\Exception;

class IDPException extends \Exception
{
    protected $result;

    public function __construct($result)
    {
        $this->result = $result;

        $code = isset($result['code']) ? $result['code'] : 0;

        if (isset($result['error'])) {

            // OAuth 2.0 Draft 10 style
            $message = $result['error'];

        } elseif (isset($result['message'])) {

            // cURL style
            $message = $result['message'];

        } else {

            $message = 'Unknown Error.';

        }

        parent::__construct($message, $code);
    }

    public function getType()
    {
        if (isset($this->result['error'])) {

            $message = $this->result['error'];

            if (is_string($message)) {
                // OAuth 2.0 Draft 10 style
                return $message;
            }
        }

        return 'Exception';
    }

    /**
     * To make debugging easier.
     *
     * @return string The string representation of the error.
     */
    public function __toString()
    {
        $str = $this->getType() . ': ';

        if ($this->code != 0) {
            $str .= $this->code . ': ';
        }

        return $str . $this->message;
    }

}


text:
package com.equalexperts.weather1self.client.response.owm;

import com.equalexperts.weather1self.client.response.TemperatureDatum;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class WeatherResponse {

    private List<TemperatureDatum> weatherData;

    public WeatherResponse(List<TemperatureDatum> weatherData) {
        this.weatherData = weatherData;
    }

    public List<TemperatureDatum> getWeatherData() {
        return weatherData;
    }

    public static WeatherResponse fromJSON(JSONObject weatherResponseJson) {
        JSONArray weatherDataJSON = weatherResponseJson.getJSONArray("list");
        List<TemperatureDatum> weatherData = new ArrayList<>();
        for (int i = 0; i < weatherDataJSON.length(); i ++) {
            WeatherDatum weatherDatum = WeatherDatum.fromJSON(weatherDataJSON.getJSONObject(i));
            weatherData.add(weatherDatum);
        }
        return new WeatherResponse(weatherData);
    }
}


text:
<?php
/*
	retuns json with genres from database
*/

header("Content-type: application/json");
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();

if (login_check($mysqli) == true) {
	$stmt = $mysqli->prepare("SELECT id, genre FROM genres");
	$stmt->execute();
	$stmt->store_result();
	$stmt->bind_result($id, $genre);
	$arr = array();
	while ($row = $stmt->fetch()) {
		$arr[] = array('id' => $id, 'genre' => $genre);
	};

	echo json_encode($arr);
}
$mysqli = NULL;
?>


text:
class CollisionData
{
private:
	std::vector<RBContact*> mp_RigidContacts;

	int m_ContactsLeft;

	float m_Restitution;
	float m_Friction;

public:
	CollisionData() {};
	~CollisionData() {};

	inline void AddContacts(int contacts) { m_ContactsLeft += contacts; };

	inline std::vector<RBContact*> GetRigidContacts() { return mp_RigidContacts; };
	inline int GetContactsLeft() { return m_ContactsLeft; };

	inline float GetRestitution() { return m_Restitution; };
	inline float GetFriction() { return m_Friction; };
};
#endif


text:
<?php
namespace TYPO3\CMS\T3editor\Hook;

/**
 * Hook for tstemplate info
 */
class TypoScriptTemplateInfoHook
{
    /**
     * @var \TYPO3\CMS\T3editor\T3editor
     */
    protected $t3editor = null;

    /**
     * @var string
     */
    protected $ajaxSaveType = 'TypoScriptTemplateInformationModuleFunctionController';

    /**
     * @return \TYPO3\CMS\T3editor\T3editor
     */
    protected function getT3editor()
    {
        if ($this->t3editor == null) {
            $this->t3editor = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\T3editor\T3editor::class)->setMode(\TYPO3\CMS\T3editor\T3editor::MODE_TYPOSCRIPT)->setAjaxSaveType($this->ajaxSaveType);
        }
        return $this->t3editor;
    }

    /**
     * Hook-function: inject t3editor JavaScript code before the page is compiled
     * called in \TYPO3\CMS\Backend\Template\DocumentTemplate:startPage
     *
     * @return void
     * @see \TYPO3\CMS\Backend\Template\DocumentTemplate::startPage
     */
    public function preStartPageHook()
    {
        // Enable editor in Template-Modul
        if (\TYPO3\CMS\Core\Utility\GeneralUtility::_GET('M') === 'web_ts') {
            $t3editor = $this->getT3editor();
            // Insert javascript code
            $t3editor->getJavascriptCode();
        }
    }

    /**
     * Hook-function:
     * called in typo3/sysext/tstemplate_info/Classes/Controller/TypoScriptTemplateInformationModuleFunctionController.php
     *
     * @param array $parameters
     * @param \TYPO3\CMS\Tstemplate\Controller\TypoScriptTemplateInformationModuleFunctionController $pObj
     * @return void
     */
    public function postOutputProcessingHook($parameters, $pObj)
    {
        $t3editor = $this->getT3editor();
        $t3editor->getJavascriptCode();
        foreach (['constants', 'config'] as $type) {
            if ($parameters['e'][$type]) {
                $attributes = 'rows="' . (int)$parameters['numberOfRows'] . '" wrap="off"' . $pObj->pObj->doc->formWidth(48, true, 'width:98%;height:60%');
                $title = $GLOBALS['LANG']->getLL('template') . ' ' . $parameters['tplRow']['title'] . $GLOBALS['LANG']->getLL('delimiter') . ' ' . $GLOBALS['LANG']->getLL($type);
                $outCode = $t3editor->getCodeEditor('data[' . $type . ']', 'text-monospace enable-tab', '$1', $attributes, $title, [
                    'pageId' => (int)$pObj->pObj->id
                ]);
                $parameters['theOutput'] = preg_replace('/\\<textarea name="data\\[' . $type . '\\]".*\\>([^\\<]*)\\<\\/textarea\\>/mi', $outCode, $parameters['theOutput']);
            }
        }
    }

    /**
     * Process saving request like in class.tstemplateinfo.php (TCE processing)
     *
     * @return bool TRUE if successful
     */
    public function save($parameters, $pObj)
    {
        $savingsuccess = false;
        if ($parameters['type'] == $this->ajaxSaveType) {
            $pageId = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('pageId');
            if (!is_numeric($pageId) || $pageId < 1) {
                return false;
            }
            // If given use the requested template_uid
            // if not, use the first template-record on the page (in this case there should only be one record!)
            $set = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('SET');
            $template_uid = $set['templatesOnPage'] ?: 0;
            // Defined global here!
            $tmpl = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\ExtendedTemplateService::class);
            // Do not log time-performance information
            $tmpl->tt_track = 0;
            $tmpl->init();
            // Get the first template record on the page, which might be hidden as well
            // (for instance the TypoScript constant editor is persisting to the first template)
            $tplRow = $tmpl->ext_getFirstTemplate($pageId, $template_uid);
            $existTemplate = is_array($tplRow);
            if ($existTemplate) {
                $saveId = $tplRow['_ORIG_uid'] ?: $tplRow['uid'];
                // Update template ?
                $POST = \TYPO3\CMS\Core\Utility\GeneralUtility::_POST();
                if ($POST['submit']) {
                    // Set the data to be saved
                    $recData = [];
                    if (is_array($POST['data'])) {
                        foreach ($POST['data'] as $field => $val) {
                            switch ($field) {
                                case 'constants':
                                case 'config':
                                    // Replace Windows- and Mac linebreaks
                                    $val = str_replace([CRLF, CR], LF, $val);
                                    $recData['sys_template'][$saveId][$field] = $val;
                                    break;
                            }
                        }
                    }
                    if (!empty($recData)) {
                        // process template row before saving
                        $tstemplateinfo = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Tstemplate\Controller\TypoScriptTemplateInformationModuleFunctionController::class);
                        /* @var $tstemplateinfo \TYPO3\CMS\Tstemplate\Controller\TypoScriptTemplateInformationModuleFunctionController */
                        // load the MOD_SETTINGS in order to check if the includeTypoScriptFileContent is set
                        $tstemplateinfo->pObj = $pObj;
                        $tstemplateinfo->pObj->MOD_SETTINGS = \TYPO3\CMS\Backend\Utility\BackendUtility::getModuleData(['includeTypoScriptFileContent' => true], [], 'web_ts');
                        $recData['sys_template'][$saveId] = $tstemplateinfo->processTemplateRowBeforeSaving($recData['sys_template'][$saveId]);
                        // Create new tce-object
                        $tce = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
                        $tce->stripslashes_values = 0;
                        // Initialize
                        $tce->start($recData, []);
                        // Saved the stuff
                        $tce->process_datamap();
                        // Clear the cache (note: currently only admin-users can clear the
                        // cache in tce_main.php)
                        $tce->clear_cacheCmd('all');
                        $savingsuccess = true;
                    }
                }
            }
        }
        return $savingsuccess;
    }
}


text:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.TagHelpers;
using OrchardCore.DisplayManagement.Layout;
using OrchardCore.DisplayManagement.Shapes;

namespace OrchardCore.DisplayManagement.TagHelpers
{
    [HtmlTargetElement("zone", Attributes = NameAttribute)]
    public class ZoneTagHelper : TagHelper
    {
        private const string PositionAttribute = "position";
        private const string NameAttribute = "name";

        private readonly ILayoutAccessor _layoutAccessor;

        public ZoneTagHelper(ILayoutAccessor layoutAccessor)
        {
            _layoutAccessor = layoutAccessor;
        }

        [HtmlAttributeName(PositionAttribute)]
        public string Position { get; set; }

        [HtmlAttributeName(NameAttribute)]
        public string Name { get; set; }

        public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (String.IsNullOrEmpty(Name))
            {
                throw new ArgumentException("The name attribute can't be empty");
            }

            var childContent = await output.GetChildContentAsync();
            var layout = await _layoutAccessor.GetLayoutAsync();

            var zone = layout.Zones[Name];

            if (zone is Shape shape)
            {
                await shape.AddAsync(childContent, Position);
            }

            // Don't render the zone tag or the inner content
            output.SuppressOutput();
        }
    }
}


text:
var hexbin = require('../../deps/hexbin');
var Bin = require('./bin');
var _ = require('lodash');
var React = require('react');
var utils = require('lightning-client-utils');
var scale = require('d3-scale');

var Hexbin = React.createClass({displayName: "Hexbin",

    getDefaultProps: function() {
        return {
          points: [],
          initialRadius: 10
        };
    },

    getInitialState: function() {
        return {
            radius: this.props.initialRadius
        };
    },

    _getExtent: function(idx) {
        var iter = function(d) { return d[idx]; };

        var min = _.min(this.props.points, iter);
        var max = _.max(this.props.points, iter);

        return [min[idx], max[idx]];
    },

    hexbin: function() {
        return hexbin().size([this.props.width, this.props.height]).radius(this.state.radius);
    },

    scaleX: function() {
        return scale.linear().domain(this._getExtent(0)).range([0, this.props.width]);
    },

    scaleY: function() {
        return scale.linear().domain(this._getExtent(1)).range([0, this.props.height]);
    },

    componentWillUpdate: function() {
        var context = this.getDOMNode().getContext('2d');
        context.clearRect(0, 0, this.props.width, this.props.height);
    },

    drawNodes: function() {
        var hexbin = this.hexbin();
        var scaleX = this.scaleX();
        var scaleY = this.scaleY();
        var path = hexbin.hexagon();

        var x, y;
        var points = _.map(this.props.points, function(d) {
            x = scaleX(d[0]);
            y = scaleY(d[1]);
            return [x, y];
        }, this);

        var data = hexbin(points);
        var value = _.pluck(data, 'length');
        var colors = utils.getColorFromData({
            value: value
        });

        return _.map(data, function(d, i) {
            return (React.createElement(Bin, {path: path, x: d.x, y: d.y, getCanvasNode: this.getDOMNode, color: colors[i], key: i}))
        }, this);
    },

    render: function() {
        return (
            React.createElement("canvas", {
                width: this.props.width,
                height: this.props.height},
                this.drawNodes()
            )
        )
    }

});

module.exports = Hexbin;


text:
<!DOCTYPE html>

<form name="testForm1" action="/" onsubmit="return validateForm()" method="post">
  First name: <input type="text" name="fname" id="fname">

  Last name: <input type="text" name="lname" id="lname">

  <input type="button" value="fill names" onClick="fillNames();">
  <input type="submit" value="Submit">

 formJscriptExample1.html
</form>


text:
package alibabacloudlogserviceexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/alibabacloudlogserviceexporter"

import "go.opentelemetry.io/collector/config"

// Config defines configuration for AlibabaCloud Log Service exporter.
type Config struct {
	config.ExporterSettings `mapstructure:",squash"`
	// LogService's Endpoint, https://www.alibabacloud.com/help/doc-detail/29008.htm
	// for AlibabaCloud Kubernetes(or ECS), set {region-id}-intranet.log.aliyuncs.com, eg cn-hangzhou-intranet.log.aliyuncs.com;
	//  others set {region-id}.log.aliyuncs.com, eg cn-hangzhou.log.aliyuncs.com
	Endpoint string `mapstructure:"endpoint"`
	// LogService's Project Name
	Project string `mapstructure:"project"`
	// LogService's Logstore Name
	Logstore string `mapstructure:"logstore"`
	// AlibabaCloud access key id
	AccessKeyID string `mapstructure:"access_key_id"`
	// AlibabaCloud access key secret
	AccessKeySecret string `mapstructure:"access_key_secret"`
	// Set AlibabaCLoud ECS ram role if you are using ACK
	ECSRamRole string `mapstructure:"ecs_ram_role"`
	// Set Token File Path if you are using ACK
	TokenFilePath string `mapstructure:"token_file_path"`
}


text:
<?php
declare(strict_types=1);
/**
 *
 * This file is part of Aura for PHP.
 *
 * @license http://opensource.org/licenses/MIT MIT
 *
 */
namespace Aura\Di\Resolver;

use ReflectionClass;
use ReflectionException;

/**
 *
 * A serializable collection point for for Reflection data.
 *
 * @package Aura.Di
 *
 */
class Reflector
{
    /**
     *
     * Collected ReflectionClass instances.
     *
     * @var array
     *
     */
    protected $classes = [];

    /**
     *
     * Collected arrays of ReflectionParameter instances for class constructors.
     *
     * @var array
     *
     */
    protected $params = [];

    /**
     *
     * Collected traits in classes.
     *
     * @var array
     *
     */
    protected $traits = [];

    /**
     *
     * When serializing, ignore the Reflection-based properties.
     *
     * @return array
     *
     */
    public function __sleep(): array
    {
        return ['traits'];
    }

    /**
     *
     * Returns a ReflectionClass for the given class.
     *
     * @param string $class Return a ReflectionClass for this class.
     *
     * @return ReflectionClass
     *
     * @throws ReflectionException when the class does not exist.
     *
     */
    public function getClass($class): ReflectionClass
    {
        if (! isset($this->classes[$class])) {
            $this->classes[$class] = new ReflectionClass($class);
        }

        return $this->classes[$class];
    }

    /**
     *
     * Returns an array of ReflectionParameter instances for the constructor of
     * a given class.
     *
     * @param string $class Return the array of ReflectionParameter instances
     * for the constructor of this class.
     *
     * @return array|\ReflectionParameter[]
     *
     */
    public function getParams($class): array
    {
        if (! isset($this->params[$class])) {
            $this->params[$class] = [];
            $constructor = $this->getClass($class)->getConstructor();
            if ($constructor) {
                $this->params[$class] = $constructor->getParameters();
            }
        }

        return $this->params[$class];
    }

    /**
     *
     * Returns all traits used by a class and its ancestors,
     * and the traits used by those traits' and their ancestors.
     *
     * @param string $class The class or trait to look at for used traits.
     *
     * @return array All traits used by the requested class or trait.
     *
     * @todo Make this function recursive so that parent traits are retained
     * in the parent keys.
     *
     */
    public function getTraits($class): array
    {
        if (! isset($this->traits[$class])) {
            $traits = [];

            // get traits from ancestor classes
            do {
                $traits += class_uses($class);
            } while ($class = get_parent_class($class));

            // get traits from ancestor traits
            $traitsToSearch = $traits;
            while (!empty($traitsToSearch)) {
                $newTraits = class_uses(array_pop($traitsToSearch));
                $traits += $newTraits;
                $traitsToSearch += $newTraits;
            };

            foreach ($traits as $trait) {
                $traits += class_uses($trait);
            }

            $this->traits[$class] = array_unique($traits);
        }

        return $this->traits[$class];
    }
}


text:
package org.apache.camel.component.redis;

import org.apache.camel.Exchange;
import org.apache.camel.impl.DefaultProducer;
import org.apache.camel.util.URISupport;

/**
 * The Redis producer.
 */
public class RedisProducer extends DefaultProducer {
    private final RedisClient redisClient;

    public RedisProducer(RedisEndpoint endpoint, RedisConfiguration configuration) {
        super(endpoint);
        redisClient = new RedisClient(configuration.getRedisTemplate());
    }

    public void process(final Exchange exchange) throws Exception {
        new CommandDispatcher(getConfiguration(), exchange).execute(redisClient);
    }

    protected RedisConfiguration getConfiguration() {
        return getEndpoint().getConfiguration();
    }

    @Override
    public RedisEndpoint getEndpoint() {
        return (RedisEndpoint)super.getEndpoint();
    }

    @Override
    public String toString() {
        return "RedisProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]";
    }
}


text:
package org.openspaces.archive;

import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openspaces.core.GigaSpace;
import org.openspaces.events.EventExceptionHandler;
import org.openspaces.events.ListenerExecutionFailedException;
import org.springframework.transaction.TransactionStatus;

import com.j_spaces.kernel.time.SystemTime;

/**
 * @author Itai Frenkel
 *
 * Logs exceptions from the {@link ArchivePollingContainer}
 * Filters last exception so it won't be repeatedly logged more than once per minute.
 */
public class DefaultArchivePollingContainerExceptionHandler implements EventExceptionHandler<Object> {

    private static final long DEFAULT_TIME_WINDOW_MILLIS = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);

    private final Log logger = LogFactory.getLog(this.getClass());

    private Class<? extends Throwable> lastExceptionClass;
    private String lastExceptionMessage;
    private long lastExceptionTimestamp;

    private final long timeWindowMillis;

    public DefaultArchivePollingContainerExceptionHandler() {
        this( DEFAULT_TIME_WINDOW_MILLIS);
    }

    public DefaultArchivePollingContainerExceptionHandler(long timeWindowsMillis) {
        this.timeWindowMillis = timeWindowsMillis;
    }

    /**
     * This is the default handler if {@link #setExceptionHandler(EventExceptionHandler)} was not called.
     * Does nothing in case of a successful archive operation
     */
    @Override
    public void onSuccess(Object data, GigaSpace gigaSpace, TransactionStatus txStatus, Object source)
            throws RuntimeException {
        //ignore
    }

    /**
     *  This is the default handler if {@link #setExceptionHandler(EventExceptionHandler)} was not called.
     *  Logs the exception if it has not occured in the last minute.
     */
    @Override
    public void onException(ListenerExecutionFailedException exception, Object data, GigaSpace gigaSpace,
            TransactionStatus txStatus, Object source) throws RuntimeException {

        long now = SystemTime.timeMillis();
        if (logger.isWarnEnabled() && shouldLog(exception, now)) {
            logger.warn("Failed to archive data", exception);
            storeLastException(exception, now);
        }

        throw exception;
    }

    public void storeLastException(ListenerExecutionFailedException exception, long now) {
        Throwable cause = exception.getCause();
        this.lastExceptionClass = (cause == null) ? null : cause.getClass();
        this.lastExceptionTimestamp = now;
        this.lastExceptionMessage = (cause == null) ? null : cause.getMessage();
    }

    public boolean shouldLog(ListenerExecutionFailedException exception, long now) {
        final Throwable cause = exception.getCause();
        return  !isSameExecptionType(cause) ||
                !isSameMessage(cause) ||
                !isSameTime(now);

    }

    private boolean isSameMessage(Throwable cause) {
        return (cause == null && lastExceptionMessage == null) ||
               (cause != null && cause.getMessage() == null && lastExceptionMessage == null) ||
               (cause != null && lastExceptionMessage != null && lastExceptionMessage.equals(cause.getMessage()));
    }

    private boolean isSameExecptionType(Throwable cause) {
        return (cause == null && lastExceptionClass == null) ||
               (cause != null && lastExceptionClass != null && lastExceptionClass.equals(cause.getClass()));
    }

    private boolean isSameTime(long now) {
        return now - lastExceptionTimestamp < getTimeWindowMillis();
    }

    public long getTimeWindowMillis() {
        return timeWindowMillis;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
 ! @(#)WaterSupp_DPFGSE_1D_CLEANEX_PM.xml 1.1 10/28/10
 !
 -->
<template type="basic" name="WaterSupp_DPFGSE_1D_CLEANEX_PM" author="chempack" investigator=""
         label="CLEANEX-PM" menu1="WaterSupp"  menu2="DPFGSE 1D"
        time_created="20101028T082034" tabname="BioPack" apptype="BioPack"
        application="liquids" scans="WaterSupp_DPFGSE_1D_CLEANEX_PM" seqfil="cleanex-pm">
  <protocol title="WaterSupp_DPFGSE_1D_CLEANEX_PM" type="protocol">
    <action  type="LIB" status="Ready" lock="off" title="WaterSupp_DPFGSE_1D_CLEANEX_PM" exp="WaterSupp_DPFGSE_1D_CLEANEX_PM"
         dodialog="yes"
        time="15:34" macro="cleanexpm" data="" />
  </protocol>
</template>


text:
module Faraday
  class Response::UTFEncoder < Response::Middleware

    begin
      require 'iconv'

      def self.register_on_complete(env)
        env[:response].on_complete do |finished_env|
          finished_env[:body] = Iconv.conv('utf-8', 'ISO-8859-1', finished_env[:body])
        end
      end
    rescue LoadError, NameError => e
      self.load_error = e
    end

    def initialize(app)
      super
      @parser = nil
    end

  end
end


text:
Kubernetes is relying on etcd for state storage. More details about the usage
can be found [here](https://kubernetes.io/docs/admin/etcd/) and
[here](https://coreos.com/etcd/docs/latest/v2/README.html).

## Backup requirement

A Kubernetes cluster deployed with kops stores the etcd state in two different
AWS EBS volumes per master node. One volume is used to store the Kubernetes
main data, the other one for events. For a HA master with three nodes this will
result in six volumes for etcd data (one in each AZ). An EBS volume is designed
to have a [failure rate](https://aws.amazon.com/ebs/details/#AvailabilityandDurability)
of 0.1%-0.2% per year.

## Create volume backups

Kubernetes does currently not provide any option to do regular backups of etcd
out of the box.

Therefore we have to either manually backup the etcd volumes regularly or use
other AWS services to do this in a automated, scheduled way. You can for example
use CloudWatch to trigger an AWS Lambda with a defined schedule (e.g. once per
hour). The Lambda will then create a new snapshot of all etcd volumes. A complete
guide on how to setup automated snapshots can be found [here](https://serverlesscode.com/post/lambda-schedule-ebs-snapshot-backups/).

Note: this is one of many examples on how to do scheduled snapshots.

## Restore volume backups

In case the Kubernetes cluster fails in a way that too many master nodes can't
access their etcd volumes it is impossible to get a etcd quorum.

In this case it is now possible to restore the volume from a snapshot we created
earlier. Details about creating a volume from a snapshot can be found in the
[AWS documentation](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-restoring-volume.html).

Kubernetes uses protokube to identify the right volumes for etcd. Therefore it
is important to tag the EBS volumes with the correct tags after restoring them
from a EBS snapshot.

protokube will look for the following tags:

* `KubernetesCluster` containing the cluster name (e.g. `k8s.mycompany.tld`)
* `Name` containing the volume name (e.g. `eu-central-1a.etcd-main.k8s.mycompany.tld`)
* `k8s.io/etcd/main` containing the availability zone of the volume (e.g. `eu-central-1a/eu-central-1a`)
* `k8s.io/role/master` with the value `1`

After fully restoring the volume ensure that the old volume is no longer there,
or you've removed the tags from the old volume. After restarting the master node
Kubernetes should pick up the new volume and start running again.


text:
-- -
-- #%L
-- kylo-service-app
-- %%
-- Copyright (C) 2017 ThinkBig Analytics
-- %%
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- #L%
-- -
/**
Get the health of the feed merging the Check data job health into the correct feed for summarizing the counts
 */
CREATE OR REPLACE VIEW BATCH_FEED_SUMMARY_COUNTS_VW AS
  SELECT f.FEED_ID as FEED_ID,f.FEED_NAME as FEED_NAME,
  count(e2.JOB_EXECUTION_ID) as ALL_COUNT,
  count(case when e2.status <>'ABANDONED' AND (e2.status = 'FAILED' or e2.EXIT_CODE = 'FAILED') then 1 else null end) as FAILED_COUNT,
  count(case when e2.status <>'ABANDONED' AND (e2.EXIT_CODE = 'COMPLETED') then 1 else null end) as COMPLETED_COUNT,
  count(case when e2.status = 'ABANDONED'then 1 else null end) as ABANDONED_COUNT,
  count(case when e2.status IN('STARTING','STARTED')then 1 else null end) as RUNNING_COUNT
  FROM   BATCH_JOB_EXECUTION e2
  INNER JOIN BATCH_JOB_INSTANCE i on i.JOB_INSTANCE_ID = e2.JOB_INSTANCE_ID
  INNER JOIN CHECK_DATA_TO_FEED_VW f on f.KYLO_FEED_ID = i.FEED_ID
  group by f.feed_id, f.feed_name;


text:
BitcoinUnits::BitcoinUnits(QObject *parent):
        QAbstractListModel(parent),
        unitlist(availableUnits())
{
}

QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
    QList<BitcoinUnits::Unit> unitlist;
    unitlist.append(BTC);
    unitlist.append(mBTC);
    unitlist.append(uBTC);
    return unitlist;
}

bool BitcoinUnits::valid(int unit)
{
    switch(unit)
    {
    case BTC:
    case mBTC:
    case uBTC:
        return true;
    default:
        return false;
    }
}

QString BitcoinUnits::name(int unit)
{
    switch(unit)
    {
    case BTC: return QString("SCC");
    case mBTC: return QString("mSCC");
    case uBTC: return QString::fromUtf8("μSCC");
    default: return QString("???");
    }
}

QString BitcoinUnits::description(int unit)
{
    switch(unit)
    {
    case BTC: return QString("Scicoins");
    case mBTC: return QString("Milli-Scicoins (1 / 1,000)");
    case uBTC: return QString("Micro-Scicoins (1 / 1,000,000)");
    default: return QString("???");
    }
}

mpq BitcoinUnits::factor(int unit)
{
    switch(unit)
    {
    case BTC:  return mpq("100000000/1");
    case mBTC: return mpq("100000/1");
    case uBTC: return mpq("100/1");
    default:   return mpq("100000000/1");
    }
}

int BitcoinUnits::amountDigits(int unit)
{
    switch(unit)
    {
    case BTC: return 8; // 21,000,000 (# digits, without commas)
    case mBTC: return 11; // 21,000,000,000
    case uBTC: return 14; // 21,000,000,000,000
    default: return 0;
    }
}

int BitcoinUnits::decimals(int unit)
{
    switch(unit)
    {
    case BTC: return 8;
    case mBTC: return 5;
    case uBTC: return 2;
    default: return 0;
    }
}

QString BitcoinUnits::format(int unit, const mpq& n, bool fPlus)
{
    // Note: not using straight sprintf here because we do NOT want
    // localized number formatting.
    if(!valid(unit))
        return QString(); // Refuse to format invalid unit
    mpq q = n * COIN / factor(unit);
    std::string str = FormatMoney(q, fPlus);
    int diff = 8 - decimals(unit);
    if(diff > 0)
        str.erase(str.length() - diff, diff);
    return QString::fromStdString(str);
}

QString BitcoinUnits::formatWithUnit(int unit, const mpq& amount, bool plussign)
{
    return format(unit, amount, plussign) + QString(" ") + name(unit);
}

bool BitcoinUnits::parse(int unit, const QString &value, mpq *val_out)
{
    mpq ret_value;
    if (!ParseMoney(value.toStdString(), ret_value))
        return false;
    if(val_out)
    {
        *val_out = ret_value * factor(unit) / COIN;
    }
    return true;
}

int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return unitlist.size();
}

QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
    int row = index.row();
    if(row >= 0 && row < unitlist.size())
    {
        Unit unit = unitlist.at(row);
        switch(role)
        {
        case Qt::EditRole:
        case Qt::DisplayRole:
            return QVariant(name(unit));
        case Qt::ToolTipRole:
            return QVariant(description(unit));
        case UnitRole:
            return QVariant(static_cast<int>(unit));
        }
    }
    return QVariant();
}


text:
define(['aeris/util'], function(_) {
  /**
   * Follows HTML5 Postion object specification,
   * except for the latLon property, which uses the aeris-standard format.
   *
   * Some position properties may be unavailable - if using
   * a IP location service, for example. In this case, their
   * values will be {null}.
   *
   * @param {Object} position Gelocated position.
   * @publicApi
   * @class aeris.geolocate.results.GeolocatePosition
   * @constructor
   */
  var GeolocatePosition = function(position) {
    _.defaults(position, {
      latLon: null,
      altitude: null,
      altitudeAccuracy: null,
      accuracy: null,
      heading: null,
      speed: null,
      timestamp: null
    });

    /**
     * @property {aeris.maps.LatLon} latLon
     */

    /**
     * @property {number|null} altitude
     */

    /**
     * @property {number|null} altitudeAccuracy
     */

    /**
     * @property {number|null} accuracy
     */

    /**
     * @property {number|null} heading
     */

    /**
     * @property {number|null} speed
     */

    /**
     * @property {Date|null} timestamp
     */

    return position;
  };

  return GeolocatePosition;
});


text:
<?php defined('_JEXEC') or die('Restricted access');

$product = $viewData['product'];

if ($viewData['showRating']) {
	$maxrating = VmConfig::get('vm_maximum_rating_scale', 5);
	if (empty($product->rating)) {
	?>
		<div class="ratingbox dummy" title="<?php echo vmText::_('COM_VIRTUEMART_UNRATED'); ?>" >

	<?php
	} else {
		$ratingwidth = $product->rating * 24;
  ?>

<div title=" <?php echo (vmText::_("COM_VIRTUEMART_RATING_TITLE") . round($product->rating) . '/' . $maxrating) ?>" class="ratingbox" >
  <div class="stars-orange" style="width:<?php echo $ratingwidth.'px'; ?>">

	<?php
	}
}


text:
package org.openkilda.integration.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.json.simple.JSONObject;
import org.openkilda.helper.RestClientManager;
import org.openkilda.integration.converter.IslLinkConverter;
import org.openkilda.integration.converter.PortConverter;
import org.openkilda.integration.exception.ContentNotFoundException;
import org.openkilda.integration.exception.IntegrationException;
import org.openkilda.integration.model.response.IslLink;
import org.openkilda.model.IslLinkInfo;
import org.openkilda.model.PortInfo;
import org.openkilda.model.SwitchInfo;
import org.openkilda.service.ApplicationService;
import org.openkilda.utility.ApplicationProperties;
import org.openkilda.utility.CollectionUtil;
import org.openkilda.utility.IoUtil;
import org.openkilda.utility.JsonUtil;

/**
 * The Class SwitchIntegrationService.
 *
 * @author Gaurav Chugh
 */
@Service
public class SwitchIntegrationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SwitchIntegrationService.class);

    @Autowired
    private RestClientManager restClientManager;

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private IslLinkConverter islLinkConverter;

    /**
     * Gets the switches.
     *
     * @return the switches
     * @throws IntegrationException
     */
    public List<SwitchInfo> getSwitches() {
        HttpResponse response = restClientManager.invoke(applicationProperties.getSwitches(),
                HttpMethod.GET, "", "", applicationService.getAuthHeader());
        if (RestClientManager.isValidResponse(response)) {
            List<SwitchInfo> switchesResponse =
                    restClientManager.getResponseList(response, SwitchInfo.class);
            return getSwitchInfoSetName(switchesResponse);
        }
        return null;
    }

    /**
     * Gets the SwitchInfoSetName.
     *
     * @return the switches
     * @throws IntegrationException
     */
    private List<SwitchInfo> getSwitchInfoSetName(List<SwitchInfo> switches) {

        LOGGER.info("Inside getSwitchInfoSetName : Start");
        if (switches != null && !StringUtils.isEmpty(switches)) {

            Map<String, String> csNames = getCustomSwitchNameFromFile();

            for (SwitchInfo switchInfo : switches) {
                switchInfo.setName(customSwitchName(csNames, switchInfo.getSwitchId()));
            }
        }
        return switches;
    }

    /**
     * This Method is used to set custom Switch name.
     *
     * @param csNames
     * @param switchId
     * @return
     */
    public String customSwitchName(Map<String, String> csNames, String switchId) {
        if (csNames != null && !StringUtils.isEmpty(csNames) && csNames.size() > 0) {
            if (csNames.containsKey(switchId.toLowerCase())
                    || csNames.containsKey(switchId.toUpperCase())) {
                if (!IoUtil.chkStringIsNotEmpty(csNames.get(switchId))) {
                    return switchId;
                } else {
                    return csNames.get(switchId);
                }
            } else {
                return switchId;
            }
        } else
            return switchId;
    }

    /**
     * Gets the isl links.
     *
     * @return the isl links
     */
    public List<IslLinkInfo> getIslLinks() {
        HttpResponse response = restClientManager.invoke(applicationProperties.getLinks(),
                HttpMethod.GET, "", "", applicationService.getAuthHeader());
        if (RestClientManager.isValidResponse(response)) {
            List<IslLink> links = restClientManager.getResponseList(response, IslLink.class);
            if (CollectionUtil.isEmpty(links)) {
                throw new ContentNotFoundException();
            }
            return islLinkConverter.toIslLinksInfo(links);
        }
        return null;
    }

    /**
     * Gets the switch ports.
     *
     * @return the switch ports
     * @throws IntegrationException
     */
    public List<PortInfo> getSwitchPorts(final String switchId) throws IntegrationException {
        try {
            HttpResponse response = restClientManager.invoke(applicationProperties.getSwitchPorts(),
                    HttpMethod.GET, "", "", "");
            if (RestClientManager.isValidResponse(response)) {
                String responseEntity = IoUtil.toString(response.getEntity().getContent());
                JSONObject jsonObject = JsonUtil.toObject(responseEntity, JSONObject.class);
                return PortConverter.toPortsInfo(jsonObject, switchId);
            }
        } catch (IOException exception) {
            LOGGER.error("Exception in getSwitchPorts " + exception.getMessage(), exception);
            throw new IntegrationException(exception);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public Map<String, String> getCustomSwitchNameFromFile() {
        Map<String, String> csNames = new HashMap<String, String>();

        InputStream inputStream = null;
        String data = null;
        try {
            inputStream = new URL(applicationProperties.getSwitchDataFilePath()).openStream();
            if (inputStream != null) {
                data = IoUtil.toString(inputStream);

                if (data != null && !StringUtils.isEmpty(data)) {
                    csNames = JsonUtil.toObject(data, HashMap.class);
                }
            }
        } catch (Exception ex) {
            LOGGER.error("Inside getCustomSwitchNameFromFile unable to find switch file path Exception :",
                    ex);
        }
        return csNames;

    }
}


text:
module BABYLON {
    class SkyMaterialDefines extends MaterialDefines {
        public CLIPPLANE = false;
        public POINTSIZE = false;
        public FOG = false;
        public VERTEXCOLOR = false;
        public VERTEXALPHA = false;

        constructor() {
            super();
            this.rebuild();
        }
    }

    export class SkyMaterial extends PushMaterial {
        // Public members
        @serialize()
        public luminance: number = 1.0;

        @serialize()
		public turbidity: number = 10.0;

        @serialize()
		public rayleigh: number = 2.0;

        @serialize()
        public mieCoefficient: number = 0.005;

        @serialize()
        public mieDirectionalG: number = 0.8;

        @serialize()
        public distance: number = 500;

        @serialize()
        public inclination: number = 0.49;

        @serialize()
        public azimuth: number = 0.25;

        @serializeAsVector3()
        public sunPosition: Vector3 = new Vector3(0, 100, 0);

        @serialize()
        public useSunPosition: boolean = false;

        // Private members
        private _cameraPosition: Vector3 = Vector3.Zero();

        private _renderId: number;

        constructor(name: string, scene: Scene) {
            super(name, scene);
        }

        public needAlphaBlending(): boolean {
            return (this.alpha < 1.0);
        }

        public needAlphaTesting(): boolean {
            return false;
        }

        public getAlphaTestTexture(): Nullable<BaseTexture> {
            return null;
        }

        // Methods
        public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
            if (this.isFrozen) {
                if (this._wasPreviouslyReady && subMesh.effect) {
                    return true;
                }
            }

            if (!subMesh._materialDefines) {
                subMesh._materialDefines = new SkyMaterialDefines();
            }

            var defines = <SkyMaterialDefines>subMesh._materialDefines;
            var scene = this.getScene();

            if (!this.checkReadyOnEveryCall && subMesh.effect) {
                if (this._renderId === scene.getRenderId()) {
                    return true;
                }
            }

            MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);

            // Attribs
            MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, false);

            // Get correct effect
            if (defines.isDirty) {
                defines.markAsProcessed();

                scene.resetCachedMaterial();

                // Fallbacks
                var fallbacks = new EffectFallbacks();
                if (defines.FOG) {
                    fallbacks.addFallback(1, "FOG");
                }

                //Attributes
                var attribs = [VertexBuffer.PositionKind];

                if (defines.VERTEXCOLOR) {
                    attribs.push(VertexBuffer.ColorKind);
                }

                var shaderName = "sky";

                var join = defines.toString();
                subMesh.setEffect(scene.getEngine().createEffect(shaderName,
                    attribs,
                    ["world", "viewProjection", "view",
                        "vFogInfos", "vFogColor", "pointSize", "vClipPlane",
                        "luminance", "turbidity", "rayleigh", "mieCoefficient", "mieDirectionalG", "sunPosition",
                        "cameraPosition"
                    ],
                    [],
                    join, fallbacks, this.onCompiled, this.onError), defines);
            }

            if (!subMesh.effect || !subMesh.effect.isReady()) {
                return false;
            }

            this._renderId = scene.getRenderId();
            this._wasPreviouslyReady = true;

            return true;
        }

        public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
            var scene = this.getScene();

            var defines = <SkyMaterialDefines>subMesh._materialDefines;
            if (!defines) {
                return;
            }

            var effect = subMesh.effect;
            if (!effect) {
                return;
            }
            this._activeEffect = effect;

            // Matrices
            this.bindOnlyWorldMatrix(world);
            this._activeEffect.setMatrix("viewProjection", scene.getTransformMatrix());

            if (this._mustRebind(scene, effect)) {
                // Clip plane
                if (scene.clipPlane) {
                    var clipPlane = scene.clipPlane;
                    this._activeEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
                }

                // Point size
                if (this.pointsCloud) {
                    this._activeEffect.setFloat("pointSize", this.pointSize);
                }
            }

            // View
            if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
                this._activeEffect.setMatrix("view", scene.getViewMatrix());
            }

            // Fog
            MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);

            // Sky
            var camera = scene.activeCamera;
            if (camera) {
                var cameraWorldMatrix = camera.getWorldMatrix();
                this._cameraPosition.x = cameraWorldMatrix.m[12];
                this._cameraPosition.y = cameraWorldMatrix.m[13];
                this._cameraPosition.z = cameraWorldMatrix.m[14];
                this._activeEffect.setVector3("cameraPosition", this._cameraPosition);
            }

            if (this.luminance > 0) {
                this._activeEffect.setFloat("luminance", this.luminance);
            }

			this._activeEffect.setFloat("turbidity", this.turbidity);
			this._activeEffect.setFloat("rayleigh", this.rayleigh);
			this._activeEffect.setFloat("mieCoefficient", this.mieCoefficient);
			this._activeEffect.setFloat("mieDirectionalG", this.mieDirectionalG);

            if (!this.useSunPosition) {
                var theta = Math.PI * (this.inclination - 0.5);
                var phi = 2 * Math.PI * (this.azimuth - 0.5);

                this.sunPosition.x = this.distance * Math.cos(phi);
                this.sunPosition.y = this.distance * Math.sin(phi) * Math.sin(theta);
                this.sunPosition.z = this.distance * Math.sin(phi) * Math.cos(theta);
            }

			this._activeEffect.setVector3("sunPosition", this.sunPosition);

            this._afterBind(mesh, this._activeEffect);
        }

        public getAnimatables(): IAnimatable[] {
            return [];
        }

        public dispose(forceDisposeEffect?: boolean): void {
            super.dispose(forceDisposeEffect);
        }

        public clone(name: string): SkyMaterial {
            return SerializationHelper.Clone<SkyMaterial>(() => new SkyMaterial(name, this.getScene()), this);
        }

        public serialize(): any {
            var serializationObject = SerializationHelper.Serialize(this);
            serializationObject.customType  = "BABYLON.SkyMaterial";
            return serializationObject;
        }

        public getClassName(): string {
            return "SkyMaterial";
        }

        // Statics
        public static Parse(source: any, scene: Scene, rootUrl: string): SkyMaterial {
            return SerializationHelper.Parse(() => new SkyMaterial(source.name, scene), source, scene, rootUrl);
        }
    }
}


text:
package create

import (
	"github.com/spf13/cobra"

	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
	"k8s.io/kubernetes/pkg/kubectl/genericclioptions/printers"
	"k8s.io/kubernetes/pkg/kubectl/scheme"
)

// CreateSubcommandOptions is an options struct to support create subcommands
type CreateSubcommandOptions struct {
	genericclioptions.IOStreams

	// PrintFlags holds options necessary for obtaining a printer
	PrintFlags *genericclioptions.PrintFlags
	// Name of resource being created
	Name string
	// DryRun is true if the command should be simulated but not run against the server
	DryRun bool

	Namespace        string
	EnforceNamespace bool

	Printer printers.ResourcePrinter
}

func NewCreateSubcommandOptions(ioStreams genericclioptions.IOStreams) *CreateSubcommandOptions {
	return &CreateSubcommandOptions{
		PrintFlags: genericclioptions.NewPrintFlags("created").WithTypeSetter(scheme.Scheme),
		IOStreams:  ioStreams,
	}
}

func (o *CreateSubcommandOptions) Complete(f genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error {
	name, err := NameFromCommandArgs(cmd, args)
	if err != nil {
		return err
	}

	o.Name = name
	o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
	if err != nil {
		return err
	}

	o.DryRun = cmdutil.GetDryRunFlag(cmd)
	if o.DryRun {
		o.PrintFlags.Complete("%s (dry run)")
	}
	o.Printer, err = o.PrintFlags.ToPrinter()
	if err != nil {
		return err
	}

	return nil
}

// NameFromCommandArgs is a utility function for commands that assume the first argument is a resource name
func NameFromCommandArgs(cmd *cobra.Command, args []string) (string, error) {
	argsLen := cmd.ArgsLenAtDash()
	// ArgsLenAtDash returns -1 when -- was not specified
	if argsLen == -1 {
		argsLen = len(args)
	}
	if argsLen != 1 {
		return "", cmdutil.UsageErrorf(cmd, "exactly one NAME is required, got %d", argsLen)
	}
	return args[0], nil

}


text:
<?php

namespace App;

use SleepingOwl\Admin\Columns\Interfaces\ColumnInterface;

class YesNoColumn implements ColumnInterface
{

    public function renderHeader()
    {
        return 'Yes/no	';
    }

    public function render($instance, $totalCount)
    {
        $content = ($instance->bool) ? 'yes' : 'no';
        return '' . $content . '	';
    }

    public function getName()
    {
        return 'columng-name';
    }

    public function isHidden()
    {
        // return false to display this column
        // return true to hide this column (used for column appendants)
        return false;
    }

    public function myCustomMethod()
    {

    }

}


text:
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}

-- | This module builds Docker (OpenContainer) images.
module Stack.Image
       (stageContainerImageArtifacts, createContainerImageFromStage,
        imgCmdName, imgDockerCmdName, imgOptsFromMonoid,
        imgDockerOptsFromMonoid, imgOptsParser, imgDockerOptsParser)
       where

import           Control.Applicative
import           Control.Exception.Lifted hiding (finally)
import           Control.Monad
import           Control.Monad.Catch hiding (bracket)
import           Control.Monad.IO.Class
import           Control.Monad.Logger
import           Control.Monad.Reader
import           Control.Monad.Trans.Control
import           Data.Char (toLower)
import qualified Data.Map.Strict as Map
import           Data.Maybe
import           Data.Monoid
import qualified Data.Text as T
import           Data.Typeable
import           Options.Applicative
import           Path
import           Path.Extra
import           Path.IO
import           Stack.Constants
import           Stack.Types
import           Stack.Types.Internal
import           System.Process

type Build e m = (HasBuildConfig e, HasConfig e, HasEnvConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadReader e m)

type Assemble e m = (HasConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadMask m, MonadReader e m)

-- | Stages the executables & additional content in a staging
-- directory under '.stack-work'
stageContainerImageArtifacts :: Build e m
                             => m ()
stageContainerImageArtifacts = do
    imageDir <- imageStagingDir <$> getWorkingDir
    removeTreeIfExists imageDir
    createTree imageDir
    stageExesInDir imageDir
    syncAddContentToDir imageDir

-- | Builds a Docker (OpenContainer) image extending the `base` image
-- specified in the project's stack.yaml.  Then new image will be
-- extended with an ENTRYPOINT specified for each `entrypoint` listed
-- in the config file.
createContainerImageFromStage :: Assemble e m
                              => m ()
createContainerImageFromStage = do
    imageDir <- imageStagingDir <$> getWorkingDir
    createDockerImage imageDir
    extendDockerImageWithEntrypoint imageDir

-- | Stage all the Package executables in the usr/local/bin
-- subdirectory of a temp directory.
stageExesInDir :: Build e m => Path Abs Dir -> m ()
stageExesInDir dir = do
    srcBinPath <-
        (</> $(mkRelDir "bin")) <$>
        installationRootLocal
    let destBinPath = dir </>
            $(mkRelDir "usr/local/bin")
    createTree destBinPath
    copyDirectoryRecursive srcBinPath destBinPath

-- | Add any additional files into the temp directory, respecting the
-- (Source, Destination) mapping.
syncAddContentToDir :: Build e m => Path Abs Dir -> m ()
syncAddContentToDir dir = do
    config <- asks getConfig
    bconfig <- asks getBuildConfig
    let imgAdd = maybe Map.empty imgDockerAdd (imgDocker (configImage config))
    forM_
        (Map.toList imgAdd)
        (\(source,dest) ->
              do sourcePath <- parseRelDir source
                 destPath <- parseAbsDir dest
                 let destFullPath = dir </> dropRoot destPath
                 createTree destFullPath
                 copyDirectoryRecursive
                     (bcRoot bconfig </> sourcePath)
                     destFullPath)

-- | Derive an image name from the project directory.
imageName :: Path Abs Dir -> String
imageName = map toLower . toFilePathNoTrailingSep . dirname

-- | Create a general purpose docker image from the temporary
-- directory of executables & static content.
createDockerImage :: Assemble e m => Path Abs Dir -> m ()
createDockerImage dir = do
    config <- asks getConfig
    let dockerConfig = imgDocker (configImage config)
    case imgDockerBase =<< dockerConfig of
        Nothing -> throwM StackImageDockerBaseUnspecifiedException
        Just base -> do
            liftIO
                (do writeFile
                        (toFilePath
                             (dir </>
                              $(mkRelFile "Dockerfile")))
                        (unlines ["FROM " ++ base, "ADD ./ /"])
                    callProcess
                        "docker"
                        [ "build"
                        , "-t"
                        , fromMaybe
                              (imageName (parent (parent dir)))
                              (imgDockerImageName =<< dockerConfig)
                        , toFilePath dir])

-- | Extend the general purpose docker image with entrypoints (if
-- specified).
extendDockerImageWithEntrypoint :: Assemble e m => Path Abs Dir -> m ()
extendDockerImageWithEntrypoint dir = do
    config <- asks getConfig
    let dockerConfig = imgDocker (configImage config)
    let dockerImageName = fromMaybe
                (imageName (parent (parent dir)))
                (imgDockerImageName =<< dockerConfig)
    let imgEntrypoints = maybe Nothing imgDockerEntrypoints dockerConfig
    case imgEntrypoints of
        Nothing -> return ()
        Just eps -> do
            forM_
                eps
                (\ep ->
                      liftIO
                          (do writeFile
                                  (toFilePath
                                       (dir </>
                                        $(mkRelFile "Dockerfile")))
                                  (unlines
                                       [ "FROM " ++ dockerImageName
                                       , "ENTRYPOINT [\"/usr/local/bin/" ++
                                         ep ++ "\"]"
                                       , "CMD []"])
                              callProcess
                                  "docker"
                                  [ "build"
                                  , "-t"
                                  , dockerImageName ++ "-" ++ ep
                                  , toFilePath dir]))

-- | The command name for dealing with images.
imgCmdName :: String
imgCmdName = "image"

-- | The command name for building a docker container.
imgDockerCmdName :: String
imgDockerCmdName = "container"

-- | A parser for ImageOptsMonoid.
imgOptsParser :: Parser ImageOptsMonoid
imgOptsParser = ImageOptsMonoid <$>
    optional
        (subparser
             (command
                  imgDockerCmdName
                  (info
                       imgDockerOptsParser
                       (progDesc "Create a container image (EXPERIMENTAL)"))))

-- | A parser for ImageDockerOptsMonoid.
imgDockerOptsParser :: Parser ImageDockerOptsMonoid
imgDockerOptsParser = ImageDockerOptsMonoid <$>
    optional
        (option
             str
             (long (imgDockerCmdName ++ "-" ++ T.unpack imgDockerBaseArgName) <>
              metavar "NAME" <>
              help "Docker base image name")) <*>
    pure Nothing <*>
    pure Nothing <*>
    pure Nothing

-- | Convert image opts monoid to image options.
imgOptsFromMonoid :: ImageOptsMonoid -> ImageOpts
imgOptsFromMonoid ImageOptsMonoid{..} = ImageOpts
    { imgDocker = imgDockerOptsFromMonoid <$> imgMonoidDocker
    }

-- | Convert Docker image opts monoid to Docker image options.
imgDockerOptsFromMonoid :: ImageDockerOptsMonoid -> ImageDockerOpts
imgDockerOptsFromMonoid ImageDockerOptsMonoid{..} = ImageDockerOpts
    { imgDockerBase = emptyToNothing imgDockerMonoidBase
    , imgDockerEntrypoints = emptyToNothing imgDockerMonoidEntrypoints
    , imgDockerAdd = fromMaybe Map.empty imgDockerMonoidAdd
    , imgDockerImageName = emptyToNothing imgDockerMonoidImageName
    }
    where emptyToNothing Nothing = Nothing
          emptyToNothing (Just s)
              | null s =
                  Nothing
              | otherwise =
                  Just s

-- | Stack image exceptions.
data StackImageException =
    StackImageDockerBaseUnspecifiedException
    deriving (Typeable)

instance Exception StackImageException

instance Show StackImageException where
    show StackImageDockerBaseUnspecifiedException = "You must specify a base docker image on which to place your haskell executables."


text:
"""The totalconnect component."""

from datetime import timedelta
import logging

from total_connect_client.client import TotalConnectClient
from total_connect_client.exceptions import AuthenticationError, TotalConnectError

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import CONF_USERCODES, DOMAIN

PLATFORMS = [Platform.ALARM_CONTROL_PANEL, Platform.BINARY_SENSOR]

CONFIG_SCHEMA = cv.removed(DOMAIN, raise_if_present=False)
SCAN_INTERVAL = timedelta(seconds=30)
_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up upon config entry in user interface."""
    conf = entry.data
    username = conf[CONF_USERNAME]
    password = conf[CONF_PASSWORD]

    if CONF_USERCODES not in conf:
        # should only happen for those who used UI before we added usercodes
        raise ConfigEntryAuthFailed("No usercodes in TotalConnect configuration")

    temp_codes = conf[CONF_USERCODES]
    usercodes = {int(code): temp_codes[code] for code in temp_codes}

    try:
        client = await hass.async_add_executor_job(
            TotalConnectClient, username, password, usercodes
        )
    except AuthenticationError as exception:
        raise ConfigEntryAuthFailed("TotalConnect authentication failed") from exception

    coordinator = TotalConnectDataUpdateCoordinator(hass, client)
    await coordinator.async_config_entry_first_refresh()

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = coordinator
    hass.config_entries.async_setup_platforms(entry, PLATFORMS)
    return True

async def async_unload_entry(hass, entry: ConfigEntry):
    """Unload a config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)

    return unload_ok

class TotalConnectDataUpdateCoordinator(DataUpdateCoordinator):
    """Class to fetch data from TotalConnect."""

    def __init__(self, hass: HomeAssistant, client):
        """Initialize."""
        self.hass = hass
        self.client = client
        super().__init__(
            hass, logger=_LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL
        )

    async def _async_update_data(self):
        """Update data."""
        await self.hass.async_add_executor_job(self.sync_update_data)

    def sync_update_data(self):
        """Fetch synchronous data from TotalConnect."""
        try:
            for location_id in self.client.locations:
                self.client.locations[location_id].get_panel_meta_data()
        except AuthenticationError as exception:
            # should only encounter if password changes during operation
            raise ConfigEntryAuthFailed(
                "TotalConnect authentication failed"
            ) from exception
        except TotalConnectError as exception:
            raise UpdateFailed(exception) from exception
        except ValueError as exception:
            raise UpdateFailed("Unknown state from TotalConnect") from exception


text:
package de.mrapp.android.adapter;

import androidx.annotation.NonNull;

import java.io.Serializable;

/**
 * Defines the interface, a class, which should support filtering by using regular expressions, must
 * implement.
 *
 * @author Michael Rapp
 * @since 0.1.0
 */
public interface Filterable extends Serializable {

    /**
     * Returns, whether the class does match a specific query, or not.
     *
     * @param query
     *         The query, as a {@link String}. The query may not be null
     * @param flags
     *         Optional flags as an {@link Integer} value or 0, if no flags should be used
     * @return True, if the class does match the given query, false otherwise
     */
    boolean match(@NonNull String query, final int flags);

}


text: pub mod messages;


text:
module EmberCli
  module Assets
    VERSION = "0.6.2"
  end
end


text:
package templates

const (
	KubeAPIClusterRole = `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: proxy-clusterrole-kubeapiserver
rules:
- apiGroups: [""]
  resources:
  - nodes/metrics
  - nodes/proxy
  - nodes/stats
  - nodes/log
  - nodes/spec
  verbs: ["get", "list", "watch", "create"]`
	KubeAPIClusterRoleBinding = `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: proxy-role-binding-kubernetes-master
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: proxy-clusterrole-kubeapiserver
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: kube-apiserver`
	SystemNodeClusterRoleBinding = `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "false"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: system:node
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:node
subjects:
- kind: Group
  name: system:nodes
  apiGroup: rbac.authorization.k8s.io`

	JobDeployerServiceAccount = `
apiVersion: v1
kind: ServiceAccount
metadata:
  name: rke-job-deployer
  namespace: kube-system`

	JobDeployerClusterRoleBinding = `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: job-deployer
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  namespace: kube-system
  name: rke-job-deployer`

	DefaultPodSecurityPolicy = `
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: default-psp
  annotations:
    seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*'
spec:
  privileged: true
  allowPrivilegeEscalation: true
  allowedCapabilities:
  - '*'
  volumes:
  - '*'
  hostNetwork: true
  hostPorts:
  - min: 0
    max: 65535
  hostIPC: true
  hostPID: true
  runAsUser:
    rule: 'RunAsAny'
  seLinux:
    rule: 'RunAsAny'
  supplementalGroups:
    rule: 'RunAsAny'
  fsGroup:
    rule: 'RunAsAny'`

	DefaultPodSecurityRole = `
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: default-psp-role
rules:
- apiGroups: ['extensions']
  resources: ['podsecuritypolicies']
  verbs:     ['use']
  resourceNames:
  - default-psp`

	DefaultPodSecurityRoleBinding = `
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: default-psp-rolebinding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: default-psp-role
subjects:
# Authorize all service accounts in a namespace:
- kind: Group
  apiGroup: rbac.authorization.k8s.io
  name: system:serviceaccounts
# Or equivalently, all authenticated users in a namespace:
- kind: Group
  apiGroup: rbac.authorization.k8s.io
  name: system:authenticated

`
)


text:
package java.io;

public class FileInputStream
  extends InputStream  implements Closeable
{
  // Constructors

  @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "FileInputStream-1", pos = {0, 1}, report = "-")
  public FileInputStream(File arg1) throws FileNotFoundException{
    super();
  }
  @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "FileInputStream-2", pos = {0, 1}, report = "-")
  public FileInputStream(FileDescriptor arg1){
    super();
  }
  @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "FileInputStream-3", pos = {0, 1}, report = "-")
  public FileInputStream(java.lang.String arg1) throws FileNotFoundException{
    super();
  }
  // Methods

  protected void finalize() throws IOException{
  }
  public void close() throws IOException{
  }
  public int read() throws IOException{
    return 0;
  }
  public int read(byte [] arg1, int arg2, int arg3) throws IOException{
    return 0;
  }
  public int available() throws IOException{
    return 0;
  }
  public java.nio.channels.FileChannel getChannel(){
    return (java.nio.channels.FileChannel) null;
  }
  @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "FileInputStream.getFD", pos = {0, -1}, report = "-")
  public final FileDescriptor getFD() throws IOException{
    return (FileDescriptor) null;
  }
  public long skip(long arg1) throws IOException{
    return 0l;
  }
}


text:
.. _examples_overview:

Overview of Examples
====================

The examples give an overview of the features of WAMP by providing working code.

Read, run, and modify as you like!

There are two main sources of examples:

* the `Autobahn|Python repository <https://github.com/crossbario/autobahn-python/tree/master/examples>`_ - for an overview see the `Autobahn|Python documentation <http://autobahn.ws/python/wamp/examples.html>`_
* the `Crossbar.io examples repository <https://github.com/crossbario/crossbarexamples>`_ - for an overview see `the Crossbar.io documentation <http://crossbar.io/docs/Examples/>`_

.. note:: The JavaScript code provided generally runs both in the browser and in Node.js. When using the browser, load the JavaScript via the provided HTML page. Each example also contains Python versions. Python and JavaScript versions are interoperable: You may run e.g. a JavaScript subscriber and a Python publisher.

Running examples
----------------

All examples require a WAMP router.

We suggest using `Crossbar.io <http://crossbar.io>`_, an open source WAMP application router.

For the installation of Crossbar.io, see the `project documentation <http://crossbar.io/docs/Quick-Start/>`_.

Examples from the Autobahn|Python repo
++++++++++++++++++++++++++++++++++++++

Once you've installed Crossbar.io, open a command shell, create a test directory, initialize Crossbar.io and start it.

::

   mkdir test1
   cd test 1
   crossbar init
   crossbar start

Code runs both in the browser and in Node.js.

For the latter, you need to have |ab| installed. To do so, in a shell do

::

   npm install autobahn
   npm install when

Examples from the crossbarexamples repo
+++++++++++++++++++++++++++++++++++++++

The examples here all include a Crossbar.io configuration for the example.

So do

::

   crossbar start

in the example directory and then open a Web browser to 'localhost:8080'.