text:
<?php

namespace DrewM\MailChimp;

/**
 * Super-simple, minimum abstraction MailChimp API v3 wrapper
 * MailChimp API v3: http://developer.mailchimp.com
 * This wrapper: https://github.com/drewm/mailchimp-api
 *
 * @author  Drew McLellan <drew.mclellan@gmail.com>
 * @version 2.5
 */
class MailChimp
{
    private $api_key;
    private $api_endpoint = 'https://<dc>.api.mailchimp.com/3.0';

    const TIMEOUT = 10;

    /*  SSL Verification
        Read before disabling:
        http://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
    */
    public $verify_ssl = true;

    private $request_successful = false;
    private $last_error         = '';
    private $last_response      = array();
    private $last_request       = array();

    /**
     * Create a new instance
     *
     * @param string $api_key      Your MailChimp API key
     * @param string $api_endpoint Optional custom API endpoint
     *
     * @throws \Exception
     */
    public function __construct($api_key, $api_endpoint = null)
    {
        if (!function_exists('curl_init') || !function_exists('curl_setopt')) {
            throw new \Exception("cURL support is required, but can't be found.");
        }

        $this->api_key = $api_key;

        if ($api_endpoint === null) {
            if (strpos($this->api_key, '-') === false) {
                throw new \Exception("Invalid MailChimp API key supplied.");
            }
            list(, $data_center) = explode('-', $this->api_key);
            $this->api_endpoint = str_replace('<dc>', $data_center, $this->api_endpoint);
        } else {
            $this->api_endpoint = $api_endpoint;
        }

        $this->last_response = array('headers' => null, 'body' => null);
    }

    /**
     * Create a new instance of a Batch request. Optionally with the ID of an existing batch.
     *
     * @param string $batch_id Optional ID of an existing batch, if you need to check its status for example.
     *
     * @return Batch            New Batch object.
     */
    public function new_batch($batch_id = null)
    {
        return new Batch($this, $batch_id);
    }

    /**
     * @return string The url to the API endpoint
     */
    public function getApiEndpoint()
    {
        return $this->api_endpoint;
    }

    /**
     * Convert an email address into a 'subscriber hash' for identifying the subscriber in a method URL
     *
     * @param   string $email The subscriber's email address
     *
     * @return  string          Hashed version of the input
     */
    public static function subscriberHash($email)
    {
        return md5(strtolower($email));
    }

    /**
     * Was the last request successful?
     *
     * @return bool  True for success, false for failure
     */
    public function success()
    {
        return $this->request_successful;
    }

    /**
     * Get the last error returned by either the network transport, or by the API.
     * If something didn't work, this should contain the string describing the problem.
     *
     * @return  string|false  describing the error
     */
    public function getLastError()
    {
        return $this->last_error ?: false;
    }

    /**
     * Get an array containing the HTTP headers and the body of the API response.
     *
     * @return array  Assoc array with keys 'headers' and 'body'
     */
    public function getLastResponse()
    {
        return $this->last_response;
    }

    /**
     * Get an array containing the HTTP headers and the body of the API request.
     *
     * @return array  Assoc array
     */
    public function getLastRequest()
    {
        return $this->last_request;
    }

    /**
     * Make an HTTP DELETE request - for deleting data
     *
     * @param   string $method  URL of the API request method
     * @param   array  $args    Assoc array of arguments (if any)
     * @param   int    $timeout Timeout limit for request in seconds
     *
     * @return  array|false   Assoc array of API response, decoded from JSON
     */
    public function delete($method, $args = array(), $timeout = self::TIMEOUT)
    {
        return $this->makeRequest('delete', $method, $args, $timeout);
    }

    /**
     * Make an HTTP GET request - for retrieving data
     *
     * @param   string $method  URL of the API request method
     * @param   array  $args    Assoc array of arguments (usually your data)
     * @param   int    $timeout Timeout limit for request in seconds
     *
     * @return  array|false   Assoc array of API response, decoded from JSON
     */
    public function get($method, $args = array(), $timeout = self::TIMEOUT)
    {
        return $this->makeRequest('get', $method, $args, $timeout);
    }

    /**
     * Make an HTTP PATCH request - for performing partial updates
     *
     * @param   string $method  URL of the API request method
     * @param   array  $args    Assoc array of arguments (usually your data)
     * @param   int    $timeout Timeout limit for request in seconds
     *
     * @return  array|false   Assoc array of API response, decoded from JSON
     */
    public function patch($method, $args = array(), $timeout = self::TIMEOUT)
    {
        return $this->makeRequest('patch', $method, $args, $timeout);
    }

    /**
     * Make an HTTP POST request - for creating and updating items
     *
     * @param   string $method  URL of the API request method
     * @param   array  $args    Assoc array of arguments (usually your data)
     * @param   int    $timeout Timeout limit for request in seconds
     *
     * @return  array|false   Assoc array of API response, decoded from JSON
     */
    public function post($method, $args = array(), $timeout = self::TIMEOUT)
    {
        return $this->makeRequest('post', $method, $args, $timeout);
    }

    /**
     * Make an HTTP PUT request - for creating new items
     *
     * @param   string $method  URL of the API request method
     * @param   array  $args    Assoc array of arguments (usually your data)
     * @param   int    $timeout Timeout limit for request in seconds
     *
     * @return  array|false   Assoc array of API response, decoded from JSON
     */
    public function put($method, $args = array(), $timeout = self::TIMEOUT)
    {
        return $this->makeRequest('put', $method, $args, $timeout);
    }

    /**
     * Performs the underlying HTTP request. Not very exciting.
     *
     * @param  string $http_verb The HTTP verb to use: get, post, put, patch, delete
     * @param  string $method    The API method to be called
     * @param  array  $args      Assoc array of parameters to be passed
     * @param int     $timeout
     *
     * @return array|false Assoc array of decoded result
     */
    private function makeRequest($http_verb, $method, $args = array(), $timeout = self::TIMEOUT)
    {
        $url = $this->api_endpoint . '/' . $method;

        $response = $this->prepareStateForRequest($http_verb, $method, $url, $timeout);

        $httpHeader = array(
            'Accept: application/vnd.api+json',
            'Content-Type: application/vnd.api+json',
            'Authorization: apikey ' . $this->api_key
        );

        if (isset($args["language"])) {
            $httpHeader[] = "Accept-Language: " . $args["language"];
        }

        if ($http_verb === 'put') {
            $httpHeader[] = 'Allow: PUT, PATCH, POST';
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
        curl_setopt($ch, CURLOPT_USERAGENT, 'DrewM/MailChimp-API/3.0 (github.com/drewm/mailchimp-api)');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
        curl_setopt($ch, CURLOPT_ENCODING, '');
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);

        switch ($http_verb) {
            case 'post':
                curl_setopt($ch, CURLOPT_POST, true);
                $this->attachRequestPayload($ch, $args);
                break;

            case 'get':
                $query = http_build_query($args, '', '&');
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $query);
                break;

            case 'delete':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;

            case 'patch':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
                $this->attachRequestPayload($ch, $args);
                break;

            case 'put':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                $this->attachRequestPayload($ch, $args);
                break;
        }

        $responseContent     = curl_exec($ch);
        $response['headers'] = curl_getinfo($ch);
        $response            = $this->setResponseState($response, $responseContent, $ch);
        $formattedResponse   = $this->formatResponse($response);

        curl_close($ch);

        $isSuccess = $this->determineSuccess($response, $formattedResponse, $timeout);

        return is_array($formattedResponse) ? $formattedResponse : $isSuccess;
    }

    /**
     * @param string  $http_verb
     * @param string  $method
     * @param string  $url
     * @param integer $timeout
     *
     * @return array
     */
    private function prepareStateForRequest($http_verb, $method, $url, $timeout)
    {
        $this->last_error = '';

        $this->request_successful = false;

        $this->last_response = array(
            'headers'     => null, // array of details from curl_getinfo()
            'httpHeaders' => null, // array of HTTP headers
            'body'        => null // content of the response
        );

        $this->last_request = array(
            'method'  => $http_verb,
            'path'    => $method,
            'url'     => $url,
            'body'    => '',
            'timeout' => $timeout,
        );

        return $this->last_response;
    }

    /**
     * Get the HTTP headers as an array of header-name => header-value pairs.
     *
     * The "Link" header is parsed into an associative array based on the
     * rel names it contains. The original value is available under
     * the "_raw" key.
     *
     * @param string $headersAsString
     *
     * @return array
     */
    private function getHeadersAsArray($headersAsString)
    {
        $headers = array();

        foreach (explode("\r\n", $headersAsString) as $i => $line) {
            if (preg_match('/HTTP\/[1-2]/', substr($line, 0, 7)) === 1) { // http code
                continue;
            }

            $line = trim($line);
            if (empty($line)) {
                continue;
            }

            list($key, $value) = explode(':', $line);
            $value = ltrim($value);

            if ($key == 'Link') {
                $value = array_merge(
                    array('_raw' => $value),
                    $this->getLinkHeaderAsArray($value)
                );
            }

            $headers[$key] = $value;
        }

        return $headers;
    }

    /**
     * Extract all rel => URL pairs from the provided Link header value
     *
     * Mailchimp only implements the URI reference and relation type from
     * RFC 5988, so the value of the header is something like this:
     *
     * 'https://us13.api.mailchimp.com/schema/3.0/Lists/Instance.json; rel="describedBy",
     * <https://us13.admin.mailchimp.com/lists/members/?id=XXXX>; rel="dashboard"'
     *
     * @param string $linkHeaderAsString
     *
     * @return array
     */
    private function getLinkHeaderAsArray($linkHeaderAsString)
    {
        $urls = array();

        if (preg_match_all('/<(.*?)>\s*;\s*rel="(.*?)"\s*/', $linkHeaderAsString, $matches)) {
            foreach ($matches[2] as $i => $relName) {
                $urls[$relName] = $matches[1][$i];
            }
        }

        return $urls;
    }

    /**
     * Encode the data and attach it to the request
     *
     * @param   resource $ch   cURL session handle, used by reference
     * @param   array    $data Assoc array of data to attach
     */
    private function attachRequestPayload(&$ch, $data)
    {
        $encoded                    = json_encode($data);
        $this->last_request['body'] = $encoded;
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
    }

    /**
     * Decode the response and format any error messages for debugging
     *
     * @param array $response The response from the curl request
     *
     * @return array|false    The JSON decoded into an array
     */
    private function formatResponse($response)
    {
        $this->last_response = $response;

        if (!empty($response['body'])) {
            return json_decode($response['body'], true);
        }

        return false;
    }

    /**
     * Do post-request formatting and setting state from the response
     *
     * @param array    $response        The response from the curl request
     * @param string   $responseContent The body of the response from the curl request
     * @param resource $ch              The curl resource
     *
     * @return array    The modified response
     */
    private function setResponseState($response, $responseContent, $ch)
    {
        if ($responseContent === false) {
            $this->last_error = curl_error($ch);
        } else {

            $headerSize = $response['headers']['header_size'];

            $response['httpHeaders'] = $this->getHeadersAsArray(substr($responseContent, 0, $headerSize));
            $response['body']        = substr($responseContent, $headerSize);

            if (isset($response['headers']['request_header'])) {
                $this->last_request['headers'] = $response['headers']['request_header'];
            }
        }

        return $response;
    }

    /**
     * Check if the response was successful or a failure. If it failed, store the error.
     *
     * @param array       $response          The response from the curl request
     * @param array|false $formattedResponse The response body payload from the curl request
     * @param int         $timeout           The timeout supplied to the curl request.
     *
     * @return bool     If the request was successful
     */
    private function determineSuccess($response, $formattedResponse, $timeout)
    {
        $status = $this->findHTTPStatus($response, $formattedResponse);

        if ($status >= 200 && $status <= 299) {
            $this->request_successful = true;
            return true;
        }

        if (isset($formattedResponse['detail'])) {
            $this->last_error = sprintf('%d: %s', $formattedResponse['status'], $formattedResponse['detail']);
            return false;
        }

        if ($timeout > 0 && $response['headers'] && $response['headers']['total_time'] >= $timeout) {
            $this->last_error = sprintf('Request timed out after %f seconds.', $response['headers']['total_time']);
            return false;
        }

        $this->last_error = 'Unknown error, call getLastResponse() to find out what happened.';
        return false;
    }

    /**
     * Find the HTTP status code from the headers or API response body
     *
     * @param array       $response          The response from the curl request
     * @param array|false $formattedResponse The response body payload from the curl request
     *
     * @return int  HTTP status code
     */
    private function findHTTPStatus($response, $formattedResponse)
    {
        if (!empty($response['headers']) && isset($response['headers']['http_code'])) {
            return (int)$response['headers']['http_code'];
        }

        if (!empty($response['body']) && isset($formattedResponse['status'])) {
            return (int)$formattedResponse['status'];
        }

        return 418;
    }
}


text:
using System;
using System.Collections;

namespace JenkinsConsoleUtility.Util
{
    public static class JcuUtil
    {
        public static void FancyWriteToConsole(params object[] lines)
        {
            Console.ForegroundColor = ConsoleColor.White;
            _FancyWriteToConsole(lines);
            Console.ForegroundColor = ConsoleColor.White;
        }

        private static void _FancyWriteToConsole(params object[] lines)
        {
            if (lines == null)
            {
                Console.Write("\n");
                return;
            }
            foreach (var each in lines)
            {
                if (each is ConsoleColor)
                    Console.ForegroundColor = (ConsoleColor)each;
                else if (each is string)
                    Console.Write(each);
                else if (each is IEnumerable)
                    foreach (var intEach in (IEnumerable)each)
                        _FancyWriteToConsole(intEach);
                else
                    Console.Write(each);
            }
            Console.Write("\n");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using BizHawk.Client.Common;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Nintendo.Gameboy;
using BizHawk.Emulation.Cores.PCEngine;
using BizHawk.Emulation.Cores.Sega.MasterSystem;
using BizHawk.Client.ApiHawk.Classes.Events;
using System.IO;

namespace BizHawk.Client.ApiHawk
{
	/// <summary>
	/// This class contains some methods that
	/// interract with BizHawk client
	/// </summary>
	public static class ClientApi
	{
		#region Fields

		private static IEmulator Emulator;
		private static IVideoProvider VideoProvider;

		private static readonly Assembly clientAssembly;
		private static readonly object clientMainFormInstance;
		private static readonly Type mainFormClass;
		private static readonly Array joypadButtonsArray = Enum.GetValues(typeof(JoypadButton));

		internal static readonly BizHawkSystemIdToEnumConverter SystemIdConverter = new BizHawkSystemIdToEnumConverter();
		internal static readonly JoypadStringToEnumConverter JoypadConverter = new JoypadStringToEnumConverter();

		private static List<Joypad> allJoypads;

		/// <summary>
		/// Occurs before a quickload is done (just after user has pressed the shortcut button
		/// or has click on the item menu)
		/// </summary>
		public static event BeforeQuickLoadEventHandler BeforeQuickLoad;
		/// <summary>
		/// Occurs before a quicksave is done (just after user has pressed the shortcut button
		/// or has click on the item menu)
		/// </summary>
		public static event BeforeQuickSaveEventHandler BeforeQuickSave;
		/// <summary>
		/// Occurs when a ROM is succesfully loaded
		/// </summary>
		public static event EventHandler RomLoaded;
		/// <summary>
		/// Occurs when a savestate is sucessfully loaded
		/// </summary>
		public static event StateLoadedEventHandler StateLoaded;
		/// <summary>
		/// Occurs when a savestate is successfully saved
		/// </summary>
		public static event StateSavedEventHandler StateSaved;

		#endregion

		#region cTor(s)

		/// <summary>
		/// Static stuff initilization
		/// </summary>
		static ClientApi()
		{
			clientAssembly = Assembly.GetEntryAssembly();
			clientMainFormInstance = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin").GetField("MainForm").GetValue(null);
			mainFormClass = clientAssembly.GetType("BizHawk.Client.EmuHawk.MainForm");
		}

		public static void UpdateEmulatorAndVP(IEmulator emu = null)
		{
			Emulator = emu;
			VideoProvider = Emulation.Common.IEmulatorExtensions.Extensions.AsVideoProviderOrDefault(emu);
		}

		#endregion

		#region Methods

		#region Helpers

		private static void InvokeMainFormMethod(string name, dynamic[] paramList = null)
		{
			List<Type> typeList = new List<Type>();
			MethodInfo method;
			if (paramList != null)
			{
				foreach (var obj in paramList)
				{
					typeList.Add(obj.GetType());
				}
				method = mainFormClass.GetMethod(name, typeList.ToArray());
			}
			else method = mainFormClass.GetMethod(name);

			if(method != null)
				method.Invoke(clientMainFormInstance, paramList);
		}

		private static object GetMainFormField(string name)
		{
			return mainFormClass.GetField(name);
		}

		private static void SetMainFormField(string name, object value)
		{
			mainFormClass.GetField(name).SetValue(clientMainFormInstance, value);
		}

		#endregion

		#region Public
		/// <summary>
		/// THE FrameAdvance stuff
		/// </summary>
		public static void DoFrameAdvance()
		{
			InvokeMainFormMethod("FrameAdvance", null);

			InvokeMainFormMethod("StepRunLoop_Throttle", null);

			InvokeMainFormMethod("Render", null);
		}

		/// <summary>
		/// THE FrameAdvance stuff
		/// Auto unpause emulation
		/// </summary>
		public static void DoFrameAdvanceAndUnpause()
		{
			DoFrameAdvance();
			UnpauseEmulation();
		}

		/// <summary>
		/// Gets a <see cref="Joypad"/> for specified player
		/// </summary>
		/// <param name="player">Player (one based) you want current inputs</param>
		/// <returns>A <see cref="Joypad"/> populated with current inputs</returns>
		/// <exception cref="IndexOutOfRangeException">Raised when you specify a player less than 1 or greater than maximum allows (see SystemInfo class to get this information)</exception>
		public static Joypad GetInput(int player)
		{
			if (player < 1 || player > RunningSystem.MaxControllers)
			{
				throw new IndexOutOfRangeException($"{RunningSystem.DisplayName} does not support {player} controller(s)");
			}
			else
			{
				GetAllInputs();
				return allJoypads[player - 1];
			}
		}

		/// <summary>
		/// Load a savestate specified by its name
		/// </summary>
		/// <param name="name">Savetate friendly name</param>
		public static void LoadState(string name)
		{
			InvokeMainFormMethod("LoadState", new object[] { Path.Combine(PathManager.GetSaveStatePath(Global.Game), $"{name}.State"), name, false, false });
		}

		/// <summary>
		/// Raised before a quickload is done (just after pressing shortcut button)
		/// </summary>
		/// <param name="sender">Object who raised the event</param>
		/// <param name="quickSaveSlotName">Slot used for quickload</param>
		/// <param name="eventHandled">A boolean that can be set if users want to handle save themselves; if so, BizHawk won't do anything</param>
		public static void OnBeforeQuickLoad(object sender, string quickSaveSlotName, out bool eventHandled)
		{
			eventHandled = false;
			if (BeforeQuickLoad != null)
			{
				BeforeQuickLoadEventArgs e = new BeforeQuickLoadEventArgs(quickSaveSlotName);
				BeforeQuickLoad(sender, e);
				eventHandled = e.Handled;
			}
		}

		/// <summary>
		/// Raised before a quicksave is done (just after pressing shortcut button)
		/// </summary>
		/// <param name="sender">Object who raised the event</param>
		/// <param name="quickSaveSlotName">Slot used for quicksave</param>
		/// <param name="eventHandled">A boolean that can be set if users want to handle save themselves; if so, BizHawk won't do anything</param>
		public static void OnBeforeQuickSave(object sender, string quickSaveSlotName, out bool eventHandled)
		{
			eventHandled = false;
			if (BeforeQuickSave != null)
			{
				BeforeQuickSaveEventArgs e = new BeforeQuickSaveEventArgs(quickSaveSlotName);
				BeforeQuickSave(sender, e);
				eventHandled = e.Handled;
			}
		}

		/// <summary>
		/// Raise when a state is loaded
		/// </summary>
		/// <param name="sender">Object who raised the event</param>
		/// <param name="stateName">User friendly name for saved state</param>
		public static void OnStateLoaded(object sender, string stateName)
		{
			if (StateLoaded != null)
			{
				StateLoaded(sender, new StateLoadedEventArgs(stateName));
			}
		}

		/// <summary>
		/// Raise when a state is saved
		/// </summary>
		/// <param name="sender">Object who raised the event</param>
		/// <param name="stateName">User friendly name for saved state</param>
		public static void OnStateSaved(object sender, string stateName)
		{
			if (StateSaved != null)
			{
				StateSaved(sender, new StateSavedEventArgs(stateName));
			}
		}

		/// <summary>
		/// Raise when a rom is successfully Loaded
		/// </summary>
		public static void OnRomLoaded(IEmulator emu)
		{
			Emulator = emu;
			VideoProvider = Emulation.Common.IEmulatorExtensions.Extensions.AsVideoProviderOrDefault(emu);
			RomLoaded?.Invoke(null, EventArgs.Empty);

			allJoypads = new List<Joypad>(RunningSystem.MaxControllers);
			for (int i = 1; i <= RunningSystem.MaxControllers; i++)
			{
				allJoypads.Add(new Joypad(RunningSystem, i));
			}
		}

		/// <summary>
		/// Save a state with specified name
		/// </summary>
		/// <param name="name">Savetate friendly name</param>
		public static void SaveState(string name)
		{
			InvokeMainFormMethod("SaveState", new object[] { Path.Combine(PathManager.GetSaveStatePath(Global.Game), $"{name}.State"), name, false });
		}

		/// <summary>
		/// Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements
		/// </summary>
		/// <param name="left">Left padding</param>
		/// <param name="top">Top padding</param>
		/// <param name="right">Right padding</param>
		/// <param name="bottom">Bottom padding</param>
		public static void SetGameExtraPadding(int left, int top, int right, int bottom)
		{
			FieldInfo f = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin").GetField("DisplayManager");
			object displayManager = f.GetValue(null);
			f = f.FieldType.GetField("GameExtraPadding");
			f.SetValue(displayManager, new Padding(left, top, right, bottom));

			InvokeMainFormMethod("FrameBufferResized");
		}

		/// <summary>
		/// Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements
		/// </summary>
		/// <param name="left">Left padding</param>
		public static void SetGameExtraPadding(int left)
		{
			SetGameExtraPadding(left, 0, 0, 0);
		}

		/// <summary>
		/// Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements
		/// </summary>
		/// <param name="left">Left padding</param>
		/// <param name="top">Top padding</param>
		public static void SetGameExtraPadding(int left, int top)
		{
			SetGameExtraPadding(left, top, 0, 0);
		}

		/// <summary>
		/// Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements
		/// </summary>
		/// <param name="left">Left padding</param>
		/// <param name="top">Top padding</param>
		/// <param name="right">Right padding</param>
		public static void SetGameExtraPadding(int left, int top, int right)
		{
			SetGameExtraPadding(left, top, right, 0);
		}

		/// <summary>
		/// Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements
		/// </summary>
		/// <param name="left">Left padding</param>
		/// <param name="top">Top padding</param>
		/// <param name="right">Right padding</param>
		/// <param name="bottom">Bottom padding</param>
		public static void SetExtraPadding(int left, int top, int right, int bottom)
		{
			FieldInfo f = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin").GetField("DisplayManager");
			object displayManager = f.GetValue(null);
			f = f.FieldType.GetField("ClientExtraPadding");
			f.SetValue(displayManager, new Padding(left, top, right, bottom));

			InvokeMainFormMethod("FrameBufferResized");
		}

		/// <summary>
		/// Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements
		/// </summary>
		/// <param name="left">Left padding</param>
		public static void SetExtraPadding(int left)
		{
			SetExtraPadding(left, 0, 0, 0);
		}

		/// <summary>
		/// Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements
		/// </summary>
		/// <param name="left">Left padding</param>
		/// <param name="top">Top padding</param>
		public static void SetExtraPadding(int left, int top)
		{
			SetExtraPadding(left, top, 0, 0);
		}

		/// <summary>
		/// Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements
		/// </summary>
		/// <param name="left">Left padding</param>
		/// <param name="top">Top padding</param>
		/// <param name="right">Right padding</param>
		public static void SetExtraPadding(int left, int top, int right)
		{
			SetExtraPadding(left, top, right, 0);
		}

		/// <summary>
		/// Set inputs in specified <see cref="Joypad"/> to specified player
		/// </summary>
		/// <param name="player">Player (one based) whom inputs must be set</param>
		/// <param name="joypad"><see cref="Joypad"/> with inputs</param>
		/// <exception cref="IndexOutOfRangeException">Raised when you specify a player less than 1 or greater than maximum allows (see SystemInfo class to get this information)</exception>
		/// <remarks>Still have some strange behaviour with multiple inputs; so this feature is still in beta</remarks>
		public static void SetInput(int player, Joypad joypad)
		{
			if (player < 1 || player > RunningSystem.MaxControllers)
			{
				throw new IndexOutOfRangeException($"{RunningSystem.DisplayName} does not support {player} controller(s)");
			}
			else
			{
				if (joypad.Inputs == 0)
				{
					AutoFireStickyXorAdapter joypadAdaptor = Global.AutofireStickyXORAdapter;
					joypadAdaptor.ClearStickies();
				}
				else
				{
					foreach (JoypadButton button in joypadButtonsArray)
					{
						if (joypad.Inputs.HasFlag(button))
						{
							AutoFireStickyXorAdapter joypadAdaptor = Global.AutofireStickyXORAdapter;
							if (RunningSystem == SystemInfo.GB)
							{
								joypadAdaptor.SetSticky($"{JoypadConverter.ConvertBack(button, RunningSystem)}", true);
							}
							else
							{
								joypadAdaptor.SetSticky($"P{player} {JoypadConverter.ConvertBack(button, RunningSystem)}", true);
							}
						}
					}
				}

				//Using this break joypad usage (even in UI); have to figure out why
				/*if ((RunningSystem.AvailableButtons & JoypadButton.AnalogStick) == JoypadButton.AnalogStick)
				{
					AutoFireStickyXorAdapter joypadAdaptor = Global.AutofireStickyXORAdapter;
					for (int i = 1; i <= RunningSystem.MaxControllers; i++)
					{
						joypadAdaptor.SetFloat($"P{i} X Axis", allJoypads[i - 1].AnalogX);
						joypadAdaptor.SetFloat($"P{i} Y Axis", allJoypads[i - 1].AnalogY);
					}
				}*/
			}
		}

		/// <summary>
		/// Resume the emulation
		/// </summary>
		public static void UnpauseEmulation()
		{
			InvokeMainFormMethod("UnpauseEmulator", null);
		}
		#endregion Public

		/// <summary>
		/// Gets all current inputs for each joypad and store
		/// them in <see cref="Joypad"/> class collection
		/// </summary>
		private static void GetAllInputs()
		{
			AutoFireStickyXorAdapter joypadAdaptor = Global.AutofireStickyXORAdapter;

			IEnumerable<string> pressedButtons = from button in joypadAdaptor.Definition.BoolButtons
												 where joypadAdaptor.IsPressed(button)
												 select button;

			foreach (Joypad j in allJoypads)
			{
				j.ClearInputs();
			}

			Parallel.ForEach<string>(pressedButtons, button =>
			{
				int player;
				if (RunningSystem == SystemInfo.GB)
				{
					allJoypads[0].AddInput(JoypadConverter.Convert(button));
				}
				else
				{
					if (int.TryParse(button.Substring(1, 2), out player))
					{
						allJoypads[player - 1].AddInput(JoypadConverter.Convert(button.Substring(3)));
					}
				}
			});

			if ((RunningSystem.AvailableButtons & JoypadButton.AnalogStick) == JoypadButton.AnalogStick)
			{
				for (int i = 1; i <= RunningSystem.MaxControllers; i++)
				{
					allJoypads[i - 1].AnalogX = joypadAdaptor.GetFloat($"P{i} X Axis");
					allJoypads[i - 1].AnalogY = joypadAdaptor.GetFloat($"P{i} Y Axis");
				}
			}
		}

		public static void CloseEmulator()
		{
			InvokeMainFormMethod("CloseEmulator");
		}

		public static void CloseEmulatorWithCode(int exitCode)
		{
			InvokeMainFormMethod("CloseEmulator", new object[] {exitCode});
		}

		public static int BorderHeight()
		{
			var point = new System.Drawing.Point(0, 0);
			Type t = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin");
			FieldInfo f = t.GetField("DisplayManager");
			object displayManager = f.GetValue(null);
			MethodInfo m = t.GetMethod("TransFormPoint");
			point = (System.Drawing.Point) m.Invoke(displayManager, new object[] { point });
			return point.Y;
		}

		public static int BorderWidth()
		{
			var point = new System.Drawing.Point(0, 0);
			Type t = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin");
			FieldInfo f = t.GetField("DisplayManager");
			object displayManager = f.GetValue(null);
			MethodInfo m = t.GetMethod("TransFormPoint");
			point = (System.Drawing.Point)m.Invoke(displayManager, new object[] { point });
			return point.X;
		}

		public static int BufferHeight()
		{
			return VideoProvider.BufferHeight;
		}

		public static int BufferWidth()
		{
			return VideoProvider.BufferWidth;
		}

		public static void ClearAutohold()
		{
			InvokeMainFormMethod("ClearHolds");
		}

		public static void CloseRom()
		{
			InvokeMainFormMethod("CloseRom");
		}

		public static void DisplayMessages(bool value)
		{
			Global.Config.DisplayMessages = value;
		}

		public static void EnableRewind(bool enabled)
		{
			InvokeMainFormMethod("EnableRewind", new object[] {enabled});
		}

		public static void FrameSkip(int numFrames)
		{
			if (numFrames > 0)
			{
				Global.Config.FrameSkip = numFrames;
				InvokeMainFormMethod("FrameSkipMessage");
			}
			else
			{
				Console.WriteLine("Invalid frame skip value");
			}
		}

		public static int GetTargetScanlineIntensity()
		{
			return Global.Config.TargetScanlineFilterIntensity;
		}

		public static int GetWindowSize()
		{
			return Global.Config.TargetZoomFactors[Emulator.SystemId];
		}

		public static void SetSoundOn(bool enable)
		{
			Global.Config.SoundEnabled = enable;
		}

		public static bool GetSoundOn()
		{
			return Global.Config.SoundEnabled;
		}

		public static bool IsPaused()
		{
			return (bool) GetMainFormField("EmulatorPaused");
		}

		public static bool IsTurbo()
		{
			return (bool)GetMainFormField("IsTurboing");
		}

		public static bool IsSeeking()
		{
			return (bool)GetMainFormField("IsSeeking");
		}

		public static void OpenRom(string path)
		{
			var ioa = OpenAdvancedSerializer.ParseWithLegacy(path);
			Type t = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin.MainForm.LoadRomArgs");
			object o = Activator.CreateInstance(t);
			t.GetField("OpenAdvanced").SetValue(o, ioa);

			InvokeMainFormMethod("LoadRom", new object[] {path, o});
		}

		public static void Pause()
		{
			InvokeMainFormMethod("PauseEmulator");
		}

		public static void PauseAv()
		{
			SetMainFormField("PauseAvi", true);
		}

		public static void RebootCore()
		{
			InvokeMainFormMethod("RebootCore");
		}

		public static void SaveRam()
		{
			InvokeMainFormMethod("FlushSaveRAM");
		}

		public static int ScreenHeight()
		{
			Type t = GetMainFormField("PresentationPanel").GetType();
			object o = GetMainFormField("PresentationPanel");
			o = t.GetField("NativeSize").GetValue(o);
			t = t.GetField("NativeSize").GetType();

			return (int) t.GetField("Height").GetValue(o);
		}

		public static void Screenshot(string path = null)
		{
			if (path == null)
			{
				InvokeMainFormMethod("TakeScreenshot");
			}
			else
			{
				InvokeMainFormMethod("TakeScreenshot", new object[] {path});
			}
		}

		public static void ScreenshotToClipboard()
		{
			InvokeMainFormMethod("TakeScreenshotToClipboard");
		}

		public static void SetTargetScanlineIntensity(int val)
		{
			Global.Config.TargetScanlineFilterIntensity = val;
		}

		public static void SetScreenshotOSD(bool value)
		{
			Global.Config.Screenshot_CaptureOSD = value;
		}

		public static int ScreenWidth()
		{
			Type t = GetMainFormField("PresentationPanel").GetType();
			object o = GetMainFormField("PresentationPanel");
			o = t.GetField("NativeSize").GetValue(o);
			t = t.GetField("NativeSize").GetType();

			return (int) t.GetField("Width").GetValue(o);
		}

		public static void SetWindowSize(int size)
		{
			if (size == 1 || size == 2 || size == 3 || size == 4 || size == 5 || size == 10)
			{
				Global.Config.TargetZoomFactors[Emulator.SystemId] = size;
				InvokeMainFormMethod("FrameBufferResized");
				Type t = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin");
				FieldInfo f = t.GetField("OSD");
				object osd = f.GetValue(null);
				t = f.GetType();
				MethodInfo m = t.GetMethod("AddMessage");
				m.Invoke(osd, new Object[] { $"Window size set to {size}x" });
			}
			else
			{
				Console.WriteLine("Invalid window size");
			}
		}

		public static void SpeedMode(int percent)
		{
			if (percent > 0 && percent < 6400)
			{
				InvokeMainFormMethod("ClickSpeedItem", new object[] {percent});
			}
			else
			{
				Console.WriteLine("Invalid speed value");
			}
		}

		public static void TogglePause()
		{
			InvokeMainFormMethod("TogglePause");
		}

		public static int TransformPointX(int x)
		{
			var point = new System.Drawing.Point(x, 0);
			Type t = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin");
			FieldInfo f = t.GetField("DisplayManager");
			object displayManager = f.GetValue(null);
			MethodInfo m = t.GetMethod("TransFormPoint");
			point = (System.Drawing.Point)m.Invoke(displayManager, new object[] { point });
			return point.X;
		}

		public static int TransformPointY(int y)
		{
			var point = new System.Drawing.Point(0, y);
			Type t = clientAssembly.GetType("BizHawk.Client.EmuHawk.GlobalWin");
			FieldInfo f = t.GetField("DisplayManager");
			object displayManager = f.GetValue(null);
			MethodInfo m = t.GetMethod("TransFormPoint");
			point = (System.Drawing.Point)m.Invoke(displayManager, new object[] { point });
			return point.Y;
		}

		public static void Unpause()
		{
			InvokeMainFormMethod("UnpauseEmulator");
		}

		public static void UnpauseAv()
		{
			SetMainFormField("PauseAvi", false);
		}

		public static int Xpos()
		{
			object o = GetMainFormField("DesktopLocation");
			Type t = mainFormClass.GetField("DesktopLocation").GetType();
			return (int)t.GetField("X").GetValue(o);
		}

		public static int Ypos()
		{
			object o = GetMainFormField("DesktopLocation");
			Type t = mainFormClass.GetField("DesktopLocation").GetType();
			return (int)t.GetField("Y").GetValue(o);
		}

		#endregion

		#region Properties

		/// <summary>
		/// Gets current emulated system
		/// </summary>
		public static SystemInfo RunningSystem
		{
			get
			{
				switch (Global.Emulator.SystemId)
				{
					case "PCE":
						if (((PCEngine)Global.Emulator).Type == NecSystemType.TurboGrafx)
						{
							return SystemInfo.PCE;
						}
						else if (((PCEngine)Global.Emulator).Type == NecSystemType.SuperGrafx)
						{
							return SystemInfo.SGX;
						}
						else
						{
							return SystemInfo.PCECD;
						}

					case "SMS":
						if (((SMS)Global.Emulator).IsSG1000)
						{
							return SystemInfo.SG;
						}
						else if (((SMS)Global.Emulator).IsGameGear)
						{
							return SystemInfo.GG;
						}
						else
						{
							return SystemInfo.SMS;
						}

					case "GB":
						if (Global.Emulator is Gameboy)
						{
							return SystemInfo.GB;
						}
						else if (Global.Emulator is GBColors)
						{
							return SystemInfo.GBC;
						}
						else
						{
							return SystemInfo.DualGB;
						}

					default:
						return SystemInfo.FindByCoreSystem(SystemIdConverter.Convert(Global.Emulator.SystemId));
				}
			}
		}

		#endregion
	}
}


text:
  <metron-config-navbar></metron-config-navbar>

<metron-config-vertical-navbar></metron-config-vertical-navbar>

<router-outlet></router-outlet>

<router-outlet name="dialog" ></router-outlet>


text:
import THREE from 'three'
import CANNON from 'cannon'
import WebGLRenderer from './WebGLRenderer'
import Scene from './Scene'
import Camera from './Camera'

import TweenMax from 'gsap'

import DAT from 'dat-gui'

const MODEL_DATA = require('../models/scene.json')
const NUM_BOXES = 80

var boxObjects = [], isAnimating = false;
var bodies = []
var world, timeStep = 1/60;

export default class App {

  constructor (targetEl) {
    this.physicsActive = false
    this.mouse = new THREE.Vector2()
    this.raycaster = new THREE.Raycaster()

    this.scene = new Scene()
    this.camera = new Camera()
    this.renderer = new WebGLRenderer(targetEl)

    this.rootObj = new THREE.Object3D()
    // this.setupLights()
    this.loadModel()
    this.worldPos = new THREE.Vector3(0, 0, 0)

    this.scene.add(this.rootObj)

    this.rootObj.position.x = -10
    this.rootObj.position.y = -10
    this.rootObj.rotation.y = 0.6
    this.rootObj.rotation.x = 0.8
    this.rootObj.rotation.z = -0.4

    this.rootObj.posOrigin = this.rootObj.position.clone()
    this.rootObj.rotOrigin = this.rootObj.rotation.clone()

    // this.animateContainer()
    this.animate()
    this.setupGUI()

    targetEl.addEventListener( 'mousemove', this.onMouseMove.bind(this), false )
    // document.addEventListener( 'mousedown', this.onMouseDown.bind(this), false )
    targetEl.addEventListener( 'click', this.onDocumentClick.bind(this), false )

  }

  initCannon() {
    world = new CANNON.World();
    world.gravity.set(0,-50,0);
    world.broadphase = new CANNON.NaiveBroadphase();
    world.solver.iterations = 10;
    var shape = new CANNON.Box(new CANNON.Vec3(2.7, 2.7, 2.7));
    var mass = 1;

    for (var i = 0; i < boxObjects.length; i++) {

      var body = new CANNON.Body({
        mass: mass
      });
      body.addShape(shape);
      body.angularVelocity.set(this.randomNumber(-15, 15),this.randomNumber(-15, 15),this.randomNumber(-15, 15));
      body.angularDamping = 0.5;
      world.addBody(body);

      var pos = boxObjects[i].origin
      body.position.set(pos.x, pos.y, pos.z)
      bodies.push(body)
    }

    // Create a plane
    var groundShape = new CANNON.Plane();
    var groundBody = new CANNON.Body({ mass: 0 });
    groundBody.addShape(groundShape);
    groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0),-Math.PI/2);
    groundBody.position.set(0, -20, 0)
    world.addBody(groundBody);

  }

  setupGUI() {
    var gui = new DAT.GUI()

    var children = this.rootObj.children[0].children

    for (var i in children) {
      var child = children[i]
      if (child.type == 'SpotLight') {
        this.dirLight = child
      } else if(child.type == 'HemisphereLight') {
        this.hemiLight = child
      }
    }

    //settings
    this.dirLight.intensity = 1.1
    this.dirLight.color = new THREE.Color(0xe8deaf)
    this.dirLight.exponent = 300
    this.dirLight.position.copy(new THREE.Vector3(471, 500, 107))

    this.hemiLight.color = new THREE.Color(0xf0bcbc)
    this.hemiLight.intensity = 0.64

    this.material.color = new THREE.Color(0xbb9161)
    this.material.emissive = new THREE.Color(0x59421f)
    this.scene.fog.density = 0.0121

    // lights
    var currLightColor = this.dirLight.color
    var hemiColor = this.hemiLight.color
    var lightColor = {
      color: [ currLightColor.r*255, currLightColor.g*255, currLightColor.b*255 ],
      hemiColor: [ hemiColor.r*255, hemiColor.g*255, hemiColor.b*255 ]
    }
    var lights = gui.addFolder('Light')
    lights.add(this.dirLight, "intensity").min(0.01).max(2.0).step(0.05)

    lights.addColor(lightColor, "color").onChange( (val) => {
      this.dirLight.color = this.convertColor(val)
    })

    lights.add(this.dirLight, 'exponent').min(0).max(300)
    lights.add(this.dirLight.position, 'x').min(-500).max(500)
    lights.add(this.dirLight.position, 'y').min(-500).max(500)
    lights.add(this.dirLight.position, 'z').min(-500).max(500)

    lights.addColor(lightColor, "hemiColor").onChange( (val) => {
      this.hemiLight.color = this.convertColor(val)
    })
    lights.add(this.hemiLight, 'intensity').min(0).max(2)

    // material
    var mat = gui.addFolder('Material')
    var currMatColor = this.material.color
    var currMatEmissive = this.material.emissive
    var matColor = {
      color: [ currMatColor.r*255, currMatColor.g*255, currMatColor.b*255 ],
      emissive: [ currMatEmissive.r*255, currMatEmissive.g*255, currMatEmissive.b*255 ]
    }

    mat.addColor(matColor, 'color').onChange( (val) => {
      this.material.color = this.convertColor(val)
    })

    mat.addColor(matColor, 'emissive').onChange( (val) => {
      this.material.emissive = this.convertColor(val)
    })

    // scene fog
    var fog = gui.addFolder('Fog')
    fog.add(this.scene.fog, 'density').min(0).max(0.02)

  }

  convertColor(val) {
    var r = val[0]/255
    var g = val[1]/255
    var b = val[2]/255
    if (typeof val == 'string') {
      return new THREE.Color(val)
    } else {
      return new THREE.Color(r, g, b)
    }
  }

  getWorldPos() {
    var vector = new THREE.Vector3(this.mouse.x, this.mouse.y, 0.5)
    vector.unproject( this.camera )

    var dir = vector.sub( this.camera.position ).normalize()
    var distance = - this.camera.position.z / dir.z
    var pos = this.camera.position.clone().add( dir.multiplyScalar( distance ) )

    return pos
  }

  onMouseMove (e) {
    this.mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1
    this.mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1
  }

  onDocumentClick(e) {
    if (isAnimating) return;

    this.physicsActive = !this.physicsActive

    if (!this.physicsActive) {
      isAnimating = true
      this.animateBoxesOut(() => {
        this.animateBoxesIn()
        setTimeout(() => {
          isAnimating = false
        }, 1000);
      }, 0.01)
      this.resetBodies()

      var tPos = this.rootObj.posOrigin
      var tRot = this.rootObj.rotOrigin
      TweenMax.to(this.rootObj.position, 2, {z: 0})

    } else {
      TweenMax.to(this.rootObj.rotation, 2, {x: 0, y: 0, z: 0})
      TweenMax.to(this.rootObj.position, 2, {z: -10})
    }
  }

  resetBodies() {
    for( var i = 0; i < bodies.length; i++ ) {
      var body = bodies[i]
      var pos = boxObjects[i].origin
      body.angularVelocity.set(this.randomNumber(-15, 15),this.randomNumber(-15, 15),this.randomNumber(-15, 15));
      body.position.set(pos.x, pos.y, pos.z)
      body.quaternion.setFromEuler(0, 0, 0)
    }
  }

  loadModel (url) {
    var loader = new THREE.ObjectLoader()

    var scene = loader.parse(MODEL_DATA)

    this.material = scene.children[0].material
    for (var i in scene.children) {
      var child = scene.children[i]
      var geom = child.geometry
      if (geom) {
        child.origin = child.position.clone()

        var randX = this.randomNumber(-100, 100)
        var randY = this.randomNumber(-100, 100)
        var randZ = this.randomNumber(-100, 100)
        child.position.set(randX, randY, randZ)

        // fix material for the loner
        if (geom.faces.length == 32) {
          child.material = this.material
        }

        boxObjects.push(child)
      }
    }

    this.rootObj.add(scene)
    this.animateBoxesIn()
    this.initCannon()
  }

  animateBoxesIn() {
    for (var i = 0; i < boxObjects.length; i++) {
      var mesh = boxObjects[i]
      var pos = mesh.origin
      TweenMax.to(mesh.position, 1.5, {x: pos.x, y: pos.y, z: pos.z, delay: 0, ease: Power4.easeInOut})
      TweenMax.to(mesh.rotation, 1.5, {x: 0, y: 0, z: 0, delay: 0, ease: Power4.easeInOut})
    }
  }

  animateBoxesOut(onComplete, delay) {
    var completed = 0

    var del = delay || 0

    for (var i = 0; i < boxObjects.length; i++) {
      var posX = this.randomNumber(-50, 50)
      var posY = this.randomNumber(-50, 50)
      var posZ = this.randomNumber(-50, 50)
      var pos = new THREE.Vector3(posX, posY, posZ)
      var mesh = boxObjects[i]
      TweenMax.to(mesh.position, 1.2, {x: pos.x, y: pos.y, z: pos.z, delay: i*del, ease: Back.easeOut, onComplete: function() {
        completed++
        if (completed === (boxObjects.length - 1)) {
          if (onComplete) {
            onComplete()
          }
        }
      }})
    }
  }

  randomNumber(min, max) {
    return Math.random() * (max - min) + min;
  }

  animate () {
    window.requestAnimationFrame(this.animate.bind(this))

    if (this.physicsActive) {
      this.updatePhysics()
    }

    this.render()
  }

  render () {
    if (!this.physicsActive) {
      var targetRotX = 0.6 - this.mouse.y * 0.5
      var targetRotY = 0.8 + this.mouse.x * 0.5

      this.rootObj.rotation.x += (targetRotX - this.rootObj.rotation.x) / 15
      this.rootObj.rotation.y += (targetRotY - this.rootObj.rotation.y) / 15
    }

    this.renderer.render(this.scene, this.camera)
  }

  updatePhysics() {
    // Step the physics world
    world.step(timeStep);
    // Copy coordinates from Cannon.js to Three.js

    for (var i = 0; i < boxObjects.length; i++) {
      var body = bodies[i]
      boxObjects[i].position.copy(body.position)
      boxObjects[i].quaternion.copy(body.quaternion);
    }
  }
}


text:
class BaseMailer < ActionMailer::Base
  self.mailer_name = "base_mailer"

  default to: "system@test.lindsaar.net",
          from: "jose@test.plataformatec.com",
          reply_to: "mikel@test.lindsaar.net"

  def welcome(hash = {})
    headers["X-SPAM"] = "Not SPAM"
    mail({ subject: "The first email on new API!" }.merge!(hash))
  end

  def welcome_with_headers(hash = {})
    headers hash
    mail
  end

  def welcome_from_another_path(path)
    mail(template_name: "welcome", template_path: path)
  end

  def welcome_without_deliveries
    mail(template_name: "welcome")
    mail.perform_deliveries = false
  end

  def html_only(hash = {})
    mail(hash)
  end

  def plain_text_only(hash = {})
    mail(hash)
  end

  def inline_attachment
    attachments.inline["logo.png"] = "\312\213\254\232"
    mail
  end

  def attachment_with_content(hash = {})
    attachments["invoice.pdf"] = "This is test File content"
    mail(hash)
  end

  def attachment_with_hash
    attachments["invoice.jpg"] = { data: ::Base64.encode64("\312\213\254\232)b"),
                                   mime_type: "image/x-jpg",
                                   transfer_encoding: "base64" }
    mail
  end

  def attachment_with_hash_default_encoding
    attachments["invoice.jpg"] = { data: "\312\213\254\232)b",
                                   mime_type: "image/x-jpg" }
    mail
  end

  def implicit_multipart(hash = {})
    attachments["invoice.pdf"] = "This is test File content" if hash.delete(:attachments)
    mail(hash)
  end

  def implicit_with_locale(hash = {})
    mail(hash)
  end

  def explicit_multipart(hash = {})
    attachments["invoice.pdf"] = "This is test File content" if hash.delete(:attachments)
    mail(hash) do |format|
      format.text { render plain: "TEXT Explicit Multipart" }
      format.html { render plain: "HTML Explicit Multipart" }
    end
  end

  def explicit_multipart_templates(hash = {})
    mail(hash) do |format|
      format.html
      format.text
    end
  end

  def explicit_multipart_with_any(hash = {})
    mail(hash) do |format|
      format.any(:text, :html) { render plain: "Format with any!" }
    end
  end

  def explicit_without_specifying_format_with_any(hash = {})
    mail(hash) do |format|
      format.any
    end
  end

  def explicit_multipart_with_options(include_html = false)
    mail do |format|
      format.text(content_transfer_encoding: "base64") { render "welcome" }
      format.html { render "welcome" } if include_html
    end
  end

  def explicit_multipart_with_one_template(hash = {})
    mail(hash) do |format|
      format.html
      format.text
    end
  end

  def implicit_different_template(template_name = "")
    mail(template_name: template_name)
  end

  def explicit_different_template(template_name = "")
    mail do |format|
      format.text { render template: "#{mailer_name}/#{template_name}" }
      format.html { render template: "#{mailer_name}/#{template_name}" }
    end
  end

  def different_layout(layout_name = "")
    mail do |format|
      format.text { render layout: layout_name }
      format.html { render layout: layout_name }
    end
  end

  def email_with_translations
    mail body: render("email_with_translations", formats: [:html])
  end

  def without_mail_call
  end

  def with_nil_as_return_value
    mail(template_name: "welcome")
    nil
  end

  def with_subject_interpolations
    mail(subject: default_i18n_subject(rapper_or_impersonator: "Slim Shady"), body: "")
  end
end


text:
package org.batfish.coordinator.queues;

import java.util.UUID;
import org.batfish.coordinator.QueuedWork;

public interface WorkQueue extends Iterable<QueuedWork> {

  enum Type {
    memory
  }

  boolean delete(QueuedWork qWork);

  QueuedWork deque();

  boolean enque(QueuedWork qWork);

  long getLength();

  QueuedWork getWork(UUID workItemId);
}


text:
class CBaseVSShader;
class IMaterialVar;
class IShaderDynamicAPI;
class IShaderShadow;

//-----------------------------------------------------------------------------
// Init params/ init/ draw methods
//-----------------------------------------------------------------------------
struct Cloak_DX9_Vars_t
{
	Cloak_DX9_Vars_t() { memset( this, 0xFF, sizeof( *this ) ); }

	int m_nBaseTexture;
	int m_nRefractAmount;
	int m_nRefractTint;
	int m_nNormalMap;
	int m_nBumpFrame;
	int m_nBumpTransform;
	int m_nRefractTintTexture;
	int m_nRefractTintTextureFrame;
	int m_nFresnelReflection;
	int m_nMasked;
	int m_nCloakFactor;
	int m_nDiffuseWarpTexture;

	int m_nPhongExponent;
	int m_nPhongTint;
	int m_nPhongAlbedoTint;
	int m_nPhongExponentTexture;
	int m_nPhongBoost;
	int m_nPhongFresnelRanges;

	// Rim lighting parameters
	int m_nRimLight;
	int m_nRimLightPower;
	int m_nRimLightBoost;
	int m_nRimMask;
};

void InitParamsCloak_DX9( CBaseVSShader *pShader, IMaterialVar** params, const char *pMaterialName,
						   Cloak_DX9_Vars_t &info );
void InitCloak_DX9( CBaseVSShader *pShader, IMaterialVar** params, Cloak_DX9_Vars_t &info );
void DrawCloak_DX9( CBaseVSShader *pShader, IMaterialVar** params, IShaderDynamicAPI *pShaderAPI,
				   IShaderShadow* pShaderShadow, Cloak_DX9_Vars_t &info, VertexCompressionType_t vertexCompression );

#endif // CLOAK_DX9_HELPER_H


text:
$StorageAccount = ""
$StorageContainer = ""
$StoragePath = ""
$LicensePath = ""
$ApiKey = ""


text:
using Foundation;

namespace NSZombieApocalypse
{
	[Register ("ZBEViewController")]
	partial class ViewController
	{
		void ReleaseDesignerOutlets ()
		{
		}
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: meindertjan
 * Date: 29/10/2017
 * Time: 14:48
 */

namespace Mkroese\RecipeBook\Controller;

use Mkroese\RecipeBook\Application;

abstract class Base
{
  protected $application, $twig;

  /**
   * Base constructor.
   * @param Application $application
   * @param \Twig_Environment $twig
   */
  public function __construct(Application $application, \Twig_Environment $twig)
  {
    $this->application = $application;
    $this->twig = $twig;
  }

  /**
   * @param string $template
   * @param array $additionalContext
   * @return string
   */
  protected function render(string $template, array $additionalContext)
  {
    return $this->twig->render($template, array_merge($this->getRenderContext(),$additionalContext));
  }

  /**
   * @return array
   */
  protected function getRenderContext()
  {
    return [
      "application" => $this->application,
      "alerts" => $this->alerts,
    ];
  }

  protected $alerts = [];

  /**
   * @param string $message
   * @param string $type one of <code>['danger','info','success','warning']</code>
   */
  protected function addAlert(string $message, $type = "info")
  {
    $this->alerts[] = ["message" => $message,"type" => $type];
  }
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { NgZorroAntdModule } from 'ng-zorro-antd';
import { NgxKerviModule, NGXKerviPipesModule  } from 'ngx-kervi'
import { DashboardPanelComponent } from './dashboard-panel/dashboard-panel.component';
import { WidgetComponent } from './widget/widget.component';
import {  ValuesModule } from './values/values.module';

import { ControllerPadComponent } from './controller-pad/controller-pad.component';
import { CamViewerComponent } from './cam-viewer/cam-viewer.component';
import { ActionComponent } from './action/action.component';
import { UIComponentsModule} from './ui-components/ui-components.module';
import { UserLogComponent} from './log/user-log/user-log.component';
import { AppHealthComponent} from './app-health/app-health.component';
import { UserMessagesComponent } from './log/messages/messages.component';
import { UserMessageButtonComponent } from './log/message-button/message-button.component';
import { FlexLayoutModule } from '@angular/flex-layout';
@NgModule({
  imports: [
    BrowserModule,
    NGXKerviPipesModule,
    NgxKerviModule,
    ValuesModule,
    NgZorroAntdModule,
    FlexLayoutModule,
    UIComponentsModule

  ],
  declarations: [
    DashboardPanelComponent,
    WidgetComponent,
    ControllerPadComponent,
    CamViewerComponent,
    ActionComponent,
    UserLogComponent,
    UserMessageButtonComponent,
    UserMessagesComponent,
    AppHealthComponent
  ],
  exports: [
    DashboardPanelComponent,
    ControllerPadComponent,
    CamViewerComponent,
    UserLogComponent,
    UserMessageButtonComponent,
    UserMessagesComponent,
    AppHealthComponent
  ]
})
export class KerviZorroModule { }


text:
package strategy;

import interfaces.IResourceRoute;
import interfaces.IResourceStrategy;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import request.HTTPRequest;
import configuration.ServerConfiguration;

/**
 * Determines the appropriate IResourceStrategy concrete implementation for an
 * incoming HTTPRequest. The finder parses any necessary information about the
 * HTTPRequest and the server's current configuration.
 *
 * @author Chandan R. Rupakheti (rupakhcr@clarkson.edu)
 */
public class ResourceStrategyFinder {
	private ServerConfiguration serverConfiguration;

	private static Map<String, IResourceStrategy> CACHED_STRATEGIES = new HashMap<String, IResourceStrategy>();

	public ResourceStrategyFinder(ServerConfiguration server) {
		serverConfiguration = server;
	}

	public IResourceRoute findRouteForRequest(HTTPRequest request) {
		return serverConfiguration.getManagedResourceConfiguration()
				.findRouteForResourcePath(request.getPath(), request.getMethod());
	}

	public IResourceStrategy getStrategyForResourceRoute(
			IResourceRoute resourceRoute) {

		Class<?> strategyClass = resourceRoute.getStrategyClass();

		if (CACHED_STRATEGIES.containsKey(strategyClass.getName())) {
			return CACHED_STRATEGIES.get(strategyClass.getName());
		}

		try {
			Constructor<?> strategyCtor = strategyClass.getConstructor();
			IResourceStrategy strategy = (IResourceStrategy) strategyCtor
					.newInstance();
			CACHED_STRATEGIES.put(strategyClass.getName(), strategy);
			return strategy;

		} catch (Exception e) {
			/*
			 * Lots of potential exceptions here. Java wants to make reflection
			 * hard.
			 */
			return new InternalErrorStrategy();
		}
	}
}


text:
import Agenda = require("agenda");
// Import injectable and reflect metadata for dependency injection
import { inject, injectable } from "inversify";
import "reflect-metadata";
// Import interfaces for class implementation and dependency injection
import { ITriggeredJob } from "../interfaces/ITriggeredJob";
import { IPIWebAPIService } from "../interfaces/IPIWebAPIService";
// Import classes
import { TimedValue } from "../apiclients/piwebapi";
// Import security config
import { config } from "../configs/piwebapi_config";
// Import node modules
import * as fs from "mz/fs";
const csv = require("csv.js");

@injectable()
export class HelloSinusoid implements ITriggeredJob {

    // Get instance of PIWebAPIService with dependency injection
    @inject("IPIWebAPIService")
    private service: IPIWebAPIService;

    // Set Websocket options object, bypass untrusted certificate check and add Basic Authentication to header
    public webSocketOptions = {
        rejectUnauthorized: false,
        headers: {
            "Authorization": 'Basic ' + new Buffer(config.username + ':' + config.password).toString('base64')
        }
    };

    // Get wss url string with no initial values included
    public getChannelURL(): Promise<string> {
        return this.service.getPIPointChannelUrlByPath("\\\\PI2016\\SINUSOID", false);
    }

    // Job run function
    public async run(job: Agenda.Job, done: any): Promise<void> {
        try {
            // Define constants for csv writing
            const newLine = "\r\n";
            const dateString: string = `${new Date().getDate()}_${new Date().getMonth()}_${new Date().getFullYear()}`;
            // Store file in output directory with data in file name
            const file = `output/helloSinusoid_${dateString}.csv`;
            // Parse job.attrs.data in typescript acceptable way to JSON object
            let channelData = JSON.parse((job.attrs.data as any) as string);
            // Create array of changed values
            let values: Array<TimedValue> = channelData.Items[0].Items;

            //Append to existing csv file or create new file with headers
            if (await fs.exists(file)) {
                const encoded = csv.encode(values, ",", false) + newLine;
                await fs.appendFile(file, encoded);
            } else {
                const encoded = csv.encode(values, ",", true) + newLine;
                await fs.writeFile(file, encoded);
            }
            done();
        } catch (error) {
            console.error(error);
            done();
        }
    }
}


text:
```
https://github.com/jdammers/jumeg)
Created on Mon Jun 18 09:07:46 2018
@author: fboers f.boers@fz-juelich.de
```
##Features
1. template dirven approach to extract event structure
2. provide channel marker information for later processes
3. export epochs and averaged data in mne-fif format

###**event features**
1. read condition parameter from epocher-template ( [json](http://jsonapi.org/) format )
2. find mne-events for conditions defined in epocher-template,
3. store event-data in pandas dataframe for each condition
4. add additional marker information to data frame
	- image onset detection (IOD)
    - response matching
    - eye-tracking events
5. save event structure into HDF5 format

###**epocher features**
1. apply baseline correction calculated from a common or unique time intervall
2. response matching for arbitrary tasks based on columns in dataframe
3. support for arbitrary digital marker channels
4. combine events (stimulus, response, eye-tracking, image onset detection)
5. for each condition generate mne-events, epochs, averages, statistic from HDF

####**Example**
~~~python
from jumeg.epocher.jumeg_epocher import jumeg_epocher

#--- input fif file
fraw  = '007_FREEVIEW01_180115_1414_1_c,rfDC-raw.fif'
raw   = None

#--- set template path & file name
template_name = 'FreeView'
template_path = "./"

#--- info flag
verbose = True

#--- conditions / events to process
condition_list= ["FVImgBc","FVImgIodBc"]

#--- finding events
print "---> EPOCHER Events"
print "  -> FIF File: "+ fname
print "  -> Template: "+ template_name+"\n"

evt_param = {
              "condition_list":condition_list,
              "template_path": template_path,
              "template_name": template_name,
              "verbose"      : verbose
            }

raw,fname,epocher_hdf_fname = jumeg_epocher.apply_events(fname,raw=raw,**evt_param)

#--- Epocher
print "---> EPOCHER Epochs"
print "  -> File            : "+ fname
print "  -> Epocher Template: "+ template_name+"\n"

ep_param={
          "condition_list": condition_list,
          "template_path" : template_path,
          "template_name" : template_name,
          "verbose"       : verbose,
          "parameter":{
                       "event_extention": ".eve",
                       "save_condition":{"events":True,"epochs":True,"evoked":True}
                      }}

raw,fname,epocher_hdf_fname = jumeg_epocher.apply_epochs(fname=fname,raw=raw,**ep_param)
~~~

# Epocher Template

>The epocher-template is written in [json](http://jsonapi.org/) format. For syntax checking you can use [_jsonlint-py_]( https://gist.github.com/Constellation/264387).

#####**Template File Naming Convention**

>The template naming is like: **_experiment name_**_jumeg_epocher_template.json

####template path
```text
- set variable by user
- if not defined use environment variable <JUMEG_TEMPLATE_PATH_EPOCHER>
- else if not defined use < default template path >
```

#### template name
```text
-  the name of the experiment or scan as prefix, defined by user
```

####template_file_name
```text
* template_name 	: filename prefix like experiment name (e.g. M100, M100A)
* postfix 			: jumeg_epocher_template
* extention 		: .json
```

**Example**
```python
from jumeg.epocher.jumeg_epocher import jumeg_epocher as jep
jep.template_name = "M100"

print"---> check if  env jumeg_epocher_template_path is defined: " + jep.env_template_path
print"  -> template path          : " +jep.template_path
print"  -> template name          : " +jep.template_name
print"  -> template filename      : " +jep.template_filename
print"  -> template full filename : " +jep.template_full_filename
print"  -> template default path  : " +jep.template_path_default

```

---------------------------
#### **Template Parameter**
---------------------------
>*jumeg epocher template* example   (json) format:  { default{ ... }, condition1{ ... }, condition2{ ... } }

**Example**
~~~json
{
"type": "jumeg epocher template",
"id"    : "1",
"attributes": {
                 "title"      : "FreeViewing",
                 "version"    : "2018-06-19-001",
                 "experiment" : "FreeView",
                },

"default":{
           "version"          :"2018-06-19-001",
           "experiment"       : "FreeView",
           "postfix"          : "test",
           "time_pre"         : -0.20,
           "time_post"        :  0.65,

           "baseline" :{"method":"mean","type_input":"iod_onset","baseline": [null,0]},

           "marker"   :{"channel":"StimImageOnset","type_input":"iod_onset","type_output":"sac_onset","prefix":"iod","type_result":"hit"},
           "response" :{"matching":true,"channel":"ETevents","type_input":"sac_onset","type_offset":"sac_offset","prefix":"sac"},

           "iod"      :{"marker"  :{"channel":"StimImageOnset","type_input":"img_onset","prefix":"img"},
                        "response":{"matching":true,"channel":"IOD","type_input":"iod_onset","type_offset":"iod_onset","prefix":"iod"}},

           "reject"   : {"mag": 5e-9},

           "ETevents":{
                       "events":{
                                  "stim_channel"   : "ET_events",
                                  "output"         : "onset",
                                  "consecutive"    : true,
                                  "min_duration"   : 0.0005,
                                  "shortest_event" : 1,
                                  "mask"           : 0
                                 },
                        "and_mask"          : 255,
                        "event_id"          : null,
                        "window"            : [0.02,5.0],
                        "counts"            : "all",
                        "system_delay_ms"   : 0.0,
                        "early_ids_to_ignore" : "all"

                       },

           "StimImageOnset":{
                       "events":{
                                  "stim_channel"   : "STI 014",
                                  "output"         : "onset",
                                  "consecutive"    : true,
                                  "min_duration"   : 0.0005,
                                  "shortest_event" : 1,
                                  "mask"           : 0
                                 },

                        "event_id"           : 84,
                        "and_mask"           : 255,
                        "system_delay_ms"    : 0.0,
                        "early_ids_to_ignore" : null
                        },

            "IOD":{
                        "events":{
                                  "stim_channel"   : "STI 013",
                                  "output"         : "onset",
                                  "consecutive"    : true,
                                  "min_duration"   : 0.0005,
                                  "shortest_event" : 1,
                                  "mask"           : 0
                                 },

                        "window"               : [0.0,0.2],
                        "counts"               : "first",
                        "system_delay_ms"      : 0.0,
                        "early_ids_to_ignore"  : null,
                        "event_id"             : 128,
                        "and_mask"             : 255
                       }
              },
}
~~~
#### Template Condition Parameter
#####**resource object part**:

```text
type,id,attributes ... for information and identification
```

#####**default condition**:

```text
every parameter defined in the < default > condition is valid in all condition.
Inside a condition parameters can be changed and the changes are only valid within these condition
```

#####**postfix**:
```text
labeling condtion in output file name
e.g.	postfix : "ImoIOD"

example:
		input  file name: 211776_FREEVIEW01_180115_1414_1_c,rfDC,meeg_bcc,tr-raw.fif
        output file name: 211776_FREEVIEW01_180115_1414_1_c,rfDC,meeg_bcc,tr,ImoIOD_evt-ave.fif
```
#####**time_pre**:
```text
epoch time onset [s] derived from mne.Epochs
```
#####**time_post**:
```text
epoch time offset [s] derived from mne.Epochs
```

#####**reject**:
```text
recjection parameter derived from mne.Epochs
e.g. "reject"   : {"mag": 5e-12},
```
#####**baseline**:
```text
baseline : <null> no baseline correction
baseline : {"method":"mean","type_input":"iod_onset","baseline": [null,0]}
	* method	: baseline value calculation method [mean,median]
	* type_input: data frame column with timesliches as window start points [iod_onset]
	* baseline	: derived from mne.Epocher e.g. [null,0] [-0.2,0]
```
#####**iod**:
```text
response matching task to include image onset detection

Task:
	A photodiode signal (TTL) were recorded in a digital channel to mark the image onset on the screen.
	These channel (e.g. STI 013) is defined within the <default>-object parameter settings
    e.g. in < jumeg epocher template file >  { "defaults":{ ..., "iod":{ ...}, ...} }
    This can be used for arbitrary marker in order to find onset or offset events

Parameter:
"iod":{ "marker":{...},"response":{ ... } },

1. marker:{"channel":"StimImageOnset","type_input":"img_onset","prefix":"img"}
	* channel	 : channel-object keyword defined within <default>-object
    	  		   e.g.: StimImageOnset, ETevents
                   { "defaults":{ ..., "ETevents":{ ...}, ...} }
	* type_input : dataframe column with timeslices to use as onset for iod-matching [img_onset]
	* prefix	 : prefix for dataframe columns  [img]

2. response:{"matching":true,"channel":"IOD","type_input":"iod_onset","type_offset":"iod_onset","prefix":"iod"}}
	* matching	 : apply IOD matching [true or false]
	* channel	 : channel-object keyword defined under <defaults> [IOD]

	* type_input : dataframe column with timeslices to use as response for iod-matching [iod_onset]
	* type_offset: dataframe column with timeslices to use in response-matching
    	 		      for identification of <to-early-events> in iod-matching [iod_onset]
	* prefix	 : prefix for dataframe columns  [iod]
```

#####**channel object definition:**
```text
keyword to label a channel-object (e.g. ImageOnsetDetection, IOD, ETevents)

defaults{ ... "ETevents":{ "events":{ ... }, ... }, ...},

	* events   : event structure derived from <mne.find_events>
   		  	     e.g. {"stim_channel":"ET_events","output":"onset","consecutive":true,"min_duration":0.0005,
               		"shortest_event":1,"mask":0},
	* and_mask : apply and mask for <stim_channel> values [null,255]
	* event_id : event code to search for with mne.find_events
	* window   : time window [s] to look for responses if <response matching> is true
	* counts   : maximum number of responses allowed to be inside the response window [all,first,1]
			  	 - number: maximum number of responses (e.g 1 if more the epoch will be labeld as wrong)
				 - first	: should be at least one to be correct, others ignored
				 - all	: accept all responses defined in <response event_id>
                   		(e.g. eye-tracking task fixation and saccards)

	* system_delay_ms     : system delay to add to timeslice columns [ms]
	* early_ids_to_ignore : list of event_id`s to exclude as to-early-events [1,2,3]
```

####**_marker_**:
```text
keyword to label a marker-object defined within <default>-object

{ "defaults":{ ... "marker":{ ... }, ...} }

"marker":{"channel":"StimImageOnset","type_input":"iod_onset","type_output":"sac_onset","prefix":"iod","type_result":"hit"},

	* channel		: channel-object keyword defined within <default>-object e.g.: StimImageOnset, ETevents
      	            { "defaults":{ ..., "ETevents":{ ...}, ...} }

	* type_input	: dataframe column with timeslices to use as marker [iod_onset]
	* type_output	: dataframe column with timeslices
    * prefix		: prefix for dataframe columns  [iod]
	* type_result	: event type to process ["hit","wrong","missed"]

```
####**_response_**:
```text
keyword to label a response-object defined within <default>-object

{ "defaults":{ ... "response":{ ... }, ...} }

"response" :{"matching":true,"channel":"ETevents","type_input":"sac_onset","type_offset":"sac_offset","prefix":"sac"},

    * matching      : apply response-matching [true or false]
    * channel		: channel-object keyword defined within <default>-object e.g.: StimImageOnset, ETevents, IOD
      	            { "defaults":{ ..., "ETevents":{ ...}, ...} }

	* type_input	: dataframe column with timeslices to use as marker [iod_onset]
	* type_output	: dataframe column with timeslices
    * prefix		: prefix for dataframe columns [sac]

```

------------------------------
### jumeg_epocher.apply_events
	 evt_param = { "condition_list":condition_list,
	                 "template_path": template_path,
	                 "template_name": template_name,
	                 "verbose"      : verbose
	               }

	  raw,fname,epocher_hdf_fname = jumeg_epocher.apply_events(fname,raw=raw,**evt_param)

### jumeg_epocher.apply_epochs
	  ep_param={
	          "condition_list": condition_list,
	          "template_path" : template_path,
	          "template_name" : template_name,
	          "verbose"       : verbose,
	          "parameter":{
	                       "event_extention": ".eve",
	                       "save_condition":{"events":True,"epochs":True,"evoked":True},
                           "weights":{"mode":"equal","method":"median","skipp_first":null}
	                      }}
	 raw,fname,epocher_hdf_fname = jumeg_epocher.apply_epochs(fname=fname,raw=raw,**ep_param)


text:
package com.github.fobo4ka.cats;

import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.RemoteViews;

import java.io.InputStream;

class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
    private final Context context;

    public ImageDownloader(Context context) {
        this.context = context;
    }

    @Override
    protected Bitmap doInBackground(String... urls) {
        String url = urls[0];
        Bitmap mIcon = null;
        try {
            InputStream in = new java.net.URL(url).openStream();
            mIcon = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("ImageDownloader", "Download failed", e);
        }
        return mIcon;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget);
        views.setImageViewBitmap(R.id.widget_image, result);

        appWidgetManager.updateAppWidget(new ComponentName(context, CatsImageWidgetProvider.class), views);
    }
}


text:
using Lidgren.Network;
using SanicballCore;
using UnityEngine;

namespace Sanicball.Logic
{
    public class MatchStarter : MonoBehaviour
    {
        public const string APP_ID = "Sanicball";

        [SerializeField]
        private MatchManager matchManagerPrefab = null;
        [SerializeField]
        private UI.Popup connectingPopupPrefab = null;
        [SerializeField]
        private UI.PopupHandler popupHandler = null;

        private UI.PopupConnecting activeConnectingPopup;

        //NetClient for when joining online matches
        private NetClient joiningClient;

        private void Update()
        {
            if (joiningClient != null)
            {
                NetIncomingMessage msg;
                while ((msg = joiningClient.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.VerboseDebugMessage:
                            Debug.Log(msg.ReadString());
                            break;

                        case NetIncomingMessageType.WarningMessage:
                            Debug.LogWarning(msg.ReadString());
                            break;

                        case NetIncomingMessageType.ErrorMessage:
                            Debug.LogError(msg.ReadString());
                            break;

                        case NetIncomingMessageType.StatusChanged:
                            NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();

                            switch (status)
                            {
                                case NetConnectionStatus.Connected:
                                    Debug.Log("Connected! Now waiting for match state");
                                    activeConnectingPopup.ShowMessage("Receiving match state...");
                                    break;

                                case NetConnectionStatus.Disconnected:
                                    activeConnectingPopup.ShowMessage(msg.ReadString());
                                    break;

                                default:
                                    string statusMsg = msg.ReadString();
                                    Debug.Log("Status change received: " + status + " - Message: " + statusMsg);
                                    break;
                            }
                            break;

                        case NetIncomingMessageType.Data:
                            byte type = msg.ReadByte();
                            if (type == MessageType.InitMessage)
                            {
                                try
                                {
                                    MatchState matchInfo = MatchState.ReadFromMessage(msg);
                                    BeginOnlineGame(matchInfo);
                                }
                                catch (System.Exception ex)
                                {
                                    activeConnectingPopup.ShowMessage("Failed to read match message - cannot join server!");
                                    Debug.LogError("Could not read match state, error: " + ex.Message);
                                }

                                /*string matchStateStr = "";
                                try
                                {
                                    matchStateStr = msg.ReadString();
                                    MatchState matchInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<MatchState>(matchStateStr);
                                    BeginOnlineGame(matchInfo);
                                }
                                catch (Newtonsoft.Json.JsonException ex)
                                {
                                    activeConnectingPopup.ShowMessage("Failed to read match state - cannot join server!");
                                    joiningClient.Disconnect("Failed to read match state");
                                    Debug.LogError("Could not read match state, error: " + ex.Message);
                                    Debug.LogError("Full message: " + matchStateStr);
                                }*/
                            }
                            break;
                    }
                }
                if (Input.GetKeyDown(KeyCode.Escape))
                {
                    popupHandler.CloseActivePopup();
                    joiningClient.Disconnect("Cancelled");
                    joiningClient = null;
                }
            }
        }

        public void BeginLocalGame()
        {
            MatchManager manager = Instantiate(matchManagerPrefab);
            manager.InitLocalMatch();
        }

        public void JoinOnlineGame(string ip = "127.0.0.1", int port = 25000)
        {
            JoinOnlineGame(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port));
        }

        public void JoinOnlineGame(System.Net.IPEndPoint endpoint)
        {
            NetPeerConfiguration conf = new NetPeerConfiguration(APP_ID);
            joiningClient = new NetClient(conf);
            joiningClient.Start();

            //Create approval message
            NetOutgoingMessage approval = joiningClient.CreateMessage();

            ClientInfo info = new ClientInfo(GameVersion.AS_FLOAT, GameVersion.IS_TESTING);
            approval.Write(Newtonsoft.Json.JsonConvert.SerializeObject(info));

            joiningClient.Connect(endpoint, approval);

            popupHandler.OpenPopup(connectingPopupPrefab);

            activeConnectingPopup = FindObjectOfType<UI.PopupConnecting>();
        }

        //Called when succesfully connected to a server
        private void BeginOnlineGame(MatchState matchState)
        {
            MatchManager manager = Instantiate(matchManagerPrefab);
            manager.InitOnlineMatch(joiningClient, matchState);
        }
    }
}


text:
namespace dragon {

template <typename T, class Context>
class Filler {
 public:
    Filler(const TensorFiller& filler): filler_(filler) {}
    virtual void Fill(Tensor* tensor) = 0;

    inline TensorFiller& filler() { return filler_; }

 protected:
    TensorFiller filler_;
};

template <typename T, class Context>
class ConstantFiller final : public Filler<T, Context> {
 public:
    ConstantFiller(const TensorFiller& filler): Filler<T, Context>(filler) {}
    void Fill(Tensor* tensor) override {
        math::Set<T, Context>(tensor->count(),
                              dragon_cast<T, float>(filler().value()),
                              tensor->mutable_data<T, Context>());
    }
};

template <typename T, class Context>
class NormalFiller final : public Filler<T, Context> {
 public:
    NormalFiller(const TensorFiller& filler): Filler<T, Context>(filler) {}
    void Fill(Tensor* tensor) override {
        math::RandomNormal<T, Context>(tensor->count(),
                                       filler().mean(),
                                        filler().std(),
                   tensor->mutable_data<T, Context>());
    }
};

template <typename T, class Context>
class TruncatedNormalFiller final : public Filler < T, Context > {
 public:
    TruncatedNormalFiller(const TensorFiller& filler): Filler<T, Context>(filler) {}
    void Fill(Tensor* tensor) override {
        //  implement it on gpu is difficult
        math::RandomTruncatedNormal<T, CPUContext>(tensor->count(),
                                                   filler().mean(),
                                                    filler().std(),
                                                    filler().low(),
                                                   filler().high(),
                            tensor->mutable_data<T, CPUContext>());
    }
};

template <typename T, class Context>
class UniformFiller final : public Filler<T, Context> {
 public:
    UniformFiller(const TensorFiller& filler) : Filler<T, Context>(filler) {}
    void Fill(Tensor* tensor) override {
        math::RandomUniform<T, Context>(tensor->count(),
                                         filler().low(),
                                        filler().high(),
                    tensor->mutable_data<T, Context>());
    }
};

template <typename T, class Context>
class XavierFiller final : public Filler<T, Context> {
 public:
    XavierFiller(const TensorFiller& filler) : Filler<T, Context>(filler) {}
    void Fill(Tensor* tensor) override {
        int fan_in = tensor->count() / tensor->dim(0);
        int fan_out = tensor->count() / tensor->dim(1);
        float n = fan_in, scale = 3.0;
        if (filler().has_scale()) scale = filler().scale();
        if (filler().variance_norm() == TensorFiller_VarianceNorm_FAN_AVG) {
            n = (fan_in + fan_out) / float(2);
        } else if (filler().variance_norm() == TensorFiller_VarianceNorm_FAN_OUT) {
            n = fan_out;
        }
        float limit = std::sqrt(scale / n);
        math::RandomUniform<T, Context>(tensor->count(),
                                                 -limit,
                                                  limit,
                    tensor->mutable_data<T, Context>());
    }
};

template <typename T, class Context>
class MSRAFiller final : public Filler <T, Context> {
 public:
    MSRAFiller(const TensorFiller& filler) : Filler<T, Context>(filler) {}
    void Fill(Tensor* tensor) override {
        int fan_in = tensor->count() / tensor->dim(0);
        int fan_out = tensor->count() / tensor->dim(1);
        float n = fan_in, scale = 2.0;
        if (filler().has_scale()) scale = filler().scale();
        if (filler().variance_norm() == TensorFiller_VarianceNorm_FAN_AVG) {
            n = (fan_in + fan_out) / float(2);
        } else if (filler().variance_norm() == TensorFiller_VarianceNorm_FAN_OUT) {
            n = fan_out;
        }
        float std = std::sqrt(scale / n);
        math::RandomNormal<T, Context>(tensor->count(),
                                              float(0),
                                                   std,
                   tensor->mutable_data<T, Context>());
    }
};

template <typename T, class Context>
Filler<T, Context>* CreateFiller(const TensorFiller& filler) {
    const string& type = filler.type();
    if (type == "constant") {
        return new ConstantFiller<T, Context>(filler);
    } else if (type == "uniform") {
        return new UniformFiller<T, Context>(filler);
    } else if (type == "normal") {
        return new NormalFiller<T, Context>(filler);
    } else if (type == "truncated_normal") {
        return new TruncatedNormalFiller<T, Context>(filler);
    } else if (type == "xavier") {
        return new XavierFiller<T, Context>(filler);
    } else if (type == "msra") {
        return new MSRAFiller<T, Context>(filler);
    }
    return new ConstantFiller<T, Context>(filler);
}

}    // namespace dragon

#endif    // DRAGON_UTILS_FILLER_H_


text:
namespace CurveLock.Panels
{
  partial class EncryptText
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
      if (disposing && (components != null))
      {
        components.Dispose();
      }
      base.Dispose(disposing);
    }

    #region Component Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.header = new System.Windows.Forms.Label();
      this.encrypt = new System.Windows.Forms.LinkLabel();
      this.label1 = new System.Windows.Forms.Label();
      this.toId = new System.Windows.Forms.TextBox();
      this.label2 = new System.Windows.Forms.Label();
      this.message = new System.Windows.Forms.TextBox();
      this.cancel = new System.Windows.Forms.LinkLabel();
      this.SuspendLayout();
      //
      // header
      //
      this.header.AutoSize = true;
      this.header.Font = new System.Drawing.Font("Segoe UI", 48F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
      this.header.Location = new System.Drawing.Point(105, 0);
      this.header.Name = "header";
      this.header.Size = new System.Drawing.Size(384, 86);
      this.header.TabIndex = 0;
      this.header.Text = "Encrypt Text";
      //
      // encrypt
      //
      this.encrypt.AutoSize = true;
      this.encrypt.LinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(94)))), ((int)(((byte)(145)))));
      this.encrypt.Location = new System.Drawing.Point(504, 435);
      this.encrypt.Name = "encrypt";
      this.encrypt.Size = new System.Drawing.Size(75, 25);
      this.encrypt.TabIndex = 2;
      this.encrypt.TabStop = true;
      this.encrypt.Text = "Encrypt";
      this.encrypt.VisitedLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(94)))), ((int)(((byte)(145)))));
      this.encrypt.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.EncryptLinkClicked);
      //
      // label1
      //
      this.label1.AutoSize = true;
      this.label1.Location = new System.Drawing.Point(3, 95);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(114, 25);
      this.label1.TabIndex = 3;
      this.label1.Text = "To Curve ID:";
      //
      // toId
      //
      this.toId.Location = new System.Drawing.Point(17, 123);
      this.toId.Name = "toId";
      this.toId.Size = new System.Drawing.Size(562, 33);
      this.toId.TabIndex = 4;
      //
      // label2
      //
      this.label2.AutoSize = true;
      this.label2.Location = new System.Drawing.Point(3, 159);
      this.label2.Name = "label2";
      this.label2.Size = new System.Drawing.Size(90, 25);
      this.label2.TabIndex = 5;
      this.label2.Text = "Message:";
      //
      // message
      //
      this.message.Location = new System.Drawing.Point(17, 187);
      this.message.Multiline = true;
      this.message.Name = "message";
      this.message.Size = new System.Drawing.Size(562, 245);
      this.message.TabIndex = 6;
      //
      // cancel
      //
      this.cancel.AutoSize = true;
      this.cancel.LinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(94)))), ((int)(((byte)(145)))));
      this.cancel.Location = new System.Drawing.Point(429, 435);
      this.cancel.Name = "cancel";
      this.cancel.Size = new System.Drawing.Size(69, 25);
      this.cancel.TabIndex = 7;
      this.cancel.TabStop = true;
      this.cancel.Text = "Cancel";
      this.cancel.VisitedLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(94)))), ((int)(((byte)(145)))));
      this.cancel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.CancelLinkClicked);
      //
      // EncryptText
      //
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
      this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(7)))), ((int)(((byte)(16)))), ((int)(((byte)(58)))));
      this.Controls.Add(this.cancel);
      this.Controls.Add(this.message);
      this.Controls.Add(this.label2);
      this.Controls.Add(this.toId);
      this.Controls.Add(this.label1);
      this.Controls.Add(this.encrypt);
      this.Controls.Add(this.header);
      this.Font = new System.Drawing.Font("Segoe UI", 14.25F);
      this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(123)))), ((int)(((byte)(132)))), ((int)(((byte)(174)))));
      this.Name = "EncryptText";
      this.Size = new System.Drawing.Size(594, 472);
      this.ResumeLayout(false);
      this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.Label header;
    private System.Windows.Forms.LinkLabel encrypt;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox toId;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.TextBox message;
    private System.Windows.Forms.LinkLabel cancel;
  }
}


text:
package org.clulab

import java.io.{File, FileWriter}
import scala.language.reflectiveCalls

package object brat {
  type Closeable = { def close(): Unit }

  def using[A <: Closeable, B](param: A)(f: A => B): B =
    try { f(param) } finally { param.close() }

  def readFile(filename: String): String =
    using (io.Source.fromFile(filename)) {
      source => source.mkString
    }

  def readFile(file: File): String =
    using (io.Source.fromFile(file)) {
      source => source.mkString
    }

  def writeFile(file: File, text: String) {
    using (new FileWriter(file)) {
      writer => writer.write(text)
    }
  }

  def writeFile(filename: String, text: String) {
    writeFile(new File(filename), text)
  }
}


text:
const _ = require('lodash');

const fs = require('fs');

const _path = require('path');

/**
 * @memberOf FileUtil
 * @function rmdirSync
 *
 * Synchronous {@link http://man7.org/linux/man-pages/man2/rmdir.2.html|rmdir(2)}.
 *
 * @param {Object} options
 * @param {String|Buffer} options.path
 *
 * @returns {undefined}
 * @see {@link https://nodejs.org/api/fs.html#fs_fs_rmdirsync_path}
 */
var rmdirSync = function (options) {
    var path = _.get(options, 'path');

    if (_.isString(path) || _.isBuffer(path)) {
        path = _path.resolve(process.cwd(), path);
    }

    return fs.rmdirSync(path);
};

module.exports = rmdirSync;


text:
package org.xllapp.portal.weixin.dao;

import com.ffcs.icity.mvc.dao.CRUDDao;
import com.ffcs.icity.mybatis.MyBatisRepository;

import org.xllapp.portal.weixin.entity.WxMessageArticle;

@MyBatisRepository
public interface WxMessageArticleDao extends CRUDDao<WxMessageArticle> {

}


text:
    {{name}}
    [{{{more_info}}}]

{{{reset_zoom}}}

{{=icon cog-duotone=}}

<canvas/>


text:
<template name="beverages">

Beverage Menu

                    Available?
                    Beverage(s)
                    Description
                    Size
                    Price
                    {{#if userCanEdit}}

                            <button href="#" class="btn btn-default navbar-btn hidden-xs fullscreen">

                            </button>
                            <button href="#" class="btn btn-default navbar-btn hidden-xs print">

                            </button>

                    {{/if}}

                {{#each beverages}}

                        {{#if isAvailable}}

                        {{else}}

                        {{/if}}

                     {{name}}
                     {{description}}
                     {{size}}
                     {{price}}
                    {{#if userCanEdit}}

                                <button href="/editBeverage/{{_id}}" class="btn btn-default navbar-btn edit">Edit</button>

                    {{/if}}

                {{/each}}

</template>


text:
import AbstractVersionsListView from 'OpenOrchestra/Application/View/Versionable/AbstractVersionsListView'

/**
 * @class NodeVersionsListView
 */
class NodeVersionsListView extends AbstractVersionsListView
{
    /**
     * @inheritDoc
     */
    initialize({collection, settings, nodeId, language}) {
        super.initialize({collection: collection, settings: settings});
        this._nodeId = nodeId;
        this._language = language;
    }

    /**
     * @inheritDoc
     */
    getTableId() {
        return 'node_versions_list';
    }

    /**
     * @param {Object} td
     * @param {Object} cellData
     * @param {Object} rowData
     *
     * @private
     */
    _createEditLink(td, cellData, rowData) {
        let link = Backbone.history.generateUrl('showNode', {
            language: rowData.get('language'),
            nodeId: rowData.get('node_id'),
            version: rowData.get('version')
        });

        cellData = $('<a>',{
            text: cellData,
            href: '#'+link
        });

        $(td).html(cellData)
    }

    /**
     * @inheritDoc
     */
    generateUrlUpdatePage(page) {
        return Backbone.history.generateUrl('manageVersionsNode', {
            nodeId: this._nodeId,
            language: this._language,
            page : page
        });
    }
}

export default NodeVersionsListView;