text:
<?php

require_once("OAuthError.class.php");
require_once("OAuthException.class.php");
require_once("OAuthResponse.class.php");
require_once("common/ErrorHandler.class.php");

class OAuthProvider {

	// Used to check if timestamp is recentish.
	protected $timestampThreshold = 300; // 5 mins in seconds
	protected $version = "1.0";
	protected $signatureMethods = array();
	protected $ds; // data store
	private $request;

	const TOKEN_EXPIR_NEVER = -1;

	/**
	 * Constructor.
	 *
	 * @param OAuthRequest $request
	 * @param string $requestToCheck (consumer | authorize | request | access)
	 * @throws OAuthException
	 */
	public function __construct(&$request, $requestToCheck) {
		$this->request = $request;

		try {
			// Check required parameters according to the oauth step.
			$tokenType = $this->checkOAuthRequest($requestToCheck);

			// The data store is smart enough to know how to fill its fields
			// (request_token or access_token) with the values given in the
			// request.

			$oauthParams = $request->getParameters();
			$this->ds = new OAuthDataStore($oauthParams, $tokenType);

			// In the API consumption step is checked if the user has granted
			// the access to the consumer application.

			if ($requestToCheck == "access")
				$this->isConsumerAllowed();

		} catch (DbException $e) {
			$this->dbErrorHandler($e);
		}
	}

	/**
	 * Check every OAuth request according to the OAuth step being executed.
	 * Return the token type.
	 *
	 * @param unknown_type $requestToCheck
	 * @throws OAuthException
	 * @return string (null | request | access)
	 */
	private function checkOAuthRequest($requestToCheck) {
		switch ($requestToCheck) {

		case "consumer":
			// 1st step: consumer credential is checked.
			$this->checkConsumerRequest();
			break;

		case "authorize":
			// 2nd step: Check if temporary credential (oauth_token) exists
			// and request the user to aprove the access for the consumer
			// app.
			$this->checkAuthorizationRequest();

			// Check if the user has approved the third app access.
			$this->checkUserPermission();

			break;

		case "request":
			// 3rd oauth step: in the access token step, the temporary
			// credential is checked.
			$this->checkTokenRequest();
			return "request";

		case "access":
			// last step: in the resource consumption step, the access
			// token credential is checked.
			$this->checkAccessRequest();
			return "access";

		default:
			throw new OAuthException(OAuthError::ERROR_UNKNOWN, 500,
				"OAuth step unknown.");
		}

		return null;
	}

	/**
	 * Throw an exception according to the exception code.
	 *
	 * @param OAuthException $e
	 * @throws OAuthException
	 */
	private static function dbErrorHandler($e) {
		switch ($e->getCode()) {

		case OAuthDataStore::ERR_NO_CONSUMER:
			// The consumer key and secret don't exist in the db. This problem
			// might be caused due to the developer didn't generate the
			// consumer credential.
			throw new OAuthException(OAuthError::CONSUMER_KEY_UNKNOWN, 400,
				"Consumer not registered.");

		case OAuthDataStore::ERR_NO_AUTHORIZED_CONSUMER:
			throw new OAuthException(OAuthError::PERMISSION_DENIED, 401,
				"Consumer not authorized.");

		case OAuthDataStore::ERR_NO_TOKEN:
			// The token doesn't exist in the db.
			throw new OAuthException(OAuthError::TOKEN_REJECTED, 400,
				$e->getMessage());

		case OAuthDataStore::ERR_NO_CALLBACK:
			// The request token is invalid, so the callback url can't be
			// retrieved.
			throw new OAuthException(OAuthError::TOKEN_REJECTED, 400,
				"The request token key is invalid.");

		default:
			throw new OAuthException(OAuthError::DB_ERROR, 500, $e->getMessage());
		}
	}

	/**
	 * Add a signature method.
	 *
	 * @param OAuthSignatureMethod $signatureMethod
	 */
	public function addSignatureMethod($signatureMethod) {
		$this->signatureMethods[$signatureMethod->getName()] = $signatureMethod;
	}

	/**
	 * Process a request_token request.
	 *
	 * @return OAuthToken
	 */
	public function fetchRequestToken() {
		$this->getVersion();
		$consumer = $this->getConsumer();

		// No token required for the initial token request.
		$this->checkSignature(null);

		// Rev A change.
		$callback = $this->request->getParameter("oauth_callback");
		$newToken = $this->newRequestToken($consumer, $callback);

		// Insert the nonce for the first time.
		$this->ds->insertNonce(
			$this->request->getParameter("oauth_nonce"),
			$newToken->key,
			$consumer->key);

		return $newToken;
	}

	/**
	 * Process an access_token request.
	 *
	 * @return OAuthToken
	 */
	public function fetchAccessToken() {
		$this->getVersion();
		$consumer = $this->getConsumer();

		// Compare the request token with the one stored in the db.
		$token = $this->getToken("request");

		// Build the signature based on the oauth params and compare it with
		// oauth_signature value.
		$this->checkSignature($token);

		// Rev A change
		$verifier = $this->request->getParameter("oauth_verifier");
		$newToken = $this->newAccessToken($token, $consumer, $verifier);

		return $newToken;
	}

	/**
	 *
	 * @param OAuthConsumer $consumer
	 * @param string $callback
	 */
	private function newRequestToken($consumer, $callback) {
		return $this->ds->newRequestToken($consumer, $callback);
	}

	/**
	 *
	 * @param OAuthToken $token
	 * @param OAuthConsumer $consumer
	 * @param string $verifier
	 */
	private function newAccessToken($token, $consumer, $verifier) {
		return $this->ds->newAccessToken($token, $consumer, $verifier);
	}

	/**
	 * This method is used only to check the temporary and access credentials,
	 * (access token and API consumption steps). It can't be used in the
	 * request token and authorization steps.
	 *
	 * @param string $tokenType
	 * @throws OAuthException
	 */
	public function verifyRequest($tokenType = "access") {
		$this->getVersion();
		$consumer = $this->getConsumer();
		$token = $this->getToken($tokenType);
		$this->checkSignature($token);

		switch ($tokenType) {
		case "request":
			// In the access token step, the temporary credential is checked. As
			// the user is redirected to the callback in the authorization step, it
			// has to be checked also the verifier code.
			if (!$this->checkVerifier())
				throw new OAuthException(OAuthError::VERIFIER_INVALID);
			break;

		case "access":
			// In the API consumption step, the access token's expiration is
			// checked.
			if ($this->isTokenExpired($token))
				throw new OAuthException(OAuthError::TOKEN_EXPIRED, 401);
			break;
		}
	}

	/**
	 * Check if the given token has expired.
	 *
	 * @param OAuthToken $token
	 * @return boolean
	 */
	private function isTokenExpired($token) {
		if ($token->expiration == self::TOKEN_EXPIR_NEVER)
			return false;

		return (time() > $token->expiration) ? true : false;
	}

	/**
	 * Check required parameters in the request token step.
	 *
	 * @throws OAuthException
	 * @return boolean
	 */
	public function checkConsumerRequest() {
		$requiredParams = array(
			"oauth_consumer_key",
			"oauth_signature_method",
			"oauth_signature",
			"oauth_timestamp",
			"oauth_nonce",
			"oauth_callback");

		OAuthProvider::checkRequiredParams($this->request, $requiredParams);
	}

	/**
	 * Check required parameters in the authorization oauth step.
	 *
	 * @throws OAuthException
	 */
	public function checkAuthorizationRequest() {
		$params = $this->request->getParameters();

		if (!array_key_exists("oauth_token", $params)) {
			throw new OAuthException(OAuthError::PARAMETER_ABSENT, 400,
				"oauth_token is a required parameter.", "oauth_token");
		}

		$oauth_token = $this->request->getParameter("oauth_token");
		if (!$oauth_token) {
			throw new OAuthException(OAuthError::PARAMETER_ABSENT, 400,
				"oauth_token is a required parameter.", "oauth_token");
		}
	}

	/**
	 * Check the required parameters in the access token request step.
	 *
	 * @throws OAuthException
	 * @return boolean
	 */
	public function checkTokenRequest() {
		$requiredParams = array(
			"oauth_consumer_key",
			"oauth_token",
			"oauth_signature_method",
			"oauth_signature",
			"oauth_timestamp",
			"oauth_nonce",
			"oauth_verifier");

		OAuthProvider::checkRequiredParams($this->request, $requiredParams);
	}

	/**
	 * Check the required parameters each time the provider gets a resource
	 * consumption request.
	 *
	 * @throws OAuthException
	 * @return boolean
	 */
	public function checkAccessRequest() {
		$requiredParams = array(
			"oauth_consumer_key",
			"oauth_token",
			"oauth_signature_method",
			"oauth_signature",
			"oauth_timestamp",
			"oauth_nonce");

		OAuthProvider::checkRequiredParams($this->request, $requiredParams);
	}

	/**
	 * Check the required oauth parameters. If anyone has an emtpy value or is
	 * missing, an exception is thrown.
	 *
	 * @param OAuthRequest $request
	 * @param array $requiredParams
	 * @throws OAuthException
	 * @return boolean
	 */
	private function checkRequiredParams($request, $requiredParams) {
		$params = $request->getParameters();

		// Look for an emtpy required parameter to throw an exception.
		foreach ($params as $k => $v) {
			if ($v)
				continue;

			if (in_array($k, $requiredParams)) {
				throw new OAuthException(OAuthError::PARAMETER_ABSENT, 400,
					"{$k} is a required parameter.", $k);
			}
		}

		// Look for a missing required param.
		foreach ($requiredParams as $k) {
			if (!array_key_exists($k, $params)) {
				throw new OAuthException(OAuthError::PARAMETER_ABSENT, 400,
					"{$k} is a required parameter.", $k);
			}
		}
	}

	/**
	 * Sends the response to the consumer (require pecl_http to work).
	 *
	 * @param OAuthResponse $response
	 * @param string $responseType
	 */
	public static function sendResponse($response, $responseType = "request") {
		$message = ($responseType == "request")
			? $response->getRequestTokenResp()
			: $response->getAccessTokenResp();

		HttpResponse::status(200);
		HttpResponse::setContentType("application/x-www-form-urlencoded");
		HttpResponse::setData($message);
		HttpResponse::send();
	}

	/**
	 * Sends the response to the consumer (require pecl_http to work).
	 *
	 * @param string $response
	 * @param integer $statusCode
	 */
	public static function reportProblem($response, $statusCode = 400) {
		HttpResponse::status($statusCode);
		HttpResponse::setContentType("application/x-www-form-urlencoded");
		HttpResponse::setData($response);
		HttpResponse::send();
	}

	/**
	 * Get the oauth version.
	 *
	 * @throws OAuthException
	 * @return string
	 */
	private function getVersion() {
		$version = $this->request->getParameter("oauth_version");

		if (!$version) {
			// Service Providers MUST assume the protocol version to be 1.0 if
			// this parameter is not present.
			// Chapter 7.0 ("Accessing Protected Ressources")
			$version = "1.0";
		}

		if ($version !== $this->version) {
			// Throw an exception with the oauth problem to be sent to
			// the consumer application.
			throw new OAuthException(OAuthError::VERSION_REJECTED, 400,
				"Invalid oauth version.", "1.0");
		}

		return $version;
	}

	/**
	 * Figure out the signature with some defaults.
	 *
	 * @throws OAuthException
	 * @return OAuthSignatureMethod
	 */
	private function getSignatureMethod() {
		$signatureMethod =
			$this->request->getParameter("oauth_signature_method");

		if (!in_array($signatureMethod,
			array_keys($this->signatureMethods)))
		{
			$oauthErrText =
				"Signature method '$signatureMethod' not supported, " .
				"try one of the following: " .
				implode(", ", array_keys($this->signatureMethods));

			throw new OAuthException(OAuthError::SIGNATURE_METHOD_REJECTED,
				400, $oauthErrText);
		}
		return $this->signatureMethods[$signatureMethod];
	}

	/**
	 * Try to find the consumer for the provided request's consumer key.
	 *
	 * @throws OAuthException
	 * @return OAuthConsumer
	 */
	private function getConsumer() {
		// Compare the given consumer key with the one stored in the db.
		$consumerKey = $this->request->getParameter("oauth_consumer_key");
		$consumer = $this->ds->lookupConsumer($consumerKey);

		if (!$consumer) {
			throw new OAuthException(OAuthError::CONSUMER_KEY_UNKNOWN, 400,
				"Invalid consumer.");
		}

		return $consumer;
	}

	/**
	 * Try to find the token for the provided request's token key.
	 *
	 * @param string $tokenType
	 * @throws OAuthException
	 * @return OAuthToken
	 */
	private function getToken($tokenType = "access") {
		// Compare the given consumer key with the one stored in the db.
		$oauthToken = $this->request->getParameter("oauth_token");
		$consumer = $this->getConsumer();
		$token = $this->ds->lookupToken($consumer, $tokenType, $oauthToken);

		if (!$token) {
			throw new OAuthException(OAuthError::TOKEN_EXPIRED, 400,
				"Invalid {$tokenType} token: {$tokenField}");
		}
		return $token;
	}

	/**
	 * All-in-one function to check the signature on a request.
	 * Should guess the signature method appropriately.
	 *
	 * @param OAuthToken $token
	 * @throws OAuthException
	 */
	private function checkSignature($token) {
		// Retrieve the parameters to check the signature.
		$timestamp = $this->request->getParameter("oauth_timestamp");
		$nonce = $this->request->getParameter("oauth_nonce");
		$consumer = $this->getConsumer();

		$this->checkTimestamp($timestamp);
		$this->checkNonce($consumer, $token, $nonce, $timestamp);

		$signatureMethod = $this->getSignatureMethod();
		$signature = $this->request->getParameter("oauth_signature");

		$validSig = $signatureMethod->checkSignature(
			$this->request,
			$consumer,
			$token,
			$signature);

		if (!$validSig) {
			throw new OAuthException(OAuthError::SIGNATURE_INVALID, 401,
				"Invalid signature.");
		}
	}

	/**
	 * Check that the timestamp is new enough.
	 *
	 * @param string timestamp
	 * @throws OAuthException
	 */
	private function checkTimestamp($timestamp) {
		// Verify that timestamp is recentish.
	    $now = time();
	    if (abs($now - $timestamp) > $this->timestampThreshold) {
			throw new OAuthException(OAuthError::TIMESTAMP_REFUSED, 400,
				"Expired timestamp, yours {$timestamp}, ours {$now}");
		}
	}

	/**
	 * Check that the nonce is not repeated.
	 *
	 * @param OAuthConsumer $consumer
	 * @param OAuthToken $token
	 * @param string $nonce
	 * @param string $timestamp
	 * @throws OAuthException
	 */
	private function checkNonce($consumer, $token, $nonce, $timestamp) {
		// If it's the request token step, the nonce is not checked.
		if ($token == null) {
			return;
		}

		// Verify that the nonce is uniqueish.
		$found = $this->ds->lookupNonce(
			$consumer,
			$token,
			$nonce,
			$timestamp);

		if ($found) {
			throw new OAuthException(OAuthError::NONCE_USED, 400,
				"Nonce already used.");
		}
	}

	/**
	 * Generate and store a verifier code.
	 *
	 * @return string
	 */
	public function generateVerifier() {
		// Generate the verification code.
		$verifier = OAuthUtil::generateVerifier();

		// Put the verification code in the db.
		$tokenKey = $this->request->getParameter("oauth_token");
		$this->ds->insertVerifier($verifier, $tokenKey);

		return $verifier;
	}

	/**
	 * Retrieve the callback URL for a consumer.
	 *
	 * @throws OAuthException
	 * @return string
	 */
	public function getCallbackUrl() {
		try {
			$tokenKey = $this->request->getParameter("oauth_token");
			$consumerKey = $this->request->getParameter("oauth_consumer_key");

			return $this->ds->getCallbackUrl($tokenKey, $consumerKey);

		} catch (DbException $e) {
			throw new OAuthException(OAuthError::TOKEN_REJECTED, 400,
				"The request token key is invalid.");
		}
	}

	/**
	 * Redirect the consumer to the callback URL.
	 *
	 * @param string $callback
	 * @param string $verifier
	 */
	public function redirectConsumer($callback, $verifier) {
		header("Location: " . $callback .
			"?oauth_token=" . $this->request->getParameter("oauth_token") .
			"&oauth_verifier=" . $verifier);
		exit();
	}

	/**
	 * Check the verifier code.
	 * @return boolean
	 */
	private function checkVerifier() {
		try {
			$verifier = $this->ds->getVerifier(
				$this->request->getParameter("oauth_token"),
				$this->request->getParameter("oauth_consumer_key")
			);
		} catch (DbException $e) {
			return false;
		}

		return ($this->request->getParameter("oauth_verifier") == $verifier)
			? true : false;
	}

	/**
	 * Redirect the browser to a given url. It could be set a message to send
	 * as GET parameter.
	 *
	 * @param string $url
	 * @param string $msg
	 */
	public static function redirect($url, $msg) {
		header("Location: " . $url . $msg);
		exit();
	}

	/**
	 * Check if the user has granted the access to the consumer app, if not,
	 * it redirects the user to an error page.
	 *
	 * @param integer $userId
	 * @throws OAuthException
	 */
	private function checkUserPermission($userId = 0) {

		$action = @$this->request->getParameter("action");
		if (!$action)
			throw new OAuthException(OAuthError::PERMISSION_UNKNOWN, 401,
				"Third party application not authorized.");

		if ($action != "ALLOW")
			throw new OAuthException(OAuthError::PERMISSION_DENIED, 401,
				"The access to the third party application has been denied.");

		$tokenKey = @$this->request->getParameter("oauth_token");
		if (!$tokenKey) {
			throw new OAuthException(OAuthError::TOKEN_REJECTED, 401,
				"Missing request token key.");
		}

		// It might be: days, weeks, months or 'for ever'.
		$tokExpirUnit = @$this->request->getParameter("tok_expir_unit");

		// Token expiration time.
		$tokExpir = @$this->request->getParameter("tok_expir");

		try {
			// If this method is executed, it means that the user has granted
			// the access to the consumer app, so 'allowed' field is set to
			// true.
			$ds = new OAuthDataStore();

			// Retrieve the user id from user_sessions table giving the
			// session id.
			// Comment: What is this? why use a php session in a stateless REST architecture?
			$userId = $ds->getUserId(session_id());

			// Allow the consumer application for the userId.
			// Set the token expiration time that will be used for the access token.
			$ds->setAllowed($tokenKey, "true", $userId, $tokExpir, $tokExpirUnit);

		} catch (DbException $e) {
			throw new OAuthException(OAuthError::DB_ERROR, 500, $e->getMessage());
		}
	}

	/**
	 * Check if the consumer app has been approved to consume resources.
	 *
	 * @throws OAuthException
	 */
	public function isConsumerAllowed() {
		$tokenKey = $this->request->getParameter("oauth_token");
		$consumerKey = $this->request->getParameter("oauth_consumer_key");

		if (!$this->ds->getAllowed($tokenKey, $consumerKey)) {
			throw new OAuthException(OAuthError::PERMISSION_DENIED, 401);
		}
	}

	/**
	 * Get the user id.
	 * @return The userID
	 * @throws OAuthException
	 */
	public function getUserID() {

		$tokenKey = $this->request->getParameter("oauth_token");
		$consumerKey = $this->request->getParameter("oauth_consumer_key");

		if ($userID = $this->ds->getValidUserID($tokenKey, $consumerKey))
			return $userID;
		else
			throw new OAuthException(OAuthError::PERMISSION_DENIED, 401);

	}

}

?>


text:
package com.stuffwithstuff.magpie.interpreter;

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

import com.stuffwithstuff.magpie.ast.Field;
import com.stuffwithstuff.magpie.intrinsic.ClassNew;

public class EnvironmentBuilder {
  public EnvironmentBuilder(Interpreter interpreter) {
    mInterpreter = interpreter;
    mModule = mInterpreter.getBaseModule();
  }

  public ClassObj createClassClass() {
    Scope scope = mModule.getScope();

    // The class of all classes. Its class is itself.
    // TODO(bob): Doc.
    ClassObj classObj = new ClassObj(null, Name.CLASS, null,
        new HashMap<String, FieldObj>(), "");
    classObj.bindClass(classObj);
    scope.define(false, Name.CLASS, classObj);

    return classObj;
  }

  public void initialize() {
    // Create the default new() method for creating objects.
    Scope scope = mModule.getScope();
    Callable newMethod = new ClassNew(scope);
    scope.define("new", newMethod);

    ClassObj iterable = class_("Iterable").end();
    ClassObj indexable = class_("Indexable", iterable).end();
    ClassObj comparable = class_("Comparable").end();

    class_("Array", indexable).end();
    class_("Bool").end();
    class_("Int", comparable).end();
    class_("Function").end();
    class_("List", indexable).end();
    class_("Nothing").end();
    class_("Record").end();
    class_("String", comparable, indexable).end();
    class_("Tuple", indexable).end();

    // Define the core error classes.
    ClassObj error = class_("Error").end();

    class_(Name.AMBIGUOUS_METHOD_ERROR, error).end();
    class_(Name.ARGUMENT_ERROR, error).end();
    // TODO(bob): Move into io module.
    class_(Name.IO_ERROR, error).end();
    class_(Name.NO_MATCH_ERROR, error).end();
    class_(Name.NO_METHOD_ERROR, error).end();
    class_(Name.NO_VARIABLE_ERROR, error).end();
    class_(Name.OUT_OF_BOUNDS_ERROR, error).end();
    class_(Name.PARENT_COLLISION_ERROR, error).end();
    class_(Name.PARSE_ERROR, error).end();
    class_(Name.REDEFINITION_ERROR, error).end();
    class_(Name.INITIALIZATION_ERROR, error).end();
  }

  private ClassBuilder class_(String name, ClassObj... parents) {
    return new ClassBuilder(name, parents);
  }

  private class ClassBuilder {
    public ClassBuilder(String name, ClassObj... parents) {
      mName = name;
      mParents = parents;
    }

    public ClassObj end() {
      // TODO(bob): Doc.
      ClassObj classObj = mInterpreter.createClass(mName,
          Arrays.asList(mParents), mFields, mModule.getScope(), "");
      mModule.getScope().define(false, mName, classObj);

      return classObj;
    }

    private final String mName;
    private final ClassObj[] mParents;
    private final Map<String, Field> mFields = new HashMap<String, Field>();
  }

  private final Interpreter mInterpreter;
  private final Module mModule;
}

redpajama_set_name: RedPajamaGithub


text:
package com.linecorp.armeria.internal.common.logging;

import java.util.function.Function;

import org.slf4j.Logger;

import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.common.RequestHeaders;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.common.logging.LogLevel;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.common.logging.RequestOnlyLog;
import com.linecorp.armeria.common.util.SafeCloseable;

/**
 * Utilities for logging decorators.
 */
public final class LoggingDecorators {
    private static final String REQUEST_FORMAT = "{} Request: {}";
    private static final String RESPONSE_FORMAT = "{} Response: {}";
    private static final String RESPONSE_FORMAT2 = "{} Response: {}, cause: {}";

    private LoggingDecorators() {}

    /**
     * Logs a stringified request of {@link RequestLog}.
     */
    public static void logRequest(
            Logger logger, RequestOnlyLog log,
            Function<? super RequestOnlyLog, LogLevel> requestLogLevelMapper,
            Function<? super RequestHeaders, ?> requestHeadersSanitizer,
            Function<Object, ?> requestContentSanitizer,
            Function<? super HttpHeaders, ?> requestTrailersSanitizer) {

        final LogLevel requestLogLevel = requestLogLevelMapper.apply(log);
        if (requestLogLevel.isEnabled(logger)) {
            final RequestContext ctx = log.context();
            final String requestStr = log.toStringRequestOnly(requestHeadersSanitizer,
                                                              requestContentSanitizer,
                                                              requestTrailersSanitizer);
            try (SafeCloseable ignored = ctx.push()) {
                requestLogLevel.log(logger, REQUEST_FORMAT, ctx, requestStr);
            }
        }
    }

    /**
     * Logs a stringified response of {@link RequestLog}.
     */
    public static void logResponse(
            Logger logger, RequestLog log,
            Function<? super RequestLog, LogLevel> requestLogLevelMapper,
            Function<? super RequestLog, LogLevel> responseLogLevelMapper,
            Function<? super RequestHeaders, ?> requestHeadersSanitizer,
            Function<Object, ?> requestContentSanitizer,
            Function<? super HttpHeaders, ?> requestTrailersSanitizer,
            Function<? super ResponseHeaders, ?> responseHeadersSanitizer,
            Function<Object, ?> responseContentSanitizer,
            Function<? super HttpHeaders, ?> responseTrailersSanitizer,
            Function<? super Throwable, ?> responseCauseSanitizer) {
        final LogLevel responseLogLevel = responseLogLevelMapper.apply(log);
        final Throwable responseCause = log.responseCause();

        if (responseLogLevel.isEnabled(logger)) {
            final RequestContext ctx = log.context();
            final String responseStr = log.toStringResponseOnly(responseHeadersSanitizer,
                                                                responseContentSanitizer,
                                                                responseTrailersSanitizer);
            try (SafeCloseable ignored = ctx.push()) {
                if (responseCause == null) {
                    responseLogLevel.log(logger, RESPONSE_FORMAT, ctx, responseStr);
                    return;
                }

                final LogLevel requestLogLevel = requestLogLevelMapper.apply(log);
                if (!requestLogLevel.isEnabled(logger)) {
                    // Request wasn't logged, but this is an unsuccessful response,
                    // so we log the request too to help debugging.
                    responseLogLevel.log(logger, REQUEST_FORMAT, ctx,
                                         log.toStringRequestOnly(requestHeadersSanitizer,
                                                                 requestContentSanitizer,
                                                                 requestTrailersSanitizer));
                }

                final Object sanitizedResponseCause = responseCauseSanitizer.apply(responseCause);
                if (sanitizedResponseCause == null) {
                    responseLogLevel.log(logger, RESPONSE_FORMAT, ctx, responseStr);
                    return;
                }

                if (sanitizedResponseCause instanceof Throwable) {
                    responseLogLevel.log(logger, RESPONSE_FORMAT, ctx,
                                         responseStr, sanitizedResponseCause);
                } else {
                    responseLogLevel.log(logger, RESPONSE_FORMAT2, ctx,
                                         responseStr, sanitizedResponseCause);
                }
            }
        }
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Nauva.CSS.Helpers where

import           Data.Text (Text)
import qualified Data.Text as T

import           Control.Monad.Writer.Lazy

import           Nauva.CSS.Types

vh :: Int -> CSSValue
vh n = CSSValue $ T.pack $ show n ++ "vh"

px :: (Show a) => a -> CSSValue
px n = CSSValue $ T.pack $ show n ++ "px"

rem :: (Show a) => a -> CSSValue
rem n = CSSValue $ T.pack $ show n ++ "rem"

pct :: (Show a) => a -> CSSValue
pct n = CSSValue $ T.pack $ show n ++ "%"

fontFamily_ :: Writer [CSSDeclaration] () -> Writer [Statement] ()
fontFamily_ v = tell [SEmit $ DFontFamily $ execWriter v]

before :: Writer [Statement] () -> Writer [Statement] ()
before style = tell [SSuffix "::before" style]

after :: Writer [Statement] () -> Writer [Statement] ()
after style = tell [SSuffix "::after" style]

onHover :: Writer [Statement] () -> Writer [Statement] ()
onHover style = tell [SSuffix ":hover" style]

onActive :: Writer [Statement] () -> Writer [Statement] ()
onActive style = tell [SSuffix ":active" style]

firstChild :: Writer [Statement] () -> Writer [Statement] ()
firstChild style = tell [SSuffix ":first-child" style]

lastChild :: Writer [Statement] () -> Writer [Statement] ()
lastChild style = tell [SSuffix ":last-child" style]

media :: Text -> Writer [Statement] () -> Writer [Statement] ()
media m style = tell [SCondition (CMedia m) style]


text:
This is an final assignment submitted for a Computer Graphics class at the University of Adelaide in 2017, involving myself (jkortman) and another student (jthughes). It uses OpenGL 3.3 and C++11.

A video of the program can be found [here](https://www.youtube.com/watch?v=TNU_dsAG1ac).

Features
---
It's mostly a mess of half-finished ideas, but does contain a number of complete and interesting features:
 - Cel shaded objects and terrain
 - Simultaneous directional, point, and spot light sources
 - OBJ file loading
 - Procedurally generated day/night skybox textures
 - Exponential fog used for depth cues (subtle)
 - Yellow tint nearby sun to imitate light scattering
 - Reflective water
 - Dynamic shadow mapping that changes with the sun position
 - Procedurally generated 3D landscape
 - Ambient occlusion (SSAO)

Compile & run instructions
---
To compile and start the program: `make all && ./assignment3_part2`
Has only really been tested on MaxOS Sierra and Ubuntu (not certain of the version).

Exploring the program:
 - The mouse is used to control the camera direction.
 - W, A, S, and D are used to move forward, left, down, and right respectively.
 - SHIFT and SPACE are used to move up and down respectively.
 - ALT is used to increase movement speed.
 - O is used to start a demo flythrough of the landscape.
 - ESC is used to exit the program.


text:
Installs the [Prometheus Adapter](https://github.com/DirectXMan12/k8s-prometheus-adapter) for the Custom Metrics API. Custom metrics are used in Kubernetes by [Horizontal Pod Autoscalers](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) to scale workloads based upon your own metric pulled from an external metrics provider like Prometheus. This chart complements the [metrics-server](https://github.com/helm/charts/tree/master/stable/metrics-server) chart that provides resource only metrics.

## Prerequisites

Kubernetes 1.9+

## Installing the Chart

To install the chart with the release name `my-release`:

```console
$ helm install --name my-release stable/prometheus-adapter
```

This command deploys the prometheus adapter with the default configuration. The [configuration](#configuration) section lists the parameters that can be configured during installation.

## Using the Chart

To use the chart, ensure the `prometheus.url` and `prometheus.port` are configured with the correct Prometheus service endpoint. Additionally, the chart comes with a set of default rules out of the box but they may pull in too many metrics or not map them correctly for your needs. Therefore, it is recommended to populate `rules.custom` with a list of rules (see the [config document](https://github.com/DirectXMan12/k8s-prometheus-adapter/blob/master/docs/config.md) for the proper format). Finally, to configure your Horizontal Pod Autoscaler to use the custom metric, see the custom metrics section of the [HPA walkthrough](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/#autoscaling-on-multiple-metrics-and-custom-metrics).

## Uninstalling the Chart

To uninstall/delete the `my-release` deployment:

```console
$ helm delete my-release
```

The command removes all the Kubernetes components associated with the chart and deletes the release.

## Configuration

The following table lists the configurable parameters of the Prometheus Adapter chart and their default values.

| Parameter                       | Description                                                                     | Default                                     |
| ------------------------------- | ------------------------------------------------------------------------------- | --------------------------------------------|
| `affinity`                      | Node affinity                                                                   | `{}`                                        |
| `image.repository`              | Image repository                                                                | `directxman12/k8s-prometheus-adapter-amd64` |
| `image.tag`                     | Image tag                                                                       | `v0.2.1`                                    |
| `image.pullPolicy`              | Image pull policy                                                               | `IfNotPresent`                              |
| `logLevel`                      | Log level                                                                       | `4`                                         |
| `metricsRelistInterval`         | Interval at which to re-list the set of all available metrics from Prometheus   | `30s`                                       |
| `nodeSelector`                  | Node labels for pod assignment                                                  | `{}`                                        |
| `prometheus.url`                | Url of where we can find the Prometheus service                                 | `http://prometheus.default.svc`             |
| `prometheus.port`               | Port of where we can find the Prometheus service                                | `9090`                                      |
| `rbac.create`                   | If true, create & use RBAC resources                                            | `true`                                      |
| `resources`                     | CPU/Memory resource requests/limits                                             | `{}`                                        |
| `rules.default`                 | If `true`, enable a set of default rules in the configmap                       | `true`                                      |
| `rules.custom`                  | A list of custom configmap rules                                                | `[]`                                        |
| `service.annotations`           | Annotations to add to the service                                               | `{}`                                        |
| `service.port`                  | Service port to expose                                                          | `443`                                       |
| `service.type`                  | Type of service to create                                                       | `ClusterIP`                                 |
| `serviceAccount.create`         | If true, create & use Serviceaccount                                            | `true`                                      |
| `serviceAccount.name`           | If not set and create is true, a name is generated using the fullname template  | ``                                          |
| `tls.enable`                    | If true, use the provided certificates. If false, generate self-signed certs    | `false`                                     |
| `tls.ca`                        | Public CA file that signed the APIService (ignored if tls.enable=false)         | ``                                          |
| `tls.key`                       | Private key of the APIService (ignored if tls.enable=false)                     | ``                                          |
| `tls.certificate`               | Public key of the APIService (ignored if tls.enable=false)                      | ``                                          |
| `tolerations`                   | List of node taints to tolerate                                                 | `[]`                                        |

Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example,

```console
$ helm install --name my-release \
  --set logLevel=1 \
 stable/prometheus-adapter
```

Alternatively, a YAML file that specifies the values for the above parameters can be provided while installing the chart. For example,

```console
$ helm install --name my-release -f values.yaml stable/prometheus-adapter
```


text:
RobotJ GenericObjectFunctions::<BIG>MouseClick</BIG>

RJ

<short_desc xmlns="">
                A single click on an object by mouse event. It uses low level mouse event to click on an object.
              </short_desc>

<detailed_desc xmlns="">

                By default, mouse click on the center of the component.
                We can also mouse click on any part of an object, or any point relative to an object
                based on a provided x,y coordinate or other component-specific parameters.

                The object to be mouse clicked is first given context and then a mouse click is
                generated at the coordinates.  Thus, a subitem or object can be
                referenced by name even though it is only recognized via coordinates.

                The coordinate lookup is done with the component name of the record AND
                Field #5 or by providing the literal text of the coordinates, where supported.

                Typical Data Table records:

                (1) t MainWindow MainWindow  MouseClick

                (2) t MainWindow MainWindow  MouseClick AnObject

                (3) t MainWindow FolderTree  MouseClick Node1

                (4) t MainWindow MainWindow  MouseClick "50,200"

                (5) t MainWindow MainWindow  MouseClick "Coords=50,200"

                #2 above will contain an AnObject="3,10" entry in the MainWindow section
                of the Application Map to mouse click at x=3, y=10 in the MainWindow.

                #3 above will contain a FolderTree entry in the MainWindow section with
                normal recognition information for it.  FolderTree will also have it's
                own section in the Application Map in which there will be an entry like
                Node1="15,30".  This will tell Robot to locate the FolderTree Generic
                object and mouse click at the coordinates specified by the reference.

                #4 and #5 above show using literal text instead of an App Map entry to specify
                where to mouse click relative to the item.

                Rational Robot no longer requires the AppMapSubKey be provided and will
                attempt to use the string as literal text if no AppMapSubKey is found in
                the current App Map.  Robot also no longer assumes the AppMapSubKey value
                or the literal value is presenting coordinate information.  This allows
                components that can accept parameters other than coordinates, like table
                row/col values or ImageMap areas to be specified.

                If the value is deduced to contain coordinates, but is not prefixed with
                "Coords=" text, then Robot will add the prefix.  Otherwise, the text value
                will remain unmodified.

		This is the direction we expect all tools to follow going forward.

		Engines should also attempt to support coordinates separated by alternate separators.
		The most common separators that should be supported would be:

"," (comma) Example: "50,200"

";" (semi-colon) Example: "50;200"

" " (space) Example: "50 200"

</detailed_desc>

Fields: [ ]=Optional with Default Value

[ AppMapSubkey =  ]

<short_desc xmlns="">
                (Optional)Name of the AppMap subkey to lookup or the literal text to use for the click.
              </short_desc>

<detailed_desc xmlns="">
                Without this we should click on the center of the object.

Name of the AppMap subkey to lookup and use for the click.
                We expect the AppMap or literal text to contain the item in the format "x,y":

                [FolderTree]
                Node1="33,120"      OR
                Node1="Coords=33,120"
                ...
                [AnHTMLImage]
                AMappdedRegion=Coords=10,10
                ANamedRegion=AreaName=TechSupport
                AnIndexedRegion=AreaIndex=2
                AnotherRegion=AreaID=Contact

                The results from the lookup are appended to the "Coords=" string
                used by the MouseClick command in Robot (only if necessary).  So any
                valid content used with the MouseClick command can be part of
                this AppMap entry.

                Both Fields #3 and #5 are used to locate the item in the App Map.
                This routine does not specify an App Map so only the current Map
                is used and it is expected to be valid.

                The Rational Robot implementation also supports using literal text in
                this parameter instead of an AppMapSubKey.  If the value retrieved from
                this field is NOT found to exist in the App Map as a Sub Key then it
                will be used as literal text as if it HAD been retrieved from the App Map.

				Engines should also attempt to support coordinates separated by alternate separators.
				The most common separators that should be supported would be:

"," (comma) Example: "50,200"

";" (semi-colon) Example: "50;200"

" " (space) Example: "50 200"

</detailed_desc>

Examples:

<usage xmlns="">T, WINDOW, COMPONENT, MOUSECLICK</usage>

<short_desc xmlns="">
               A single mouse click on the center of the object.
              </short_desc>

<detailed_desc xmlns="">
               A single click on the center of the object.
              </detailed_desc>

<usage xmlns="">T, WINDOW, WINDOW, MOUSECLICK, AnObject</usage>

<short_desc xmlns="">
               A single mouse click will be performed at a x,y coordinate indicated by the AnObject reference in
               the Application Map.
              </short_desc>

<detailed_desc xmlns="">
               Field  5 : TQ String. A reference identified in the Application Map identifying coordinates
               on which to click
               This example shows AnObject which will be found in the Application Map as a referenced item
               in the WINDOW section.
              </detailed_desc>

<usage xmlns="">T, WINDOW, AnObject, MOUSECLICK, ASubObject</usage>

<short_desc xmlns="">
               A single mouse click will be performed at a x,y coordinate indicated by the ASubObject reference in
               the Application Map.
              </short_desc>

<detailed_desc xmlns="">
               Field  5 : TQ String. A reference identified in the Application Map identifying coordinates
               on which to click
               This example shows AnObject as a viable object in the WINDOW but that it also has its own
               section in the Application Map which contains one or more named references like
               ASubObject which are used for test.
              </detailed_desc>

<usage xmlns="">T, WINDOW, AnObject, MOUSECLICK, 10;20</usage>

<short_desc xmlns="">
               A single mouse click will be performed at coordinate 10,20 in the object.
              </short_desc>

<detailed_desc xmlns="">
               Field  5 : TQ String. The item does not exist in the app map so will be
               treated as literal text.  Note we allow semi-colon delimited coordinates
               to support the case when commas are used as field delimiters and cannot be
               used to delimit the X and Y coordinates.
              </detailed_desc>

<usage xmlns="">T, WINDOW, AnObject, MOUSECLICK, "Coords=10;20"</usage>

<short_desc xmlns="">
               A single mouse click will be performed at coordinate 10,20 in the object.
              </short_desc>

<detailed_desc xmlns="">
               Field  5 : TQ String. The item does not exist in the app map so will be
               treated as literal text.  Note we allow semi-colon delimited coordinates
               to support the case when commas are used as field delimiters and cannot be
               used to delimit the X and Y coordinates.
              </detailed_desc>

[How To Read This Reference]


text:
$(document).ready(function () {
    $(window).load(function () {
        GetResources();
    });
    $(window).scroll(function () {
        if (($(window).scrollTop() + 1) >= ($(document).height() - $(window).height())) {
            GetResources();
        };
    });
});

var oldResourcesDivHeight = $('#resourcesDiv').height();

function GetResources() {
    $.ajax({
        type: 'POST',
        url: '/storage/show-additional-content',
        data: { path: window.location.pathname, resourseRenderCount: $(".element-container").length },
        dataType: "html",
        success: function (result) {
            var domElement = $(result);
            $('#resourcesDiv').append(domElement);
            if ($(document).height() == $(window).height() && oldResourcesDivHeight != $('#resourcesDiv').height()) {
                GetResources();
                oldResourcesDivHeight = $('#resourcesDiv').height();
            };

            recalculateResourseHeight();
        }
    });
};


text:
import base64
import confluent.config.configmanager as cfm
import confluent.collective.manager as collective
import confluent.util as util
import eventlet.green.subprocess as subprocess
import eventlet
import glob
import os
import shutil
import tempfile

agent_pid = None
ready_keys = {}
_sshver = None

def sshver():
    global _sshver
    if _sshver is None:
        p = subprocess.Popen(['ssh', '-V'], stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        _, output = p.communicate()
        _sshver = float(output.split()[0].split(b'_')[1].split(b'p')[0])
    return _sshver

def normalize_uid():
    curruid = os.geteuid()
    neededuid = os.stat('/etc/confluent').st_uid
    if curruid != neededuid:
        os.seteuid(neededuid)
    if os.geteuid() != neededuid:
        raise Exception('Need to run as root or owner of /etc/confluent')
    return curruid

agent_starting = False
def assure_agent():
    global agent_starting
    global agent_pid
    while agent_starting:
        eventlet.sleep(0.1)
    if agent_pid is None:
        try:
            agent_starting = True
            sai = util.run(['ssh-agent'])[0]
            for line in sai.split(b'\n'):
                if b';' not in line:
                    continue
                line, _ = line.split(b';', 1)
                if b'=' not in line:
                    continue
                k, v = line.split(b'=', 1)
                if not isinstance(k, str):
                    k = k.decode('utf8')
                    v = v.decode('utf8')
                if k == 'SSH_AGENT_PID':
                    agent_pid = v
                os.environ[k] = v
        finally:
            agent_starting = False
    return True

def get_passphrase():
    if sshver() <= 7.6:
        return ''
    # convert the master key to base64
    # for use in ssh passphrase context
    if cfm._masterkey is None:
        cfm.init_masterkey()
    phrase = base64.b64encode(cfm._masterkey)
    if not isinstance(phrase, str):
        phrase = phrase.decode('utf8')
    return phrase

class AlreadyExists(Exception):
    pass

def initialize_ca():
    ouid = normalize_uid()
    # if already there, skip, make warning
    myname = collective.get_myname()
    if os.path.exists('/etc/confluent/ssh/ca.pub'):
        cafilename = '/var/lib/confluent/public/site/ssh/{0}.ca'.format(myname)
        shutil.copy('/etc/confluent/ssh/ca.pub', cafilename)
        os.seteuid(ouid)
        raise AlreadyExists()
    try:
        os.makedirs('/etc/confluent/ssh', mode=0o700)
    except OSError as e:
        if e.errno != 17:
            raise
    finally:
        os.seteuid(ouid)
    comment = '{0} SSH CA'.format(myname)
    subprocess.check_call(
        ['ssh-keygen', '-C', comment, '-t', 'ed25519', '-f',
         '/etc/confluent/ssh/ca', '-N', get_passphrase()],
         preexec_fn=normalize_uid)
    ouid = normalize_uid()
    try:
        os.makedirs('/var/lib/confluent/public/site/ssh/', mode=0o755)
    except OSError as e:
        if e.errno != 17:
            raise
    finally:
        os.seteuid(ouid)
    cafilename = '/var/lib/confluent/public/site/ssh/{0}.ca'.format(myname)
    shutil.copy('/etc/confluent/ssh/ca.pub', cafilename)
    #    newent = '@cert-authority * ' + capub.read()

adding_key = False
def prep_ssh_key(keyname):
    global adding_key
    while adding_key:
        eventlet.sleep(0.1)
    adding_key = True
    if keyname in ready_keys:
        adding_key = False
        return
    if not assure_agent():
        ready_keys[keyname] = 1
        adding_key = False
        return
    tmpdir = tempfile.mkdtemp()
    try:
        askpass = os.path.join(tmpdir, 'askpass.sh')
        with open(askpass, 'w') as ap:
            ap.write('#!/bin/sh\necho $CONFLUENT_SSH_PASSPHRASE\nrm {0}\n'.format(askpass))
        os.chmod(askpass, 0o700)
        os.environ['CONFLUENT_SSH_PASSPHRASE'] = get_passphrase()
        os.environ['DISPLAY'] = 'NONE'
        os.environ['SSH_ASKPASS'] = askpass
        with open(os.devnull, 'wb') as devnull:
            subprocess.check_output(['ssh-add', keyname], stdin=devnull, stderr=devnull)
        del os.environ['CONFLUENT_SSH_PASSPHRASE']
        ready_keys[keyname] = 1
    finally:
        adding_key = False
        shutil.rmtree(tmpdir)

def sign_host_key(pubkey, nodename, principals=()):
    tmpdir = tempfile.mkdtemp()
    try:
        prep_ssh_key('/etc/confluent/ssh/ca')
        ready_keys['ca.pub'] = 1
        pkeyname = os.path.join(tmpdir, 'hostkey.pub')
        with open(pkeyname, 'wb') as pubfile:
            pubfile.write(pubkey)
        principals = set(principals)
        principals.add(nodename)
        principals = ','.join(sorted(principals))
        flags = '-Us' if sshver() > 7.6 else '-s'
        keyname = '/etc/confluent/ssh/ca.pub' if flags == '-Us' else '/etc/confluent/ssh/ca'
        subprocess.check_call(
            ['ssh-keygen', flags, keyname, '-I', nodename,
             '-n', principals, '-h', pkeyname])
        certname = pkeyname.replace('.pub', '-cert.pub')
        with open(certname) as cert:
            return cert.read()
    finally:
        shutil.rmtree(tmpdir)

def initialize_root_key(generate, automation=False):
    authorized = []
    myname = collective.get_myname()
    alreadyexist = False
    for currkey in glob.glob('/root/.ssh/*.pub'):
        authorized.append(currkey)
    if generate and not authorized and not automation:
        subprocess.check_call(['ssh-keygen', '-t', 'ed25519', '-f', '/root/.ssh/id_ed25519', '-N', ''])
        for currkey in glob.glob('/root/.ssh/*.pub'):
            authorized.append(currkey)
    if automation and generate:
        if os.path.exists('/etc/confluent/ssh/automation'):
            alreadyexist = True
        else:
            subprocess.check_call(
                ['ssh-keygen', '-t', 'ed25519',
                '-f','/etc/confluent/ssh/automation', '-N', get_passphrase(),
                '-C', 'Confluent Automation by {}'.format(myname)],
                preexec_fn=normalize_uid)
        authorized = ['/etc/confluent/ssh/automation.pub']
    ouid = normalize_uid()
    try:
        os.makedirs('/var/lib/confluent/public/site/ssh', mode=0o755)
    except OSError as e:
        if e.errno != 17:
            raise
    finally:
        os.seteuid(ouid)
    neededuid = os.stat('/etc/confluent').st_uid
    if automation:
        suffix = 'automationpubkey'
    else:
        suffix = 'rootpubkey'
    for auth in authorized:
        shutil.copy(
            auth,
            '/var/lib/confluent/public/site/ssh/{0}.{1}'.format(
                    myname, suffix))
        os.chmod('/var/lib/confluent/public/site/ssh/{0}.{1}'.format(
                myname, suffix), 0o644)
        os.chown('/var/lib/confluent/public/site/ssh/{0}.{1}'.format(
                myname, suffix), neededuid, -1)
    if alreadyexist:
        raise AlreadyExists()

def ca_exists():
    return os.path.exists('/etc/confluent/ssh/ca')

if __name__ == '__main__':
    initialize_root_key(True)
    if not ca_exists():
        initialize_ca()
    print(repr(sign_host_key(open('/etc/ssh/ssh_host_ed25519_key.pub').read(), collective.get_myname())))


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title> Mihael | Gregor von Laszewski</title>
    <link>/author/mihael/</link>
      <atom:link href="/author/mihael/index.xml" rel="self" type="application/rss+xml" />
    <description> Mihael</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><lastBuildDate>Mon, 01 Jan 2007 00:00:00 +0000</lastBuildDate>
    <image>
      <url>/images/icon_hufdd866d90d76849587aac6fbf27da1ac_464_512x512_fill_lanczos_center_2.png</url>
      <title> Mihael</title>
      <link>/author/mihael/</link>
    </image>

    <item>
      <title>The Open Grid Computing Environments collaboration: portlets and services for science gateways</title>
      <link>/publication/las-07-ogce/</link>
      <pubDate>Mon, 01 Jan 2007 00:00:00 +0000</pubDate>
      <guid>/publication/las-07-ogce/</guid>
      <description></description>
    </item>

    <item>
      <title>Analysis and Provision of QoS for Distributed Grid Applications</title>
      <link>/publication/las-04-qos-journal/</link>
      <pubDate>Tue, 01 Jun 2004 00:00:00 +0000</pubDate>
      <guid>/publication/las-04-qos-journal/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
#ifndef RMF_NODE_HANDLE_H
#define RMF_NODE_HANDLE_H

#include <boost/shared_ptr.hpp>
#include <string>
#include <vector>

#include "ID.h"
#include "NodeConstHandle.h"
#include "RMF/Nullable.h"
#include "RMF/config.h"
#include "RMF/enums.h"
#include "RMF/exceptions.h"
#include "RMF/infrastructure_macros.h"
#include "RMF/internal/SharedData.h"
#include "internal/SharedData.h"
#include "types.h"

namespace RMF {
class NodeHandle;
}  // namespace RMF

RMF_ENABLE_WARNINGS

#ifndef SWIG
#define RMF_HDF5_NODE_KEY_TYPE_METHODS(Traits, UCName)
#else
// otherwise swig gets confused
#define RMF_HDF5_NODE_KEY_TYPE_METHODS(Traits, UCName) \
  void set_frame_value(UCName##Key k, UCName v) const; \
  void set_value(UCName##Key k, UCName v) const;       \
  void set_static_value(UCName##Key k, UCName v) const;

#endif

namespace RMF {

class NodeHandle;

//! Pass a list of them
typedef std::vector<NodeHandle> NodeHandles;

class FileHandle;

//! A handle for a particular node in the hierarchy.
/** Use these handles to access and modify parts of the
    hierarchy.

    Make sure to check out the base class for the const
    methods.
 */
class RMFEXPORT NodeHandle : public NodeConstHandle {
  friend class FileHandle;
  template <class Tag>
  void set_value_impl(ID<Tag> k, typename Tag::ArgumentType v) const {
    Nullable<typename Tag::Type> sv = get_static_value(k);
    if (sv.get_is_null()) {
      set_static_value(k, v);
      return;
    }
    if (Tag::get_are_equal(sv.get(), v)) return;
    set_frame_value(k, v);
  }
#if !defined(SWIG) && !defined(RMF_DOXYGEN)
 public:
  NodeHandle(NodeID node, boost::shared_ptr<internal::SharedData> shared);
#endif

 public:
  NodeHandle() {}
  /** Create a new node as a child of this one.
   */
  NodeHandle add_child(std::string name, NodeType t) const;

  /** Add an existing node as a child.*/
  void add_child(NodeConstHandle nh) const;

  /** Create a new node that replaces an existing child of this one.
      The new node will take the place of the existing child, and the
      existing child will be moved to become the only child of the new node. */
  NodeHandle replace_child(NodeHandle child, std::string name,
		           NodeType t) const;

  NodeHandles get_children() const;

  /** \name Functions to access attributes

      @{
   */

  /** \brief  set the value of the attribute k for this node on the
      current frame.
  */
  template <class Tag>
  void set_frame_value(ID<Tag> k, typename Tag::ArgumentType v) const {
    RMF_USAGE_CHECK(shared_->get_loaded_frame() != FrameID(),
                    "Need to set a current frame before setting values.");
    shared_->set_loaded_value(node_, k, v);
  }
  /** Set the value
      - if the attribute has a static value and it is equal to the current one
        do nothing.
      - if the attribute doesn't have a static value, set it,
      - otherwise set the frame value.
  */
  template <class Tag>
  void set_value(ID<Tag> k, typename Tag::ArgumentType v) const {
    set_value_impl(k, v);
  }
  /** \brief  set the value of the attribute k for all frames.
   *
  */
  template <class Tag>
  void set_static_value(ID<Tag> k, typename Tag::ArgumentType v) const {
    shared_->set_static_value(node_, k, v);
  }
  /** @} */

  RMF_FOREACH_TYPE(RMF_HDF5_NODE_KEY_TYPE_METHODS);

  FileHandle get_file() const;
};
} /* namespace RMF */

RMF_DISABLE_WARNINGS

#endif /* RMF_NODE_HANDLE_H */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coniothyrium epiphyllum Linds.

### Remarks
null


text:
/* written by Jim Meyering */

#include <time.h>

#if GETTIMEOFDAY_CLOBBERS_LOCALTIME || TZSET_CLOBBERS_LOCALTIME

/* The address of the last buffer returned by localtime() or gmtime().  */
extern struct tm *localtime_buffer_addr;

#endif


text:
source ../../../setup/setenv.sh

echo "Enter your password for the Apigee Enterprise organization, followed by [ENTER]:"

read -s password

echo using $username and $org

echo Install API Products

curl -u $username:$password $url/v1/o/$org/apiproducts \
  -H "Content-Type: application/json" -X POST -T login-app-product.json

echo Create developers

curl -u $username:$password $url/v1/o/$org/developers \
  -H "Content-Type: application/xml" -X POST -T login-app-developer.xml

echo Create apps

curl -u $username:$password \
  $url/v1/o/$org/developers/loginappdev@example.com/apps \
  -H "Content-Type: application/xml" -X POST -T login-app.xml

# Get consumer key and attach API product
# Do this in a quick and clean way that doesn't require python or anything

echo Get app info
curl -u $username:$password -H "Accept: application/json" \
     $url/v1/o/$org/developers/loginappdev@example.com/apps/login-app

key=`curl -u $username:$password -H "Accept: application/json" \
     $url/v1/o/$org/developers/loginappdev@example.com/apps/login-app 2>/dev/null \
     | grep consumerKey | awk -F '\"' '{ print $4 }'`

secret=`curl -u $username:$password -H "Accept: application/json" \
     $url/v1/o/$org/developers/loginappdev@example.com/apps/login-app 2>/dev/null \
     | grep consumerSecret | awk -F '\"' '{ print $4 }'`

curl -u $username:$password \
  $url/v1/o/$org/developers/loginappdev@example.com/apps/login-app/keys/${key} \
  -H "Content-Type: application/xml" -X POST -T login-app-product.xml

echo "\n\nConsumer key for login-app is ${key}"
echo "\n\nConsumer secret for login-app is ${secret}"


text:
<?php

// autoload_static.php @generated by Composer

namespace Composer\Autoload;

class ComposerStaticInitc08d5bfd5b6d7ffc218a831191c09ca9
{
    public static $prefixLengthsPsr4 = array (
        'H' =>
        array (
            'Hashids\\' => 8,
        ),
    );

    public static $prefixDirsPsr4 = array (
        'Hashids\\' =>
        array (
            0 => __DIR__ . '/..' . '/hashids/hashids/src',
        ),
    );

    public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {
            $loader->prefixLengthsPsr4 = ComposerStaticInitc08d5bfd5b6d7ffc218a831191c09ca9::$prefixLengthsPsr4;
            $loader->prefixDirsPsr4 = ComposerStaticInitc08d5bfd5b6d7ffc218a831191c09ca9::$prefixDirsPsr4;

        }, null, ClassLoader::class);
    }
}


text:
module Api
  module V3
    # Shows and updates heat network orders.
    class HeatNetworkOrdersController < BaseController
      include UsesScenario

      rescue_from NoMethodError do |e|
        raise e unless e.message.starts_with?("undefined method `permit'")

        render json: { errors: ['Invalid JSON payload'] }, status: 400
      end

      def show
        render json: heat_network_order
      end

      def update
        heat_network_order[:order] = heat_network_order_params[:order]

        if heat_network_order.valid?
          heat_network_order.save
          render json: heat_network_order
        else
          # There is no reason for invalid options to have been provided, unless
          # the front-end is unaware of a change. Notify.
          Raven.capture_message(
            'Invalid heat network order',
            extra: {
              errors: heat_network_order.errors.full_messages,
              order: heat_network_order_params[:order],
              scenario_id: params[:scenario_id]
            }
          )

          render_errors(heat_network_order)
        end
      end

      private

      def heat_network_order
        @heat_network_order ||= scenario.heat_network_order
      end

      def heat_network_order_params
        params.require(:heat_network_order).permit(order: [])
      end

      def render_errors(heat_network_order)
        render json: { errors: heat_network_order.errors.full_messages }, status: 422
      end
    end
  end
end


text:
package org.xtreemfs.babudb.log;

import java.util.zip.Checksum;

import org.xtreemfs.babudb.lsmdb.LSN;
import org.xtreemfs.babudb.lsmdb.LSMDBRequest;
import org.xtreemfs.foundation.buffer.BufferPool;
import org.xtreemfs.foundation.buffer.ReusableBuffer;
import org.xtreemfs.foundation.logging.Logging;

/**
 *
 * @author bjko
 */
public class LogEntry {

    /**
     * length of the entry's header (excluding the length field itself)
     */
    protected static final int  headerLength        = Integer.SIZE / 8 * 4 +
                                                  Long.SIZE / 8 + Byte.SIZE / 8;

    public static final boolean USE_CHECKSUMS       = true;

    public static final byte    PAYLOAD_TYPE_INSERT = 0;

    public static final byte    PAYLOAD_TYPE_SNAP   = 1;

    public static final byte    PAYLOAD_TYPE_CREATE = 2;

    public static final byte    PAYLOAD_TYPE_COPY   = 3;

    public static final byte    PAYLOAD_TYPE_DELETE = 4;

    public static final byte    PAYLOAD_TYPE_SNAP_DELETE = 5;

    public static final byte    PAYLOAD_TYPE_TRANSACTION = 6;

    /**
     * view ID of the log entry. The view ID is an epoch number which creates a
     * total order on the log entries (viewId.logSequenceNo).
     */
    protected int               viewId              = -1;

    protected long              logSequenceNo       = -1L;

    protected int               checksum;

    protected ReusableBuffer    payload;

    protected SyncListener      listener;

    private LSMDBRequest<?>     attachment;

    protected byte              payloadType;

    private LogEntry() {
    }

    public LogEntry(ReusableBuffer payload, SyncListener l, byte payloadType) {
        assert(payload != null);

        this.payload = payload;
        this.listener = l;
        this.payloadType = payloadType;
    }

    public void assignId(int viewId, long logSequenceNo) {
        this.viewId = viewId;
        this.logSequenceNo = logSequenceNo;
    }

    public ReusableBuffer serialize(Checksum csumAlgo) {
        assert (viewId > 0);
        assert (logSequenceNo > 0);

        final int bufSize = headerLength + payload.remaining();
        ReusableBuffer buf = BufferPool.allocate(bufSize);
        buf.putInt(bufSize);
        buf.putInt(checksum);
        buf.putInt(viewId);
        buf.putLong(logSequenceNo);
        buf.put(payloadType);
        buf.put(payload);
        payload.flip(); // otherwise payload is not reusable
        buf.putInt(bufSize);
        buf.flip();

        if (USE_CHECKSUMS) {
            // reset the old checksum to 0, before calculating a new one
            buf.position(Integer.SIZE / 8);
            buf.putInt(0);
            buf.position(0);

            csumAlgo.update(buf.array(), 0, bufSize);
            int cPos = buf.position();

            // write the checksum to the buffer
            buf.position(Integer.SIZE / 8);
            buf.putInt((int) csumAlgo.getValue());
            buf.position(cPos);
        }

        return buf;
    }

    public void setListener(SyncListener listener) {
        this.listener = listener;
    }

    public SyncListener getListener() {
        return listener;
    }

    public ReusableBuffer getPayload() {
        return this.payload;
    }

    public int getViewId() {
        return this.viewId;
    }

    public long getLogSequenceNo() {
        return this.logSequenceNo;
    }

    public LSN getLSN() {
        if (this.viewId == -1 && this.logSequenceNo == -1L) return null;
        else return new LSN(this.viewId, this.logSequenceNo);
    }

    public static void checkIntegrity(ReusableBuffer data)
        throws LogEntryException {
        int cPos = data.position();

        if (data.remaining() < Integer.SIZE / 8)
            throw new LogEntryException("Empty data. Cannot read log entry.");

        int length1 = data.getInt();

        if ((length1 - Integer.SIZE / 8) > data.remaining()) {
            data.position(cPos);
            Logging.logMessage(Logging.LEVEL_DEBUG, null, "not long enough");
            throw new LogEntryException("The log entry is incomplete. " +
            		"The length indicated in the header exceeds the " +
            		"available data.");
        }

        data.position(cPos + length1 - Integer.SIZE / 8);

        int length2 = data.getInt();

        data.position(cPos);

        if (length1 != length2) {
            throw new LogEntryException("Invalid Frame. The length entries do" +
            		" not match; length1=" + length1 + ", length2=" +
            		length2);
        }

    }

    public static LogEntry deserialize(ReusableBuffer data, Checksum csumAlgo)
        throws LogEntryException {
        checkIntegrity(data);

        final int startPos = data.position();
        final int bufSize = data.getInt();

        LogEntry e = new LogEntry();
        e.checksum = data.getInt();
        e.viewId = data.getInt();
        e.logSequenceNo = data.getLong();
        e.payloadType = data.get();
        final int payloadSize = bufSize - headerLength;
        int payloadPosition = data.position();
        ReusableBuffer payload = data.createViewBuffer();
        payload.range(payloadPosition, payloadSize);
        e.payload = payload;

        if (USE_CHECKSUMS) {
            // reset the old checksum to 0, before calculating a new one
            data.position(startPos + Integer.SIZE / 8);
            data.putInt(0);
            data.position(startPos);

            csumAlgo.update(data.array(), startPos, bufSize);
            int csum = (int) csumAlgo.getValue();

            // write back the checksum to the buffer
            data.position(startPos + Integer.SIZE / 8);
            data.putInt((int) e.checksum);

            if (csum != e.checksum) {
                throw new LogEntryException(
                    "Invalid Checksum. Checksum in log entry and calculated " +
                    "checksum do not match.");
            }
        }

        data.position(startPos);

        return e;
    }

    public void free() {
        BufferPool.free(payload);
        payload = null;
    }

    public LSMDBRequest<?> getAttachment() {
        return attachment;
    }

    public void setAttachment(LSMDBRequest<?> attachment) {
        this.attachment = attachment;
    }

    public byte getPayloadType() {
        return payloadType;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#clone()
     */
    @Override
    public LogEntry clone() {
        LogEntry result = new LogEntry(payload.createViewBuffer(), listener, payloadType);
        result.assignId(viewId, logSequenceNo);
        result.attachment = attachment;
        result.checksum = checksum;
        return result;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "LSN(" + viewId + ":" + logSequenceNo + ") with " + payload.remaining() +
               " bytes of payload.";
    }
}


text:
from django.core.urlresolvers import reverse
from tastypie import authorization
from tastypie.authentication import MultiAuthentication

from crits.certificates.certificate import Certificate
from crits.certificates.handlers import handle_cert_file
from crits.core.api import CRITsApiKeyAuthentication, CRITsSessionAuthentication
from crits.core.api import CRITsSerializer, CRITsAPIResource

class CertificateResource(CRITsAPIResource):
    """
    Class to handle everything related to the Certificate API.

    Currently supports GET and POST.
    """

    class Meta:
        object_class = Certificate
        allowed_methods = ('get', 'post', 'patch')
        resource_name = "certificates"
        authentication = MultiAuthentication(CRITsApiKeyAuthentication(),
                                             CRITsSessionAuthentication())
        authorization = authorization.Authorization()
        serializer = CRITsSerializer()

    def get_object_list(self, request):
        """
        Use the CRITsAPIResource to get our objects but provide the class to get
        the objects from.

        :param request: The incoming request.
        :type request: :class:`django.http.HttpRequest`
        :returns: Resulting objects in the specified format (JSON by default).

        """

        return super(CertificateResource, self).get_object_list(request,
                                                                Certificate)

    def obj_create(self, bundle, **kwargs):
        """
        Handles creating Certificates through the API.

        :param bundle: Bundle containing the information to create the Certificate.
        :type bundle: Tastypie Bundle object.
        :returns: HttpResponse.

        """

        content = {'return_code': 1,
                   'type': 'Certificate'}
        analyst = bundle.request.user.username
        file_ = bundle.data.get('filedata', None)
        if not file_:
            content['message'] = "Upload type of 'file' but no file uploaded."
            self.crits_response(content)

        filedata = file_.read()
        filename = str(file_)

        source = bundle.data.get('source', None)
        method = bundle.data.get('method', None)
        reference = bundle.data.get('reference', None)
        description = bundle.data.get('reference', None)
        relationship = bundle.data.get('relationship', None)
        related_id = bundle.data.get('related_id', None)
        related_md5 = bundle.data.get('related_md5', None)
        related_type = bundle.data.get('related_type', None)
        bucket_list = bundle.data.get('bucket_list', None)
        ticket = bundle.data.get('ticket', None)

        result = handle_cert_file(filename,
                                  filedata,
                                  source,
                                  analyst,
                                  description,
                                  related_id=related_id,
                                  related_md5=related_md5,
                                  related_type = related_type,
                                  method=method,
                                  reference=reference,
                                  relationship=relationship,
                                  bucket_list=bucket_list,
                                  ticket=ticket)

        if result.get('id'):
            url = reverse('api_dispatch_detail',
                          kwargs={'resource_name': 'certificates',
                                  'api_name': 'v1',
                                  'pk': result.get('id')})
            content['url'] = url
            content['id'] = result.get('id')

        if result['success']:
            content['return_code'] = 0

        content['message'] = result['message']
        self.crits_response(content)


text:
using Stratis.SmartContracts.Core.Hashing;

namespace Stratis.SmartContracts.CLR
{
    /// <summary>
    /// Encodes keys by applying a Keccak256 hash, returning 32-bytes.
    /// </summary>
    public class KeyHashingStrategy : IKeyEncodingStrategy
    {
        public static KeyHashingStrategy Default = new KeyHashingStrategy();

        public byte[] GetBytes(byte[] key)
        {
            return HashHelper.Keccak256(key);
        }
    }
}


text:
package com.ap.dummyapp;

/**
 * Sample code for "Developers test: From beginner to master" book.
 * Tomasz Kaczanowski
 * http://kaczanowscy.pl/tomek
 * 3/20/12, 7:44 AM
 */
public interface Template {
}


text:
namespace Wires.Sample.ViewModel
{
	using System;
	using Newtonsoft.Json;

	public class Post
	{
		[JsonProperty("id")]
		public string Identifier { get; set; }

		[JsonProperty("author")]
		public string Author { get; set; }

		[JsonProperty("title")]
		public string Title { get; set; }

		[JsonProperty("created")]
		public long Timestamp { get; set; }

		[JsonIgnore]
		public DateTime Datetime => new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(this.Timestamp).ToLocalTime();

		[JsonProperty("thumbnail")]
		public string Thumbnail { get; set; }
	}
}


text:
/*
    artifact generator: C:\My\wizzi\v4\node_modules\v4-wizzi-js\lib\artifacts\js\module\gen\main.js
    primary source IttfDocument: c:\my\wizzi\v4\kernel\wizzi-repo\src\ittf\lib\repo\errors.js.ittf
    utc time: Tue, 10 Oct 2017 15:38:08 GMT
*/
'use strict';
var globalErrors = require('../errors');
var utils = require('./utils');

var md = module.exports = globalErrors;

function RepoIOError(message, uri, innerEx) {
    this.name = 'RepoIOError';
    this.message = message + '\nuri: ' + uri;
    // 5/8/17 set this.stack = (new Error()).stack
}
RepoIOError.prototype.toString = function() {
    return this.message;
};
RepoIOError.prototype = Object.create(Error.prototype);
RepoIOError.prototype.constructor = RepoIOError;
md.RepoIOError = RepoIOError;


text:
/*
 * DC/OS
 *
 * DC/OS API
 *
 * API version: 1.0.0
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package dcos

type EdgelbV2RewriteHttp struct {
	// Set the host header value
	Host     string                      `json:"host,omitempty"`
	Path     EdgelbV2RewriteHttpPath     `json:"path,omitempty"`
	Request  EdgelbV2RewriteHttpRequest  `json:"request,omitempty"`
	Response EdgelbV2RewriteHttpResponse `json:"response,omitempty"`
	Sticky   EdgelbV2RewriteHttpSticky   `json:"sticky,omitempty"`
}


text:
using System;

namespace GoogleContactExport
{
    public class ContactEventArgs
    {
        //Name
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string middleName { get; set; }

        //Adresses
        public string privateStreet { get; set; }
        public string privateCity { get; set; }
        public string privateRegion { get; set; }
        public string privatePostcode { get; set; }
        public string privateCountry { get; set; }
        public string businessStreet { get; set; }
        public string businessCity { get; set; }
        public string businessRegion { get; set; }
        public string businessPostcode { get; set; }
        public string businessCountry { get; set; }

        //Phone Numbers
        public string privatePhone { get; set; }
        public string mobilePhone { get; set; }
        public string privateFax { get; set; }
        public string businessPhone { get; set; }
        public string business2Phone { get; set; }
        public string businessFax { get; set; }
        public string pager { get; set; }

        //E-Mail Adresses
        public string privateEmail { get; set; }
        public string businessEmail { get; set; }
        public string business2Email { get; set; }

        //Other
        public string notes { get; set; }
        public DateTime birthday { get; set; }
        public string gender { get; set; }
        public string company { get; set; }
        public string jobTitle { get; set; }
    }
}


text:
package com.dubu.livecamera.gpuimage;

import android.opengl.GLES20;

public class GPUImageSobelThresholdFilter extends
		GPUImage3x3TextureSamplingFilter {
    public static final String SOBEL_THRESHOLD_EDGE_DETECTION = "" +
    		"precision mediump float;\n" +
    		"\n" +
    		"varying vec2 textureCoordinate;\n" +
    		"varying vec2 leftTextureCoordinate;\n" +
    		"varying vec2 rightTextureCoordinate;\n" +
    		"\n" +
    		"varying vec2 topTextureCoordinate;\n" +
    		"varying vec2 topLeftTextureCoordinate;\n" +
    		"varying vec2 topRightTextureCoordinate;\n" +
    		"\n" +
    		"varying vec2 bottomTextureCoordinate;\n" +
    		"varying vec2 bottomLeftTextureCoordinate;\n" +
    		"varying vec2 bottomRightTextureCoordinate;\n" +
    		"\n" +
    		"uniform sampler2D inputImageTexture;\n" +
    		"uniform lowp float threshold;\n" +
    		"\n" +
    		"const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);\n" +
    		"\n" +
    		"void main()\n" +
    		"{\n" +
    		"    float bottomLeftIntensity = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;\n" +
    		"    float topRightIntensity = texture2D(inputImageTexture, topRightTextureCoordinate).r;\n" +
    		"    float topLeftIntensity = texture2D(inputImageTexture, topLeftTextureCoordinate).r;\n" +
    		"    float bottomRightIntensity = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;\n" +
    		"    float leftIntensity = texture2D(inputImageTexture, leftTextureCoordinate).r;\n" +
    		"    float rightIntensity = texture2D(inputImageTexture, rightTextureCoordinate).r;\n" +
    		"    float bottomIntensity = texture2D(inputImageTexture, bottomTextureCoordinate).r;\n" +
    		"    float topIntensity = texture2D(inputImageTexture, topTextureCoordinate).r;\n" +
    		"    float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;\n" +
    		"    float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;\n" +
    		"\n" +
    		"    float mag = 1.0 - length(vec2(h, v));\n" +
    		"    mag = step(threshold, mag);\n" +
    		"\n" +
    		"    gl_FragColor = vec4(vec3(mag), 1.0);\n" +
    		"}\n";

    private int mUniformThresholdLocation;
    private float mThreshold = 0.9f;

    public GPUImageSobelThresholdFilter() {
    	this(0.9f);
    }

    public GPUImageSobelThresholdFilter(float threshold) {
    	super(SOBEL_THRESHOLD_EDGE_DETECTION);
    	mThreshold = threshold;
    }

    @Override
    public void onInit() {
    	super.onInit();
    	mUniformThresholdLocation = GLES20.glGetUniformLocation(getProgram(), "threshold");
    }

    @Override
    public void onInitialized() {
    	super.onInitialized();
    	setThreshold(mThreshold);
    }

    public void setThreshold(final float threshold) {
    	mThreshold = threshold;
    	setFloat(mUniformThresholdLocation, threshold);
    }
}


text:
package config_test

import (
	"bytes"
	"fmt"
	"reflect"
	"strings"
	"testing"

	"github.com/arsham/expipe/reader"
	"github.com/arsham/expipe/tools"
	"github.com/arsham/expipe/tools/config"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
)

func TestLoadYAML(t *testing.T) {
	t.Parallel()
	v := viper.New()
	v.SetConfigType("yaml")
	log := tools.DiscardLogger()

	input := bytes.NewBuffer([]byte(`
    readers:
        reader1:
            no_type: true
    recorders:
        recorder1:
            type: elasticsearch
    `))
	v.ReadConfig(input)
	_, err := config.LoadYAML(log, v)

	var (
		val *config.NotSpecifiedError
		ok  bool
	)
	if val, ok = errors.Cause(err).(*config.NotSpecifiedError); !ok {
		t.Fatalf("err.(*config.NotSpecifiedError): err = (%v); want notSpecifiedErr", err)
	}

	if !strings.Contains(val.Section, "reader1") {
		t.Errorf("want error for (reader1) section, got for (%s)", val.Section)
	}

	input = bytes.NewBuffer([]byte(`
    readers:
        reader1:
            type: expvar
    recorders:
        recorder1:
            no_type: true
    `))
	v.ReadConfig(input)
	_, err = config.LoadYAML(log, v)

	if val, ok = errors.Cause(err).(*config.NotSpecifiedError); !ok {
		t.Fatalf("err.(*config.NotSpecifiedError): err = (%v); want (notSpecifiedErr)", err)
	}

	if val.Section != "recorder1" {
		t.Errorf("val.Section = (%s); want (error) for Section", val.Section)
	}
}

func TestLoadYAMLSuccess(t *testing.T) {
	t.Parallel()
	v := viper.New()
	v.SetConfigType("yaml")
	log := tools.DiscardLogger()
	input, err := config.FixtureWithSection("various.txt", "LoadYAMLSuccess")
	if err != nil {
		t.Fatalf("error getting section: %v", err)
	}

	v.ReadConfig(input.Body)
	confMap, err := config.LoadYAML(log, v)
	if errors.Cause(err) != nil {
		t.Errorf("err = (%v); want (nil)", err)
	}
	if confMap == nil {
		t.Error("confMap = (nil); want (confMap)")
	}
}

func stringInMapKeys(niddle string, haystack map[string]reader.DataReader) bool {
	for b := range haystack {
		if b == niddle {
			return true
		}
	}
	return false
}

func TestLoadYAMLRemoveUnused(t *testing.T) {
	t.Parallel()
	v := viper.New()
	v.SetConfigType("yaml")
	log := tools.DiscardLogger()
	input, err := config.FixtureWithSection("various.txt", "LoadYAMLRemoveUnused")
	if err != nil {
		t.Fatalf("error getting section: %v", err)
	}

	v.ReadConfig(input.Body)
	confMap, err := config.LoadYAML(log, v)
	if errors.Cause(err) != nil {
		t.Errorf("err = (%v); want (nil)", err)
	}
	if confMap == nil {
		t.Fatal("confMap = (nil); want (confMap)")
	}
	unwantedReaders := []string{"reader2", "reader3"}
	unwantedRecorders := []string{"recorder3"}
	for red, rec := range confMap.Routes {
		if tools.StringInSlice(red, unwantedReaders) {
			t.Errorf("(%s) reader should not be in (%v))", red, unwantedReaders)
		}
		for _, r := range rec {
			if tools.StringInSlice(r, unwantedRecorders) {
				t.Errorf("(%s) recorder should not be in (%v))", r, unwantedRecorders)
			}
		}
	}
}

func TestLoadSettingsErrors(t *testing.T) {
	t.Parallel()

	v := viper.New()
	log := tools.DiscardLogger()
	nilErr := &config.StructureErr{Section: "", Reason: "", Err: nil}
	v.SetConfigType("yaml")

	input := bytes.NewBuffer([]byte(""))
	v.ReadConfig(input)
	_, err := config.LoadYAML(log, v)
	if err != config.ErrEmptyConfig {
		t.Errorf("want (%v), got (%v)", config.ErrEmptyConfig, err)
	}

	input = bytes.NewBuffer([]byte(`
    settings:
        log_level:
            - 123
    `))
	v.ReadConfig(input)
	_, err = config.LoadYAML(log, v)
	if reflect.TypeOf(err) != reflect.TypeOf(nilErr) {
		t.Errorf("err =  (%v); want (%v)", err, config.ErrEmptyConfig)
	}

	if !strings.Contains(err.Error(), "log_level") {
		t.Errorf("expecting mention of log_level, got (%v)", err)
	}

	input = bytes.NewBuffer([]byte(`
    settings:
        log_level: debug
    `))
	v.ReadConfig(input)
	config.LoadYAML(log, v)
	if log.Level != tools.DebugLevel {
		t.Errorf("log.Level = (%v); want (tools.DebugLevel)", log.Level)
	}
}

func TestLoadSections(t *testing.T) {
	t.Parallel()
	v := viper.New()
	log := tools.DiscardLogger()
	v.SetConfigType("yaml")

	notSpec := func(t *testing.T, err error, section string) {
		if _, ok := errors.Cause(err).(*config.NotSpecifiedError); !ok {
			t.Errorf("err.(*config.NotSpecifiedError) = (%v); want (NotSpecifiedError)", err)
		}

		if !strings.Contains(err.Error(), section) {
			t.Errorf("expected (%s) in error message, got (%v)", section, err.Error())
		}
	}

	tcs := []struct {
		input   *bytes.Buffer
		section string
	}{
		{
			input: bytes.NewBuffer([]byte(`
    readers:
    recorders: blah
    routes: blah
    `)),
			section: "readers",
		},
		{
			input: bytes.NewBuffer([]byte(`
    readers: blah
    recorders:
    routes: blah
    `)),
			section: "recorders",
		},
		{
			input: bytes.NewBuffer([]byte(`
    readers: blah
    recorders: blah
    routes:
    `)),
			section: "routes",
		},
	}
	for i, tc := range tcs {
		name := fmt.Sprintf("case_%d", i)
		t.Run(name, func(t *testing.T) {
			v.ReadConfig(tc.input)
			_, err := config.LoadYAML(log, v)
			notSpec(t, err, tc.section)
		})
	}
}


text:
 0" ng-class="node.collapsed ? 'fa fa-plus-square-o' : 'fa fa-minus-square-o'" ng-click="node.collapsed = !node.collapsed;nodeChange(node)">

        <input type="checkbox" ng-model="node.checked" data-ng-change="nodeChange(node)" />


text:
namespace Finsternis
{
    using System;
    using UnityEngine;

    [Serializable]
    public class BrushSizeVariation
    {
        [SerializeField]
        [Range(1, 100)]
        private int minWidth;
        [SerializeField]
        [Range(1, 100)]
        private int maxWidth;
        [SerializeField]
        [Range(1, 100)]
        private int minHeight;
        [SerializeField]
        [Range(1, 100)]
        private int maxHeight;

        public Vector2 Min
        {
            get { return new Vector2(minWidth, minHeight); }
        }

        public Vector2 Max
        {
            get { return new Vector2(maxWidth, maxHeight); }
        }

        public BrushSizeVariation(int minWidth, int maxWidth, int minHeight, int maxHeight)
        {
            this.minWidth = minWidth;
            this.maxWidth = maxWidth;
            this.minHeight = minHeight;
            this.maxHeight = maxHeight;
        }

        public void Validate(int maxWidth, int maxHeight)
        {
            this.maxWidth = Mathf.Clamp(this.maxWidth, 0, maxWidth);
            this.minWidth = Mathf.Clamp(this.minWidth, 0, this.maxWidth);

            this.maxHeight = Mathf.Clamp(this.maxHeight, 0, maxHeight);
            this.minHeight = Mathf.Clamp(this.minHeight, 0, this.maxHeight);
        }
    }
}


text:
title: "metrics.target"
---

`metrics.target` configures the backend the metrics values are sent to.

Possible values are:

* `<empty>`:  do not report metrics
* `stdout`:   report metrics to stdout
* `graphite`: report metrics to Graphite on [metrics.graphite.addr](/ref/metrics.graphite.addr/)
* `statsd`: legacy statsd support, used in v1.5.5 and lower - removed in v1.6
* `statsd_raw`: report metrics to StatsD on [metrics.statsd.addr](/ref/metrics.statsd.addr/) - this was
  intentionally renamed because anyone upgrading to 1.6 will need to revisit their configuration anyway due to
  rewrite of this backend.  It was quite broken before, the counters never reset, it did not follow the spec so the info was
  likely wrong or people using this were doing some workarounds they'll need to remove anyway.
* `circonus`: report metrics to Circonus (https://circonus.com/)
* `prometheus`: use prometheus metrics. (https://prometheus.io)  Must be used in conjuction with a prometheus
  listener in [proxy.addr](/ref/proxy.addr/)
* `dogstatsd`: use with datadog dogstatsd (https://www.datadoghq.com/)

The default is

	metrics.target =

Multiple metrics targets can be defined separated by comma.


text:
package com.orientechnologies.orient.core.index;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;

/**
 * Proxied single value index.
 *
 * @author Luca Garulli
 *
 */
public class OIndexRemoteOneValue extends OIndexRemote<OIdentifiable> {
  protected final static String QUERY_GET = "select rid from index:%s where key = ?";

  public OIndexRemoteOneValue(final String iName, final String iWrappedType, final ORID iRid,
      final OIndexDefinition iIndexDefinition, final ODocument iConfiguration, final Set<String> clustersToIndex) {
    super(iName, iWrappedType, iRid, iIndexDefinition, iConfiguration, clustersToIndex);
  }

  public OIdentifiable get(final Object iKey) {
    final OCommandRequest cmd = formatCommand(QUERY_GET, name);
    final List<OIdentifiable> result = getDatabase().command(cmd).execute(iKey);
    if (result != null && !result.isEmpty())
      return ((OIdentifiable) ((ODocument) result.get(0).getRecord()).field("rid", OType.LINK)).getIdentity();
    return null;
  }

  public Iterator<Entry<Object, OIdentifiable>> iterator() {
    final OCommandRequest cmd = formatCommand(QUERY_ENTRIES, name);
    final Collection<ODocument> result = getDatabase().command(cmd).execute();

    final Map<Object, OIdentifiable> map = new LinkedHashMap<Object, OIdentifiable>();
    for (final ODocument d : result) {
      map.put(d.field("key"), (OIdentifiable) d.field("rid", OType.LINK));
    }

    return map.entrySet().iterator();
  }

  public Iterator<Entry<Object, OIdentifiable>> inverseIterator() {
    final OCommandRequest cmd = formatCommand(QUERY_ENTRIES, name);
    final List<ODocument> result = getDatabase().command(cmd).execute();

    final Map<Object, OIdentifiable> map = new LinkedHashMap<Object, OIdentifiable>();

    for (ListIterator<ODocument> it = result.listIterator(); it.hasPrevious();) {
      ODocument d = it.previous();
      map.put(d.field("key"), (OIdentifiable) d.field("rid", OType.LINK));
    }

    return map.entrySet().iterator();
  }

  public Iterator<OIdentifiable> valuesIterator() {
    throw new UnsupportedOperationException();
  }

  public Iterator<OIdentifiable> valuesInverseIterator() {
    throw new UnsupportedOperationException();
  }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter, Switch, Route } from 'react-router-dom';
import App from './components/hoc/App';
import PageCalendar from './components/pages/PageCalendar';
import PageCommits from './components/pages/PageCommits';
import PageContributor from './components/pages/PageContributor';
import PageContributors from './components/pages/PageContributors';
import PageCuriosa from './components/pages/PageCuriosa';
import PageRepositories from './components/pages/PageRepositories';
import PageRepository from './components/pages/PageRepository';
import PageStaleness from './components/pages/PageStaleness';
import PageTrends from './components/pages/PageTrends';
import PageDashboard from './components/pages/PageDashboard';
import './styles/index.css';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <HashRouter basename="/">
      <App>
        <Switch>
          <Route path="/calendar/" component={PageCalendar} />
          <Route path="/commits/" component={PageCommits} />
          <Route path="/contributor/:paramAuthorEmail" component={PageContributor} />
          <Route path="/contributors/" component={PageContributors} />
          <Route path="/curiosa/" component={PageCuriosa} />
          <Route path="/repository/:paramRepoName" component={PageRepository} />
          <Route path="/repositories/" component={PageRepositories} />
          <Route path="/staleness/" component={PageStaleness} />
          <Route path="/trends/" component={PageTrends} />
          <Route path="/" component={PageDashboard} exact />
        </Switch>
      </App>
    </HashRouter>
  </React.StrictMode>,
  document.getElementById('root'),
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Palindromes
{
    class Palindromes
    {
        static void Main(string[] args)
        {
            string text = Console.ReadLine();
            string[] words = text.Split(new[] { ' ', ',', '?', '!', '.' }, StringSplitOptions.RemoveEmptyEntries);

            SortedSet<string> palindromes = new SortedSet<string>();
            foreach (string word in words)
            {
                if (IsPalindrome(word))
                {
                    palindromes.Add(word);
                }
            }

            Console.WriteLine(string.Join(", ", palindromes));
        }

        static bool IsPalindrome(string input)
        {
            for (int i = 0; i < input.Length / 2; i++)
            {
                if (input[i] != input[input.Length - 1 - i])
                {
                    return false;
                }
            }
            return true;
        }
    }
}


text:
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="canonical" href="https://stealthefish.com/tags/js/"/>
    <title>Andrea D. Blog</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" id="tl-id-1" data-turbolinks-permanent />
    <link rel="stylesheet" href="/css/css.css" data-turbolinks-permanent id="tl-id-2" />

    <link rel="preload"
          as="style"
          href="https://fonts.googleapis.com/css?family=Raleway:200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i&subset=latin-ext&display=swap" id="tl-id-6" data-turbolinks-permanent />

    <link rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Raleway:200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i&subset=latin-ext&display=swap"
          media="all" onload="this.media='all'" id="tl-id-3" data-turbolinks-permanent />

    <link rel="alternate" href="/atom.xml" title="Andrea D. Blog" type="application/atom+xml" id="tl-id-10" data-turbolinks-permanent>

    <meta name="theme-color" content="#2c62b8">
    <link rel="icon" href="/favicon/steal-fav512w.svg">
    <link rel="apple-touch-icon" href="/favicon/steal-fav180w.png">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/SimpleLightbox/2.1.0/simpleLightbox.min.css" id="tl-id-4" data-turbolinks-permanent />

      <meta name="description" content="...and definitely it steals the fish.">
<meta property="og:type" content="website">
<meta property="og:title" content="Andrea D. Blog">
<meta property="og:url" content="https://stealthefish.com/tags/js/">
<meta property="og:site_name" content="Andrea D. Blog">
<meta property="og:description" content="...and definitely it steals the fish.">
<meta property="og:locale" content="en_US">
<meta property="article:author" content="Andrea Dessi">
<meta property="article:tag" content="tech">
<meta property="article:tag" content=" development">
<meta property="article:tag" content=" me">
<meta property="article:tag" content=" web culture">
<meta name="twitter:card" content="summary">
<meta name="twitter:creator" content="@nkjoep">

  <meta name="generator" content="Hexo 4.2.1"><link rel="stylesheet" href="/css/prism-material-light.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css">

    Andrea D. Blog
          Twitter
          LinkedIn
          GitHub
          rss

      archive.ejs

Projects

        Experiments, tests and other stuff I've worked on. Have a look.

hexo-blog-theme-starter

whatismyremoteip

hn-meets-modern-html

i-love-markdown.css

svg-to-symbol

CSV-Transformer

qrcode-bookmarklet

microsmith

event-accelaration-test

vscode-mac-classic-theme

MooCells

EntandoPageModelsBuilder

jquery.entando.js

bootstrap-swapon

jpstaticresourceeditor

Entando-Plugin-Builder-for-ANT

dummy-jsp-image

MooContentAssist

Credits

          © Andrea Dessì 2020.

          All The Ideas are mine if not specified otherwise.

Some pictures from me.


text:
package com.skype.connector;

import java.util.EventListener;

/**
 * Connector event listener interface.
 * Implement this interface when writing an event listener for connector classes.
 */
public interface ConnectorListener extends EventListener {
	/**
	 * This will be triggered when a connector has received a message.
	 * @param event the event source.
	 */
    void messageReceived(ConnectorMessageEvent event);

    /**
     * This will be triggered when a connector has send a message to a Skype Client.
     * @param event the event source.
     */
    void messageSent(ConnectorMessageEvent event);

    /**
     * This method will be triggered when the status of a connector changes.
     * @param event the event source.
     */
    void statusChanged(ConnectorStatusEvent event);
}