text:
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using TWCore.Collections;
using TWCore.Diagnostics.Status;
using TWCore.Net.RPC.Descriptors;
using TWCore.Serialization;
using TWCore.Threading;
// ReSharper disable MethodSupportsCancellation

// ReSharper disable UnassignedGetOnlyAutoProperty
// ReSharper disable MemberCanBePrivate.Global

namespace TWCore.Net.RPC.Client.Transports.Default
{
    /// <inheritdoc />
    /// <summary>
    /// Default RPC Transport client
    /// </summary>
    [StatusName("Transport")]
    public class DefaultTransportClient : ITransportClient
    {
        private const int ResetIndex = 500000;
        private readonly ConcurrentDictionary<Guid, RpcMessageHandler> _messageResponsesHandlers = new ConcurrentDictionary<Guid, RpcMessageHandler>();
        private readonly LRU2QCollection<Guid, object> _previousMessages = new LRU2QCollection<Guid, object>(100);
        private readonly ReferencePool<RpcMessageHandler> _messageHandlerPool = new ReferencePool<RpcMessageHandler>(0, item =>
        {
            item.Message = null;
            item.Event.Reset();
        });
        private readonly AsyncLock _connectionLocker = new AsyncLock();
        private CancellationTokenSource _connectionCancellationTokenSource;
        private CancellationToken _connectionCancellationToken;
        private bool _shouldBeConnected;
        private readonly int _socketsPerClient = 4;
        private int _currentIndex = -1;
        private RpcClient[] _clients;

        #region Nested Types
        private sealed class RpcMessageHandler
        {
            public readonly AsyncManualResetEvent Event = new AsyncManualResetEvent();
            public RPCResponseMessage Message;
        }
        #endregion

        #region Properties
        /// <inheritdoc />
        /// <summary>
        /// Transport name, should be the same name for Server and Client
        /// </summary>
        [StatusProperty]
        public string Name => "DefaultTransport";
        /// <inheritdoc />
        /// <summary>
        /// Serializer to encode and decode the incoming and outgoing data
        /// </summary>
        [StatusProperty]
        public ISerializer Serializer { get; set; }
        /// <inheritdoc />
        /// <summary>
        /// Services descriptors to use on RPC Request messages
        /// </summary>
        public ServiceDescriptorCollection Descriptors { get; set; }
        /// <summary>
        /// RPC Transport Server host
        /// </summary>
        [StatusProperty]
        public string Host { get; }
        /// <summary>
        /// RPC Transport Server port
        /// </summary>
        [StatusProperty]
        public int Port { get; }
        /// <summary>
        /// Invoke Method Timeout
        /// </summary>
        [StatusProperty]
        public int InvokeMethodTimeout { get; set; } = 45000;
        #endregion

        #region Events
        /// <summary>
        /// Events received from the RPC transport server
        /// </summary>
        public event EventHandler<EventDataEventArgs> OnEventReceived;
        /// <summary>
        /// Event when a push message has been received from server
        /// </summary>
        public event EventHandler<EventArgs<RPCPushMessage>> OnPushMessageReceived;
        #endregion

        #region .ctor
        /// <summary>
        /// Default RPC Transport client
        /// </summary>
        public DefaultTransportClient()
        {
            Serializer = SerializerManager.DefaultBinarySerializer.DeepClone();
            if (Serializer != null)
            {
                Serializer.KnownTypes.Add(typeof(RPCError));
                Serializer.KnownTypes.Add(typeof(RPCEventMessage));
                Serializer.KnownTypes.Add(typeof(RPCPushMessage));
                Serializer.KnownTypes.Add(typeof(RPCRequestMessage));
                Serializer.KnownTypes.Add(typeof(RPCResponseMessage));
                Serializer.KnownTypes.Add(typeof(RPCSessionRequestMessage));
                Serializer.KnownTypes.Add(typeof(RPCSessionResponseMessage));
            }
            Core.Status.Attach(collection =>
            {
                collection.Add("Messages Waiting Response Count", _messageResponsesHandlers.Count, true);
                collection.Add("Connections count", _clients?.Length, true);
            });
        }
        /// <summary>
        /// Default RPC Transport client
        /// </summary>
        /// <param name="host">RPC Transport Server Host</param>
        /// <param name="port">RPC Transport Server Port</param>
        /// <param name="socketsPerClient">Sockets per transport client</param>
        /// <param name="serializer">Serializer for data transfer, is is null then is XmlTextSerializer</param>
        public DefaultTransportClient(string host, int port, byte socketsPerClient, ISerializer serializer = null)
        {
            Host = host;
            Port = port;
            Serializer = serializer ?? SerializerManager.DefaultBinarySerializer.DeepClone();
            if (socketsPerClient > 0)
                _socketsPerClient = socketsPerClient;
            if (Serializer != null)
            {
                Serializer.KnownTypes.Add(typeof(RPCError));
                Serializer.KnownTypes.Add(typeof(RPCCancelMessage));
                Serializer.KnownTypes.Add(typeof(RPCEventMessage));
                Serializer.KnownTypes.Add(typeof(RPCPushMessage));
                Serializer.KnownTypes.Add(typeof(RPCRequestMessage));
                Serializer.KnownTypes.Add(typeof(RPCResponseMessage));
                Serializer.KnownTypes.Add(typeof(RPCSessionRequestMessage));
                Serializer.KnownTypes.Add(typeof(RPCSessionResponseMessage));
            }
            Core.Status.Attach(collection =>
            {
                collection.Add("Messages Waiting Response Count", _messageResponsesHandlers.Count, true);
                collection.Add("Connections count", _clients?.Length, true);
            });
        }
        #endregion

        #region Connection
        /// <summary>
        /// Connect to the transport server
        /// </summary>
        /// <returns>Task as result of the connection process</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task ConnectAsync()
        {
            if (_shouldBeConnected) return;
            using (await _connectionLocker.LockAsync().ConfigureAwait(false))
            {
                _shouldBeConnected = true;
                try
                {
                    _connectionCancellationTokenSource = new CancellationTokenSource();
                    _connectionCancellationToken = _connectionCancellationTokenSource.Token;
                    if (_clients is null)
                    {
                        _clients = new RpcClient[_socketsPerClient];
                        for (var i = 0; i < _clients.Length; i++)
                        {
                            var client = new RpcClient(Host, Port, (BinarySerializer)Serializer);
                            client.OnMessageReceived += ClientOnOnMessageReceived;
                            _clients[i] = client;
                        }
                    }
                    await _clients.Select(c => c.ConnectAsync()).ConfigureAwait(false);
                }
                catch (Exception)
                {
                    _shouldBeConnected = false;
                    throw;
                }
            }
        }
        /// <summary>
        /// Disconnect from the transport server
        /// </summary>
        /// <returns>Task as result of the disconnection process</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task DisconnectAsync()
        {
            if (!_shouldBeConnected) return;
            using (await _connectionLocker.LockAsync().ConfigureAwait(false))
            {
                _shouldBeConnected = false;
                _connectionCancellationTokenSource.Cancel();
                await _clients.Select(c => c.DisconnectAsync()).ConfigureAwait(false);
            }
        }
        #endregion

        #region Interface Methods

        /// <inheritdoc />
        /// <summary>
        /// Initialize the Transport client
        /// </summary>
        /// <returns>Task of the method execution</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task InitAsync()
        {
            try
            {
                await ConnectAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Core.Log.Error(ex.Message);
            }
        }
        /// <inheritdoc />
        /// <summary>
        /// Gets the descriptors for the RPC service
        /// </summary>
        /// <returns>Task of the method execution</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<ServiceDescriptorCollection> GetDescriptorsAsync()
        {
            var request = RPCRequestMessage.Retrieve(Guid.Empty, null, false);
            var response = await InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            return (ServiceDescriptorCollection)response.ReturnValue;
        }
        /// <inheritdoc />
        /// <summary>
        /// Invokes a RPC method on the RPC server and gets the results
        /// </summary>
        /// <param name="messageRq">RPC request message to send to the server</param>
        /// <returns>RPC response message from the server</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<RPCResponseMessage> InvokeMethodAsync(RPCRequestMessage messageRq)
        {
            if (!_shouldBeConnected)
                await ConnectAsync().ConfigureAwait(false);
            if (_connectionCancellationToken.IsCancellationRequested) return null;
            var handler = _messageHandlerPool.New();
            while (!_messageResponsesHandlers.TryAdd(messageRq.MessageId, handler))
                await Task.Yield();
            if (_currentIndex > ResetIndex) _currentIndex = -1;
            bool sent;
            do
            {
                var client = _clients[Interlocked.Increment(ref _currentIndex) % _socketsPerClient];
                sent = await client.SendRpcMessageAsync(messageRq).ConfigureAwait(false);
            } while (!sent);
            await handler.Event.WaitAsync(InvokeMethodTimeout, _connectionCancellationToken).ConfigureAwait(false);
            if (handler.Event.IsSet)
            {
                var msg = handler.Message;
                _messageHandlerPool.Store(handler);
                return msg;
            }
            _messageHandlerPool.Store(handler);
            _connectionCancellationToken.ThrowIfCancellationRequested();
            throw new TimeoutException($"Timeout of {InvokeMethodTimeout / 1000} seconds has been reached waiting the response from the server with Id={messageRq.MessageId}.");
        }
        /// <inheritdoc />
        /// <summary>
        /// Invokes a RPC method on the RPC server and gets the results
        /// </summary>
        /// <param name="messageRq">RPC request message to send to the server</param>
        /// <param name="cancellationToken">Cancellation Token instance</param>
        /// <returns>RPC response message from the server</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<RPCResponseMessage> InvokeMethodAsync(RPCRequestMessage messageRq, CancellationToken cancellationToken)
        {
            if (!_shouldBeConnected)
                await ConnectAsync().ConfigureAwait(false);
            if (_connectionCancellationToken.IsCancellationRequested) return null;
            var handler = _messageHandlerPool.New();
            while (!_messageResponsesHandlers.TryAdd(messageRq.MessageId, handler))
                await Task.Yield();
            if (_currentIndex > ResetIndex) _currentIndex = -1;
            bool sent;
            RpcClient client;
            using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_connectionCancellationToken, cancellationToken))
            {
                do
                {
                    client = _clients[Interlocked.Increment(ref _currentIndex) % _socketsPerClient];
                    sent = await client.SendRpcMessageAsync(messageRq).ConfigureAwait(false);
                } while (!sent);
                await handler.Event.WaitAsync(InvokeMethodTimeout, linkedTokenSource.Token).ConfigureAwait(false);
            }
            if (handler.Event.IsSet)
            {
                var msg = handler.Message;
                _messageHandlerPool.Store(handler);
                return msg;
            }
            _messageHandlerPool.Store(handler);
            _connectionCancellationToken.ThrowIfCancellationRequested();
            if (cancellationToken.IsCancellationRequested)
            {
                await client.SendRpcMessageAsync(new RPCCancelMessage { MessageId = messageRq.MessageId }).ConfigureAwait(false);
                cancellationToken.ThrowIfCancellationRequested();
            }
            throw new TimeoutException($"Timeout of {InvokeMethodTimeout / 1000} seconds has been reached waiting the response from the server with Id={messageRq.MessageId}.");
        }
        #endregion

        /// <inheritdoc />
        /// <summary>
        /// Dispose all resources
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Dispose()
        {
            DisconnectAsync().WaitAsync();
        }

        #region Private Methods
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void ClientOnOnMessageReceived(RpcClient rpcClient1, RPCMessage rpcMessage)
        {
            switch (rpcMessage)
            {
                case RPCResponseMessage responseMessage:
                    if (!_messageResponsesHandlers.TryRemove(responseMessage.RequestMessageId, out var value))
                        return;
                    value.Message = responseMessage;
                    value.Event.Set();
                    break;
                case RPCEventMessage eventMessage:
                    if (!_previousMessages.TryGetValue(eventMessage.MessageId, out _))
                    {
                        _previousMessages.TryAdd(eventMessage.MessageId, null);
                        var edea = EventDataEventArgs.Retrieve(eventMessage.ServiceName, eventMessage.EventName, eventMessage.EventArgs);
                        OnEventReceived?.Invoke(this, edea);
                        EventDataEventArgs.Store(edea);
                    }
                    break;
                case RPCPushMessage pushMessage:
                    if (!_previousMessages.TryGetValue(pushMessage.MessageId, out _))
                    {
                        _previousMessages.TryAdd(pushMessage.MessageId, null);
                        var evArgs = ReferencePool<EventArgs<RPCPushMessage>>.Shared.New();
                        evArgs.Item1 = pushMessage;
                        OnPushMessageReceived?.Invoke(this, evArgs);
                        evArgs.Item1 = null;
                        ReferencePool<EventArgs<RPCPushMessage>>.Shared.Store(evArgs);
                    }
                    break;
                case RPCError errorMessage:
                    var respMsg = RPCResponseMessage.Retrieve(errorMessage);
                    foreach (var mHandler in _messageResponsesHandlers.ToArray())
                    {
                        mHandler.Value.Message = respMsg;
                        mHandler.Value.Event.Set();
                        _messageResponsesHandlers.TryRemove(mHandler.Key, out _);
                    }
                    break;
            }
        }
        #endregion
    }
}


text:
@interface PodsDummy_Pods_WatchTest : NSObject
@end
@implementation PodsDummy_Pods_WatchTest
@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PhpCodeQuality\AutoloadValidation\Exception;

/**
 * This exception is thrown when a parent class could not be loaded.
 */
class ParentClassNotFoundException extends \RuntimeException
{
    /**
     * The parent class.
     *
     * @var string
     */
    private $parentClass;

    /**
     * Construct the exception.
     *
     * @param string     $class    The name of the parent class that could not be loaded.
     *
     * @param int        $code     The Exception code.
     *
     * @param \Exception $previous The previous exception used for the exception chaining.
     */
    public function __construct($class, $code = 0, \Exception $previous = null)
    {
        $this->parentClass = $class;

        parent::__construct('Parent class ' . $class . ' could not be loaded', $code, $previous);
    }

    /**
     * Retrieve the parent class name.
     *
     * @return string
     */
    public function getParentClass()
    {
        return $this->parentClass;
    }
}


text:
class Clazz:
    def __init__(self) -> None:
        pass


text:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace Nest
{
	public interface IGetRoleResponse : IResponse
	{
		IDictionary<string, Role> Roles { get; }
	}

	[JsonObject(MemberSerialization.OptIn)]
	[JsonConverter(typeof(DictionaryResponseJsonConverter<GetRoleResponse, string, Role>))]
	public class GetRoleResponse : DictionaryResponseBase<string, Role>, IGetRoleResponse
	{
		[JsonIgnore]
		public IDictionary<string, Role> Roles => Self.BackingDictionary;
	}
}


text:
HighDefinitionFaceFrameReference Members
========================================

**HighDefinitionFaceFrameReference** has the following members.

Properties
==========

<colgroup>
<col width="30%" />
<col width="60%" />
</colgroup>

Name
Description

RelativeTime
Gets the relative time of this frame.

Methods
=======

<colgroup>
<col width="30%" />
<col width="60%" />
</colgroup>

Name
Description

AcquireFrame
Gets a container for one frame of high-definition face frame data.

See also
========

#### Reference

[HighDefinitionFaceFrameReference Class](../HighDefinitionFaceFrameR.md)
 [Microsoft.Kinect.Face Namespace](../../Kinect.Face.md)


text:
import Test.Hspec        (Spec, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)

import HelloWorld        (hello)

main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs

specs :: Spec
specs = it "hello" $ hello `shouldBe` "Hello, World!"


text:
<?php

namespace Magento\Sales\Api\Data;

use Magento\Framework\Api\ExtensibleDataInterface;

/**
 * Shipment Track Creation interface.
 *
 * @api
 */
interface ShipmentTrackCreationInterface extends TrackInterface, ExtensibleDataInterface
{
    /**
     * Retrieve existing extension attributes object or create a new one.
     *
     * @return \Magento\Sales\Api\Data\ShipmentTrackCreationExtensionInterface|null
     */
    public function getExtensionAttributes();

    /**
     * Set an extension attributes object.
     *
     * @param \Magento\Sales\Api\Data\ShipmentTrackCreationExtensionInterface $extensionAttributes
     * @return $this
     */
    public function setExtensionAttributes(
        \Magento\Sales\Api\Data\ShipmentTrackCreationExtensionInterface $extensionAttributes
    );
}


text:
package tw.soleil.pwrs;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import tw.soleil.pwrs.object.DataStream;
import tw.soleil.pwrs.object.Feed;

public class GraphsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.activity_graphs);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {

                new AlertDialog.Builder(GraphsActivity.this)
                        .setTitle("Power switch")
                        .setMessage("Do you want to turn on or off?")
                        .setIcon(R.drawable.ic_action_image_flash_on)
                        .setPositiveButton("Turn on", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                JsonParser parser = new JsonParser();

                                String jsonText = toJSONPowerSwitch(true);

                                Log.i(XivelySettings.TAG, "JSON Text: " + jsonText);

                                final ProgressDialog loadingDialog = new ProgressDialog(GraphsActivity.this);
                                loadingDialog.setMessage("Updating");
                                loadingDialog.show();

                                Ion.with(GraphsActivity.this)
                                        .load("PUT", "https://api.xively.com/v2/feeds/"+ XivelySettings.FEED_ID)
                                        .setHeader("X-ApiKey", XivelySettings.API_KEY)
                                        .setJsonObjectBody(parser.parse(jsonText).getAsJsonObject())
                                        .asString()
                                        .setCallback(new FutureCallback<String>() {
                                            @Override
                                            public void onCompleted(Exception e, String result) {

                                                loadingDialog.dismiss();
                                                if (e == null) {

                                                    Log.i(XivelySettings.TAG, "Result: " + result);

                                                    Snackbar.make(view, "Power has been turned on.", Snackbar.LENGTH_LONG)
                                                            .setAction("Action", null).show();
                                                    loadGraphics();
                                                } else {
                                                    Log.e(XivelySettings.TAG, "Put error: " + e.getLocalizedMessage());
                                                }
                                            }
                                        });
                            }
                        })
                        .setNegativeButton("Turn off", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                JsonParser parser = new JsonParser();

                                String jsonText = toJSONPowerSwitch(false);

                                Log.i(XivelySettings.TAG, "JSON Text: " + jsonText);

                                final ProgressDialog loadingDialog = new ProgressDialog(GraphsActivity.this);
                                loadingDialog.setMessage("Updating");
                                loadingDialog.show();

                                Ion.with(GraphsActivity.this)
                                        .load("PUT", "https://api.xively.com/v2/feeds/"+ XivelySettings.FEED_ID)
                                        .setHeader("X-ApiKey", XivelySettings.API_KEY)
                                        .setJsonObjectBody(parser.parse(jsonText).getAsJsonObject())
                                        .asString()
                                        .setCallback(new FutureCallback<String>() {
                                            @Override
                                            public void onCompleted(Exception e, String result) {
                                                loadingDialog.dismiss();
                                                if (e == null) {

                                                    Log.i(XivelySettings.TAG, "Result: " + result);

                                                    Snackbar.make(view, "Power has been turned off.", Snackbar.LENGTH_LONG)
                                                            .setAction("Action", null).show();
                                                    loadGraphics();
                                                } else {
                                                    Log.e(XivelySettings.TAG, "Put error: " + e.getLocalizedMessage());
                                                }
                                            }
                                        });
                            }
                        })
                        .setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .show();

            }
        });

    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        loadGraphics();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_graphs, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        if (id == R.id.action_refresh) {
            this.loadGraphics();
        }

        return super.onOptionsItemSelected(item);
    }

    public void loadGraphics() {

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        final TextView kwTextView = (TextView)findViewById(R.id.kw_text_view);
        final TextView kwhTextView = (TextView)findViewById(R.id.kwh_text_view);
        final TextView paTextView = (TextView)findViewById(R.id.pa_text_view);
        final TextView pvTextView = (TextView)findViewById(R.id.pv_text_view);

        final ProgressDialog loadingDialog = new ProgressDialog(GraphsActivity.this);
        loadingDialog.setMessage("Loading");
        loadingDialog.show();

        // Load all data from feeds
        Ion.with(GraphsActivity.this)
                .load("GET", "https://api.xively.com/v2/feeds/" + XivelySettings.FEED_ID +".json")
                .setHeader("X-ApiKey", XivelySettings.API_KEY)
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        if (result != null) {

                            loadingDialog.dismiss();

                            Gson gson = new Gson();

                            // Put Json Object into Feed Object
                            Feed feed = gson.fromJson(result, Feed.class);

                            Log.d("XivelyTestDrive", "Feed result: " + feed.toString());

                            if (feed.getDatastreams() != null) {
                                for (DataStream eachData : feed.getDatastreams()) {
                                    if (eachData.getId().equalsIgnoreCase("KW")) {
                                        String symbol = eachData.getUnit().get("symbol");
                                        kwTextView.setText("Current value: " + eachData.getCurrent_value() + " " +symbol);
                                    }
                                    if (eachData.getId().equalsIgnoreCase("KWH")) {
                                        String symbol = eachData.getUnit().get("symbol");
                                        kwhTextView.setText("Current value: " + eachData.getCurrent_value() + " " +symbol);
                                    }
                                    if (eachData.getId().equalsIgnoreCase("PA")) {
                                        String symbol = eachData.getUnit().get("symbol");
                                        paTextView.setText("Current value: " + eachData.getCurrent_value() + " " +symbol);
                                    }
                                    if (eachData.getId().equalsIgnoreCase("PV")) {
                                        String symbol = eachData.getUnit().get("symbol");
                                        pvTextView.setText("Current value: " + eachData.getCurrent_value() + " " +symbol);
                                    }

                                    // Check whether plug is on or not
                                    if (eachData.getId().equalsIgnoreCase("PSW")) {
                                        if (eachData.getCurrent_value().equalsIgnoreCase("ON")) {
                                            fab.setImageResource(R.drawable.ic_action_on);
                                        } else if (eachData.getCurrent_value().equalsIgnoreCase("OFF")) {
                                            fab.setImageResource(R.drawable.ic_action_off);
                                        }
                                    }

                                }
                            }

//                            Toast.makeText(GraphsActivity.this, "Updated", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

        // Load KW image view
        final ImageView kwImageView = (ImageView)findViewById(R.id.kw_image_view);
        Ion.with(GraphsActivity.this)
                .load("https://api.xively.com/v2/feeds/"+ XivelySettings.FEED_ID +"/datastreams/KW.png?b=true&g=true&t=KW&timezone=Taipei")
                .setHeader("X-ApiKey", XivelySettings.API_KEY)
                .noCache()
                .asBitmap()
                .setCallback(new FutureCallback<Bitmap>() {
                    @Override
                    public void onCompleted(Exception e, Bitmap result) {
                        if (result != null) {
                            kwImageView.setImageBitmap(result);
                        }

                        if (e != null) {
                            Log.e(XivelySettings.TAG, "Error image: " + e.getLocalizedMessage());
                        }
                    }
                });

        // Load KWH image view
        final ImageView kwhImageView = (ImageView)findViewById(R.id.kwh_image_view);
        Ion.with(GraphsActivity.this)
                .load("https://api.xively.com/v2/feeds/"+ XivelySettings.FEED_ID +"/datastreams/KWH.png?b=true&g=true&t=KWH&timezone=Taipei")
                .setHeader("X-ApiKey", XivelySettings.API_KEY)
                .noCache()
                .asBitmap()
                .setCallback(new FutureCallback<Bitmap>() {
                    @Override
                    public void onCompleted(Exception e, Bitmap result) {
                        if (result != null) {
                            kwhImageView.setImageBitmap(result);
                        }

                        if (e != null) {
                            Log.e(XivelySettings.TAG, "Error image: " + e.getLocalizedMessage());
                        }
                    }
                });

        // Load PA image view
        final ImageView paImageView = (ImageView)findViewById(R.id.pa_image_view);
        Ion.with(GraphsActivity.this)
                .load("https://api.xively.com/v2/feeds/"+ XivelySettings.FEED_ID +"/datastreams/PA.png?b=true&g=true&t=PA&timezone=Taipei")
                .setHeader("X-ApiKey", XivelySettings.API_KEY)
                .noCache()
                .asBitmap()
                .setCallback(new FutureCallback<Bitmap>() {
                    @Override
                    public void onCompleted(Exception e, Bitmap result) {
                        if (result != null) {
                            paImageView.setImageBitmap(result);
                        }

                        if (e != null) {
                            Log.e(XivelySettings.TAG, "Error image: " + e.getLocalizedMessage());
                        }
                    }
                });

        // Load PV image view
        final ImageView pvImageView = (ImageView)findViewById(R.id.pv_image_view);
        Ion.with(GraphsActivity.this)
                .load("https://api.xively.com/v2/feeds/"+ XivelySettings.FEED_ID +"/datastreams/PV.png?b=true&g=true&t=PV&timezone=Taipei")
                .setHeader("X-ApiKey", XivelySettings.API_KEY)
                .noCache()
                .asBitmap()
                .setCallback(new FutureCallback<Bitmap>() {
                    @Override
                    public void onCompleted(Exception e, Bitmap result) {
                        if (result != null) {
                            pvImageView.setImageBitmap(result);
                        }

                        if (e != null) {
                            Log.e(XivelySettings.TAG, "Error image: " + e.getLocalizedMessage());
                        }
                    }
                });
    }

    private String toJSONPowerSwitch(boolean turnOn) {

        String turnOnOff = new String();
        if (turnOn) {
            turnOnOff = "ON";
        } else {
            turnOnOff = "OFF";
        }

        Gson gson = new Gson();

        Feed feed = new Feed();
        feed.setVersion("1.0.0");

        DataStream dataStream = new DataStream();
        dataStream.setId("PSW");

        HashMap<String, String> value = new HashMap<String, String>();
        value.put("value", turnOnOff);

        // yyyy-MM-dd'T'HH:mm:ss'Z'
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        value.put("at", simpleDateFormat.format(new Date()));

        List<HashMap<String, String>> datapoints = new ArrayList<>();
        datapoints.add(value);

        dataStream.setDatapoints(datapoints);
        dataStream.setCurrent_value(turnOnOff);

        List<DataStream> dataStreams = new ArrayList<DataStream>();
        dataStreams.add(dataStream);

        feed.setDatastreams(dataStreams);

        JsonParser parser = new JsonParser();

        String jsonText = gson.toJson(feed);

        return jsonText;
    }
}


text:
/**
 *
 */
package com.ocean.test;

/**
 * @author junfang
 *
 */
public class BB {
	public static String getString() {
		System.out.println("1111");
		return " dggdgdgdgdg";

	}

	public static String getString2() {
		System.out.println("222");
		return " wwwwwwwwwwwwwww";

	}

	public  String getString3() {
		System.out.println("3333");
		return " dggdgdgdgdg";

	}

	public  String getString4() {
		System.out.println("44444");
		return " wwwwwwwwwwwwwww";

	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BB bb=new BB();
		String  temp=bb.getString4()+bb.getString3();
		System.out.println(temp);

	}

}


text:
from __future__ import absolute_import, unicode_literals

from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth import forms as auth_forms
from .models import User

class UserChangeForm(auth_forms.UserChangeForm):
    class Meta(auth_forms.UserChangeForm.Meta):
        model = User

class UserCreationForm(auth_forms.UserCreationForm):

    error_message = auth_forms.UserCreationForm.error_messages.update({
        'duplicate_username': 'This username has already been taken.'
    })

    class Meta(auth_forms.UserCreationForm.Meta):
        model = User

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

@admin.register(User)
class UserAdmin(AuthUserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm
    fieldsets = (
            ('User Profile', {'fields': ('name',)}),
    ) + AuthUserAdmin.fieldsets
    list_display = ('username', 'is_superuser')
    search_fields = ['name']


text:
#pragma checksum "..\..\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "5A1D8C5A1876E53B0034E44E8CFF3258"
//------------------------------------------------------------------------------
// <auto-generated>
//     Este código fue generado por una herramienta.
//     Versión de runtime:4.0.30319.18051
//
//     Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
//     se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;

namespace Microsoft.Samples.Kinect.SkeletonBasics {

    /// <summary>
    /// App
    /// </summary>
    public partial class App : System.Windows.Application {

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        public void InitializeComponent() {

            #line 4 "..\..\App.xaml"
            this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);

            #line default
            #line hidden
        }

        /// <summary>
        /// Application Entry Point.
        /// </summary>
        [System.STAThreadAttribute()]
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        public static void Main() {
            Microsoft.Samples.Kinect.SkeletonBasics.App app = new Microsoft.Samples.Kinect.SkeletonBasics.App();
            app.InitializeComponent();
            app.Run();
        }
    }
}


text:
import React, { ReactElement } from 'react';
// eslint-disable-next-line @talend/import-depth
import { IconNameWithSize } from '@talend/icons/dist/typeUtils';
import { DataAttributes } from '../../types';
import { Icon } from './Icon';
import { SizedIcon } from './SizedIcon';

export function getIconWithDeprecatedSupport({
	iconSrc,
	size,
	...rest
}: {
	iconSrc: string | ReactElement;
	size: 'XS' | 'S' | 'M' | 'L';
} & DataAttributes) {
	if (typeof iconSrc === 'string') {
		if (iconSrc.includes('talend-') || iconSrc.includes('remote-') || iconSrc.includes('src-')) {
			return <Icon name={iconSrc} {...rest} />;
		}
		return <SizedIcon size={size} name={iconSrc as IconNameWithSize<typeof size>} {...rest} />;
	}

	return React.cloneElement(iconSrc, {});
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <!-- Allow dynamic config changes via JMX -->
    <jmxConfigurator/>

    <!-- Rolling file appender -->
    <appender name="FileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.dir}/webapp-out.log</file>
        <encoder class="org.oclc.elk.demo.logging.logback.LogstashEncoder">
            <sourceApplication>ServiceE</sourceApplication>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.dir}/webapp-out.log.%d{yyyy-MM-dd}</fileNamePattern>
        </rollingPolicy>
    </appender>

    <root>
        <level value="info"/>
        <appender-ref ref="FileAppender"/>
    </root>

    <logger name="org.oclc">
        <level value="debug" />
    </logger>

    <logger name="org.oclc.tracing.timed">
        <level value="trace" />
    </logger>

</configuration>


text:
package com.linecorp.armeria.server.auth;

import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Nullable;

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

import com.google.common.base.Strings;

import com.linecorp.armeria.common.HttpHeaders;

import io.netty.util.AsciiString;

/**
 * Extracts {@link OAuth2Token} from {@link HttpHeaders}, in order to be used by {@link HttpAuthServiceBuilder}.
 */
final class OAuth2TokenExtractor implements Function<HttpHeaders, OAuth2Token> {

    private static final Logger logger = LoggerFactory.getLogger(OAuth2TokenExtractor.class);
    private static final Pattern AUTHORIZATION_HEADER_PATTERN = Pattern.compile(
            "\\s*(?i)bearer\\s+(?<accessToken>\\S+)\\s*");

    private final AsciiString header;

    OAuth2TokenExtractor(AsciiString header) {
        this.header = header;
    }

    @Nullable
    @Override
    public OAuth2Token apply(HttpHeaders headers) {
        final String authorization = headers.get(header);
        if (Strings.isNullOrEmpty(authorization)) {
            return null;
        }

        final Matcher matcher = AUTHORIZATION_HEADER_PATTERN.matcher(authorization);
        if (!matcher.matches()) {
            logger.warn("Invalid authorization header: " + authorization);
            return null;
        }

        return OAuth2Token.of(matcher.group("accessToken"));
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}

-- | Query tests

module Database.CouchDB.Conduit.Test.Query (tests) where

import Test.Framework (testGroup, mutuallyExclusive, Test)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, (@=?))

import Control.Monad.IO.Class (liftIO)

import Database.CouchDB.Conduit.View.Query

tests :: Test
tests = mutuallyExclusive $ testGroup "Generic" [
    testCase "Descending" caseDescending
    ]

caseDescending :: Assertion
caseDescending = liftIO $ do
    mkQuery [QPInt "i" 0] @=? [("i", Just "0")]
    mkQuery [QPDescending, QPInt "i" 0] @=?
            [desc, ("i", Just "0")]
    let swappable = [QPStartKey (0::Int), QPEndKey (1::Int)]
    mkQuery swappable @=?
            [("startkey", Just "0"), ("endkey", Just "1")]
    mkQuery (QPDescending : swappable) @=?
            [desc, ("endkey", Just "0"), ("startkey", Just "1")]
  where
    desc = ("descending", Just "true")


text:
Loading...

ERROR!

     Add Collection

                    Id
                    Name

                    No collections found!

                    {{collection.id}}
                    {{collection.name}}

                             View
                             Edit
                            <button
                                class='btn btn-danger'
                                ng-class='{"disabled": meta(collection).deleteDisabled.value}'
                                ng-click='delete(collection)'
                                tooltip='{{ meta(collection).deleteDisabled.tooltip }}'
                                tooltip-placement='right'
                            ></button>


text:
import {Component, OnInit} from '@angular/core';
import { ApiService } from '../../services/api.service';

@Component ({
     selector: 'main-news',
     templateUrl: './main-news.component.html',
     styleUrls: ['./main-news.component.scss'],
 })

 export default class MainNewsComponent implements OnInit{
    news: any;

    constructor(private API: ApiService){}
    ngOnInit(){

        this.API.get('news')
                .subscribe((response)=> this.news = response);

    }
     createSlugFromTitle(title: string): string{

        return title.toLowerCase().split(' ').join('-');

    }
}


text:
package com.gdgand.rxjava.rxjavasample.queue.command;

import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

public class BottomCommand implements Command {
    private final Queue2Adapter adapter;

    public BottomCommand(Queue2Adapter adapter) {

        this.adapter = adapter;
    }

    @Override
    public void call() {
        try {
            Thread.sleep(700);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Observable.just(adapter.getItemCount())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    adapter.add(0, "Bottom : " + String.valueOf(integer));
                    adapter.notifyDataSetChanged();
                });
    }
}


text:
package com.intellij.util;

import com.intellij.openapi.diagnostic.Logger;
import org.jetbrains.annotations.NotNull;

public class DeprecatedMethodException extends RuntimeException {
  private static final Logger LOG = Logger.getInstance(DeprecatedMethodException.class);
  private DeprecatedMethodException(String message) {
    super(message);
  }

  public static void report(@NotNull String message) {

    LOG.warn(new DeprecatedMethodException("This method in " + ReflectionUtil.findCallerClass(2) +
                                           " is deprecated and going to be removed soon. "+message));
  }
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ipc/ipc_message.h"

#include <stddef.h>
#include <stdint.h>
#include <string.h>

#include <limits>
#include <memory>

#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "ipc/ipc_message_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

// IPC messages for testing ----------------------------------------------------

#define IPC_MESSAGE_IMPL
#include "ipc/ipc_message_macros.h"

#define IPC_MESSAGE_START TestMsgStart

IPC_MESSAGE_CONTROL0(TestMsgClassEmpty)

IPC_MESSAGE_CONTROL1(TestMsgClassI, int)

IPC_SYNC_MESSAGE_CONTROL1_1(TestMsgClassIS, int, std::string)

namespace IPC {

TEST(IPCMessageTest, BasicMessageTest) {
  int v1 = 10;
  std::string v2("foobar");
  base::string16 v3(base::ASCIIToUTF16("hello world"));

  IPC::Message m(0, 1, IPC::Message::PRIORITY_NORMAL);
  EXPECT_TRUE(m.WriteInt(v1));
  EXPECT_TRUE(m.WriteString(v2));
  EXPECT_TRUE(m.WriteString16(v3));

  base::PickleIterator iter(m);

  int vi;
  std::string vs;
  base::string16 vs16;

  EXPECT_TRUE(iter.ReadInt(&vi));
  EXPECT_EQ(v1, vi);

  EXPECT_TRUE(iter.ReadString(&vs));
  EXPECT_EQ(v2, vs);

  EXPECT_TRUE(iter.ReadString16(&vs16));
  EXPECT_EQ(v3, vs16);

  // should fail
  EXPECT_FALSE(iter.ReadInt(&vi));
  EXPECT_FALSE(iter.ReadString(&vs));
  EXPECT_FALSE(iter.ReadString16(&vs16));
}

TEST(IPCMessageTest, ListValue) {
  base::ListValue input;
  input.Set(0, new base::FundamentalValue(42.42));
  input.Set(1, new base::StringValue("forty"));
  input.Set(2, base::Value::CreateNullValue());

  IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL);
  IPC::WriteParam(&msg, input);

  base::ListValue output;
  base::PickleIterator iter(msg);
  EXPECT_TRUE(IPC::ReadParam(&msg, &iter, &output));

  EXPECT_TRUE(input.Equals(&output));

  // Also test the corrupt case.
  IPC::Message bad_msg(1, 2, IPC::Message::PRIORITY_NORMAL);
  bad_msg.WriteInt(99);
  iter = base::PickleIterator(bad_msg);
  EXPECT_FALSE(IPC::ReadParam(&bad_msg, &iter, &output));
}

TEST(IPCMessageTest, DictionaryValue) {
  base::DictionaryValue input;
  input.Set("null", base::Value::CreateNullValue());
  input.Set("bool", new base::FundamentalValue(true));
  input.Set("int", new base::FundamentalValue(42));
  input.SetWithoutPathExpansion("int.with.dot", new base::FundamentalValue(43));

  std::unique_ptr<base::DictionaryValue> subdict(new base::DictionaryValue());
  subdict->Set("str", new base::StringValue("forty two"));
  subdict->Set("bool", new base::FundamentalValue(false));

  std::unique_ptr<base::ListValue> sublist(new base::ListValue());
  sublist->Set(0, new base::FundamentalValue(42.42));
  sublist->Set(1, new base::StringValue("forty"));
  sublist->Set(2, new base::StringValue("two"));
  subdict->Set("list", sublist.release());

  input.Set("dict", subdict.release());

  IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL);
  IPC::WriteParam(&msg, input);

  base::DictionaryValue output;
  base::PickleIterator iter(msg);
  EXPECT_TRUE(IPC::ReadParam(&msg, &iter, &output));

  EXPECT_TRUE(input.Equals(&output));

  // Also test the corrupt case.
  IPC::Message bad_msg(1, 2, IPC::Message::PRIORITY_NORMAL);
  bad_msg.WriteInt(99);
  iter = base::PickleIterator(bad_msg);
  EXPECT_FALSE(IPC::ReadParam(&bad_msg, &iter, &output));
}

TEST(IPCMessageTest, FindNext) {
  IPC::Message message;
  EXPECT_TRUE(message.WriteString("Goooooooogle"));
  EXPECT_TRUE(message.WriteInt(111));

  std::vector<char> message_data(message.size() + 7);
  memcpy(message_data.data(), message.data(), message.size());

  const char* data_start = message_data.data();
  const char* data_end = data_start + message.size();

  IPC::Message::NextMessageInfo next;

  // Data range contains the entire message plus some extra bytes
  IPC::Message::FindNext(data_start, data_end + 1, &next);
  EXPECT_TRUE(next.message_found);
  EXPECT_EQ(next.message_size, message.size());
  EXPECT_EQ(next.pickle_end, data_end);
  EXPECT_EQ(next.message_end, data_end);

  // Data range exactly contains the entire message
  IPC::Message::FindNext(data_start, data_end, &next);
  EXPECT_TRUE(next.message_found);
  EXPECT_EQ(next.message_size, message.size());
  EXPECT_EQ(next.pickle_end, data_end);
  EXPECT_EQ(next.message_end, data_end);

  // Data range doesn't contain the entire message
  // (but contains the message header)
  IPC::Message::FindNext(data_start, data_end - 1, &next);
  EXPECT_FALSE(next.message_found);
  EXPECT_EQ(next.message_size, message.size());

  // Data range doesn't contain the message header
  // (but contains the pickle header)
  IPC::Message::FindNext(data_start,
                         data_start + sizeof(IPC::Message::Header) - 1,
                         &next);
  EXPECT_FALSE(next.message_found);
  EXPECT_EQ(next.message_size, 0u);

  // Data range doesn't contain the pickle header
  IPC::Message::FindNext(data_start,
                         data_start + sizeof(base::Pickle::Header) - 1,
                         &next);
  EXPECT_FALSE(next.message_found);
  EXPECT_EQ(next.message_size, 0u);
}

TEST(IPCMessageTest, FindNextOverflow) {
  IPC::Message message;
  EXPECT_TRUE(message.WriteString("Data"));
  EXPECT_TRUE(message.WriteInt(777));

  const char* data_start = reinterpret_cast<const char*>(message.data());
  const char* data_end = data_start + message.size();

  IPC::Message::NextMessageInfo next;

  // Payload size is negative (defeats 'start + size > end' check)
  message.header()->payload_size = static_cast<uint32_t>(-1);
  IPC::Message::FindNext(data_start, data_end, &next);
  EXPECT_FALSE(next.message_found);
  if (sizeof(size_t) > sizeof(uint32_t)) {
    // No overflow, just insane message size
    EXPECT_EQ(next.message_size,
              message.header()->payload_size + sizeof(IPC::Message::Header));
  } else {
    // Actual overflow, reported as max size_t
    EXPECT_EQ(next.message_size, std::numeric_limits<size_t>::max());
  }

  // Payload size is max positive integer (defeats size < 0 check, while
  // still potentially causing overflow down the road).
  message.header()->payload_size = std::numeric_limits<int32_t>::max();
  IPC::Message::FindNext(data_start, data_end, &next);
  EXPECT_FALSE(next.message_found);
  EXPECT_EQ(next.message_size,
            message.header()->payload_size + sizeof(IPC::Message::Header));
}

namespace {

class IPCMessageParameterTest : public testing::Test {
 public:
  IPCMessageParameterTest() : extra_param_("extra_param"), called_(false) {}

  bool OnMessageReceived(const IPC::Message& message) {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(IPCMessageParameterTest, message,
                                     &extra_param_)
      IPC_MESSAGE_HANDLER(TestMsgClassEmpty, OnEmpty)
      IPC_MESSAGE_HANDLER(TestMsgClassI, OnInt)
      //IPC_MESSAGE_HANDLER(TestMsgClassIS, OnSync)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()

    return handled;
  }

  void OnEmpty(std::string* extra_param) {
    EXPECT_EQ(extra_param, &extra_param_);
    called_ = true;
  }

  void OnInt(std::string* extra_param, int foo) {
    EXPECT_EQ(extra_param, &extra_param_);
    EXPECT_EQ(foo, 42);
    called_ = true;
  }

  /* TODO: handle sync IPCs
    void OnSync(std::string* extra_param, int foo, std::string* out) {
    EXPECT_EQ(extra_param, &extra_param_);
    EXPECT_EQ(foo, 42);
    called_ = true;
    *out = std::string("out");
  }

  bool Send(IPC::Message* reply) {
    delete reply;
    return true;
  }*/

  std::string extra_param_;
  bool called_;
};

}  // namespace

TEST_F(IPCMessageParameterTest, EmptyDispatcherWithParam) {
  TestMsgClassEmpty message;
  EXPECT_TRUE(OnMessageReceived(message));
  EXPECT_TRUE(called_);
}

#if defined(OS_ANDROID)
#define MAYBE_OneIntegerWithParam DISABLED_OneIntegerWithParam
#else
#define MAYBE_OneIntegerWithParam OneIntegerWithParam
#endif
TEST_F(IPCMessageParameterTest, MAYBE_OneIntegerWithParam) {
  TestMsgClassI message(42);
  EXPECT_TRUE(OnMessageReceived(message));
  EXPECT_TRUE(called_);
}

/* TODO: handle sync IPCs
TEST_F(IPCMessageParameterTest, Sync) {
  std::string output;
  TestMsgClassIS message(42, &output);
  EXPECT_TRUE(OnMessageReceived(message));
  EXPECT_TRUE(called_);
  EXPECT_EQ(output, std::string("out"));
}*/

}  // namespace IPC


text:
namespace inCapsulam
{
    partial class UserControlConstraintsManager
    {
        /// <summary>
        /// Требуется переменная конструктора.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Код, автоматически созданный конструктором компонентов

        /// <summary>
        /// Обязательный метод для поддержки конструктора - не изменяйте
        /// содержимое данного метода при помощи редактора кода.
        /// </summary>
        private void InitializeComponent()
        {
            this.constraintsListBox = new System.Windows.Forms.ListBox();
            this.expressionTextBox = new System.Windows.Forms.TextBox();
            this.buttonNew = new System.Windows.Forms.Button();
            this.buttonSave = new System.Windows.Forms.Button();
            this.buttonRemove = new System.Windows.Forms.Button();
            this.buttonTest = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // constraintsListBox
            //
            this.constraintsListBox.Font = new System.Drawing.Font("Cambria", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.constraintsListBox.ItemHeight = 19;
            this.constraintsListBox.Location = new System.Drawing.Point(0, 149);
            this.constraintsListBox.Name = "constraintsListBox";
            this.constraintsListBox.Size = new System.Drawing.Size(340, 156);
            this.constraintsListBox.TabIndex = 0;
            this.constraintsListBox.SelectedIndexChanged += new System.EventHandler(this.constraintsListBox_SelectedIndexChanged);
            //
            // expressionTextBox
            //
            this.expressionTextBox.Font = new System.Drawing.Font("Cambria", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.expressionTextBox.Location = new System.Drawing.Point(0, 29);
            this.expressionTextBox.Multiline = true;
            this.expressionTextBox.Name = "expressionTextBox";
            this.expressionTextBox.Size = new System.Drawing.Size(340, 114);
            this.expressionTextBox.TabIndex = 1;
            this.expressionTextBox.TextChanged += new System.EventHandler(this.expressionTextBox_TextChanged);
            //
            // buttonNew
            //
            this.buttonNew.Location = new System.Drawing.Point(0, 0);
            this.buttonNew.Name = "buttonNew";
            this.buttonNew.Size = new System.Drawing.Size(75, 23);
            this.buttonNew.TabIndex = 2;
            this.buttonNew.Text = "Новое";
            this.buttonNew.UseVisualStyleBackColor = true;
            this.buttonNew.Click += new System.EventHandler(this.buttonNew_Click);
            //
            // buttonSave
            //
            this.buttonSave.Location = new System.Drawing.Point(162, 0);
            this.buttonSave.Name = "buttonSave";
            this.buttonSave.Size = new System.Drawing.Size(75, 23);
            this.buttonSave.TabIndex = 3;
            this.buttonSave.Text = "Сохранить";
            this.buttonSave.UseVisualStyleBackColor = true;
            this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
            //
            // buttonRemove
            //
            this.buttonRemove.Location = new System.Drawing.Point(243, 0);
            this.buttonRemove.Name = "buttonRemove";
            this.buttonRemove.Size = new System.Drawing.Size(75, 23);
            this.buttonRemove.TabIndex = 4;
            this.buttonRemove.Text = "Удалить";
            this.buttonRemove.UseVisualStyleBackColor = true;
            this.buttonRemove.Click += new System.EventHandler(this.buttonRemove_Click);
            //
            // buttonTest
            //
            this.buttonTest.Location = new System.Drawing.Point(81, 0);
            this.buttonTest.Name = "buttonTest";
            this.buttonTest.Size = new System.Drawing.Size(75, 23);
            this.buttonTest.TabIndex = 5;
            this.buttonTest.Text = "Тест";
            this.buttonTest.UseVisualStyleBackColor = true;
            this.buttonTest.Click += new System.EventHandler(this.buttonTest_Click);
            //
            // UserControlConstraintsManager
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.buttonTest);
            this.Controls.Add(this.buttonRemove);
            this.Controls.Add(this.buttonSave);
            this.Controls.Add(this.buttonNew);
            this.Controls.Add(this.expressionTextBox);
            this.Controls.Add(this.constraintsListBox);
            this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.Name = "UserControlConstraintsManager";
            this.Size = new System.Drawing.Size(343, 307);
            this.Resize += new System.EventHandler(this.UserControlConstraintsManager_Resize);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ListBox constraintsListBox;
        private System.Windows.Forms.TextBox expressionTextBox;
        private System.Windows.Forms.Button buttonNew;
        private System.Windows.Forms.Button buttonSave;
        private System.Windows.Forms.Button buttonRemove;
        private System.Windows.Forms.Button buttonTest;
    }
}


text:
<?php

namespace bmwx591\google\maps\overlays;

use bmwx591\google\maps\ObjectAbstract;
use bmwx591\google\maps\OptionsTrait;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;

/**
 * MarkerShape
 *
 * Object for the anonymous constructor of a symbol. For further reference of the options available please visit
 * https://developers.google.com/maps/documentation/javascript/reference#Symbol
 *
 *
 * @property array coords The format of this attribute depends on the value of the type and follows the w3 AREA coords
 * specification found at http://www.w3.org/TR/REC-html40/struct/objects.html#adef-coords.
 * The coords attribute is an array of integers that specify the pixel position of the shape relative to the top-left
 * corner of the target image. The coordinates depend on the value of type as follows:
 *
 * - circle: coords is [x1,y1,r] where x1,y2 are the coordinates of the center of the circle, and r is the radius of the
 * circle.
 * - poly: coords is [x1,y1,x2,y2...xn,yn] where each x,y pair contains the coordinates of one vertex of the polygon.
 * - rect: coords is [x1,y1,x2,y2] where x1,y1 are the coordinates of the upper-left corner of the rectangle and x2,y2
 * are the coordinates of the lower-right coordinates of the rectangle.
 *
 * @property string type Describes the shape's type and can be circle, poly or rect.
 *
 *
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
 * @link http://www.ramirezcobos.com/
 * @link http://www.2amigos.us/
 * @package bmwx591\google\maps
 */
class MarkerShape extends ObjectAbstract
{
    use OptionsTrait;

    /**
     * @inheritdoc
     *
     * @param array $config
     */
    public function __construct($config = [])
    {
        $this->options = ArrayHelper::merge(
            [
                'coords' => null,
                'type' => null
            ],
            $this->options
        );

        parent::__construct($config);
    }

    /**
     * @inheritdoc
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {

        if ($this->coords == null) {
            throw new InvalidConfigException('"coords" cannot be null');
        }

        if ($this->type == null) {
            throw new InvalidConfigException('"type" cannot be null');
        }
    }

}


text:
var p = require("path");

module.exports = function loadConfig(configLocation) {
    var contents = require("fs").readFileSync(configLocation, {encoding: "utf8"});
    var config = JSON.parse(contents);
    config.eslintRulesDir = p.resolve(config.eslintRulesDir);
    config.srcPath = p.resolve(config.srcPath);
    config.karmaPath = p.resolve(config.karmaPath);
    config.artifactPath = p.resolve(config.artifactPath);
    config.fullEntryGlob = require("path").join(config.srcPath, config.entryGlob);
    return config;
};


text:
package me.lorenc.dreadlogs.captor.logback;

import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.LinkedList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import ch.qos.logback.classic.spi.ILoggingEvent;
import me.lorenc.dreadlogs.captor.LogCapture;

@RunWith(MockitoJUnitRunner.class)
public class LogbackCapturingAppenderTest {

    @Mock
    private LogCapture<ILoggingEvent> logCapture;
    @Mock
    private ILoggingEvent loggingEvent;

    private LogbackCapturingAppender capturingAppender;

    @Before
    public void before() throws Exception {
        capturingAppender = new LogbackCapturingAppender(logCapture);
    }

    @Test
    public void shouldCaptureLoggingEvent() throws Exception {

        capturingAppender.append(loggingEvent);

        verify(logCapture, only()).capture(loggingEvent);
    }

    @Test
    public void shouldResetLogCapture() throws Exception {

        capturingAppender.reset();

        verify(logCapture, only()).reset();
    }

    @Test
    public void shouldReturnCapturedLogs() throws Exception {
        List<ILoggingEvent> expectedList = new LinkedList<ILoggingEvent>();
        when(logCapture.getCapturedLogs()).thenReturn(expectedList);

        List<ILoggingEvent> capturedLogs = capturingAppender.getCapturedLogs();

        assertThat(capturedLogs, sameInstance(expectedList));

        verify(logCapture, only()).getCapturedLogs();
    }

}


text:
package PredatorPrey;

import repast.simphony.context.Context;
import repast.simphony.engine.environment.RunEnvironment;
import repast.simphony.parameter.Parameters;
import repast.simphony.space.grid.Grid;
import repast.simphony.space.grid.GridPoint;
import repast.simphony.util.ContextUtils;

/**
 * The wolf agent.
 *
 * @author Eric Tatara
 */

public class Wolf extends SimpleAgent {

	// This constructor is used to create an offspring
	public Wolf (double energy){
		this.setEnergy(energy);               // assign the offspring energy
		this.setHeading(Math.random()*360);   // randomize the heading from 0-360 degrees
	}

	// This constructor is used to create initial wolves from the context creator
	public Wolf(){
		// Get the value of the wolf gain from food from the environment parameters
		Parameters p = RunEnvironment.getInstance().getParameters();
		double gain = (Double)p.getValue("wolfgainfromfood");

		this.setEnergy(Math.random() * 2 * gain);    // set the initial energy
		this.setHeading(Math.random()*360);          //  and initial heading
	}

  @Override
	public void step() {
    // Get the context in which the wolf resides.
		Context context = ContextUtils.getContext(this);

		// Move the wolf
		move();

		// Reduce the wolf's energy by one unit
		this.setEnergy(this.getEnergy() - 1);

		// Catch sheep
    // Get the patch grid from the context
		Grid patch = (Grid) context.getProjection("Simple Grid");

		// Get the wolf's current patch
		GridPoint point = patch.getLocation(this);

		int x = point.getX();    // The x-ccordinate of the wolf's current patch
		int y = point.getY();    // The y-ccordinate of the wolf's current patch

		// Get the wolf gain from food from the user parameters
		Parameters p = RunEnvironment.getInstance().getParameters();
		double gain = (Double)p.getValue("wolfgainfromfood");

		// Find sheep at the patch and eat it if one exists
		Sheep sheep = null;
		for (Object o: patch.getObjectsAt(x,y)){
			if (o instanceof Sheep)
				sheep = (Sheep)o;
		}
		// If there is a sheep on the patch then eat it
		if (sheep != null){
			sheep.die();              // kill the sheep
			this.setEnergy(this.getEnergy() + gain);   // increment the wolf's energy
		}

		// Reproduce the wolf
    // Get the reproduction rate from the user parameters
		double rate = (Double)p.getValue("wolfreproduce");

    //	Spawn a new wolf if a random draw on [0,100) < reproduction rate
		if (100*Math.random() < rate){
			this.setEnergy(this.getEnergy() / 2);      // divide the parent's energy in half
			Wolf wolf = new Wolf(this.getEnergy());    // create a new wolf offspring and assing its energy
			context.add(wolf);	                       // add the offspring to the root context
		}

		// Death
		if (this.getEnergy() < 0)
			die();
	}

  // Public getter for the data gatherer for counting
	@Override
	public int isWolf() {
		return 1;
	}
}


text:
<!DOCTYPE HTML>

<title>Uses of Class com.ensoftcorp.open.android.essentials.permissions.AndroidManifest</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2020-05-24">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Uses of Class
com.ensoftcorp.open.android.essentials.permissions.AndroidManifest

Packages that use AndroidManifest

Package
Description

com.ensoftcorp.open.android.essentials.permissions

Uses of AndroidManifest in com.ensoftcorp.open.android.essentials.permissions

Methods in com.ensoftcorp.open.android.essentials.permissions that return types with arguments of type AndroidManifest

Modifier and Type
Method
Description

static java.util.Collection<AndroidManifest>
AndroidManifest.parseManifestFiles(java.util.Collection<java.io.File> files)

Returns a collection of Manifest objects for each AndroidManifest.xml file given

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help


text:
package net.geocentral.geometria.event;

import java.util.ArrayList;
import java.util.Collection;
import java.util.EventObject;

public class GEventHandler {

    private Collection<GEventListener> listeners;

    public GEventHandler() {
        listeners = new ArrayList<GEventListener>();
    }

    public void addListener(GEventListener listener) {
        listeners.add(listener);
    }

    public void fireEvent(EventObject event) {
        for (GEventListener listener : listeners)
            listener.handleEvent(event);
    }
}


text:
TypeScript cannot always infer types for all places in code.
Some locations require type annotations for their types to be inferred.

```ts
class ContainsText {
  // There must be a type annotation here to infer the type
  delayedText: string;

  // `typedef` requires a type annotation here to maintain consistency
  immediateTextExplicit: string = 'text';

  // This is still a string type because of its initial value
  immediateTextImplicit = 'text';
}
```

**_Note:_** requiring type annotations unnecessarily can be cumbersome to maintain and generally reduces code readability.
TypeScript is often better at inferring types than easily written type annotations would allow.

**Instead of enabling `typedef`, it is generally recommended to use the `--noImplicitAny` and `--strictPropertyInitialization` compiler options to enforce type annotations only when useful.**

## Rule Details

This rule can enforce type annotations in locations regardless of whether they're required.
This is typically used to maintain consistency for element types that sometimes require them.

> To enforce type definitions existing on call signatures as per TSLint's `arrow-call-signature` and `call-signature` options, use `explicit-function-return-type`, or `explicit-module-boundary-types`.

## Options

```ts
type Options = {
  arrayDestructuring?: boolean;
  arrowParameter?: boolean;
  memberVariableDeclaration?: boolean;
  objectDestructuring?: boolean;
  parameter?: boolean;
  propertyDeclaration?: boolean;
  variableDeclaration?: boolean;
  variableDeclarationIgnoreFunction?: boolean;
};

const defaultOptions: Options = {
  arrayDestructuring: false,
  arrowParameter: false,
  memberVariableDeclaration: false,
  objectDestructuring: false,
  parameter: false,
  propertyDeclaration: false,
  variableDeclaration: false,
  variableDeclarationIgnoreFunction: false,
};
```

For example, with the following configuration:

```json
{
  "rules": {
    "@typescript-eslint/typedef": [
      "error",
      {
        "arrowParameter": true,
        "variableDeclaration": true
      }
    ]
  }
}
```

- Type annotations on arrow function parameters are required
- Type annotations on variables are required

### `arrayDestructuring`

Whether to enforce type annotations on variables declared using array destructuring.

Examples of **incorrect** code with `{ "arrayDestructuring": true }`:

```ts
const [a] = [1];
const [b, c] = [1, 2];
```

Examples of **correct** code with `{ "arrayDestructuring": true }`:

```ts
const [a]: number[] = [1];
const [b]: [number] = [2];
const [c, d]: [boolean, string] = [true, 'text'];

for (const [key, val] of new Map([['key', 1]])) {
}
```

### `arrowParameter`

Whether to enforce type annotations for parameters of arrow functions.

Examples of **incorrect** code with `{ "arrowParameter": true }`:

```ts
const logsSize = size => console.log(size);

['hello', 'world'].map(text => text.length);

const mapper = {
  map: text => text + '...',
};
```

Examples of **correct** code with `{ "arrowParameter": true }`:

```ts
const logsSize = (size: number) => console.log(size);

['hello', 'world'].map((text: string) => text.length);

const mapper = {
  map: (text: string) => text + '...',
};
```

### `memberVariableDeclaration`

Whether to enforce type annotations on member variables of classes.

Examples of **incorrect** code with `{ "memberVariableDeclaration": true }`:

```ts
class ContainsText {
  delayedText;
  immediateTextImplicit = 'text';
}
```

Examples of **correct** code with `{ "memberVariableDeclaration": true }`:

```ts
class ContainsText {
  delayedText: string;
  immediateTextImplicit: string = 'text';
}
```

### `objectDestructuring`

Whether to enforce type annotations on variables declared using object destructuring.

Examples of **incorrect** code with `{ "objectDestructuring": true }`:

```ts
const { length } = 'text';
const [b, c] = Math.random() ? [1, 2] : [3, 4];
```

Examples of **correct** code with `{ "objectDestructuring": true }`:

```ts
const { length }: { length: number } = 'text';
const [b, c]: [number, number] = Math.random() ? [1, 2] : [3, 4];

for (const { key, val } of [{ key: 'key', val: 1 }]) {
}
```

### `parameter`

Whether to enforce type annotations for parameters of functions and methods.

Examples of **incorrect** code with `{ "parameter": true }`:

```ts
function logsSize(size): void {
  console.log(size);
}

const doublesSize = function (size): number {
  return size * 2;
};

const divider = {
  curriesSize(size): number {
    return size;
  },
  dividesSize: function (size): number {
    return size / 2;
  },
};

class Logger {
  log(text): boolean {
    console.log('>', text);
    return true;
  }
}
```

Examples of **correct** code with `{ "parameter": true }`:

```ts
function logsSize(size: number): void {
  console.log(size);
}

const doublesSize = function (size: number): number {
  return size * 2;
};

const divider = {
  curriesSize(size: number): number {
    return size;
  },
  dividesSize: function (size: number): number {
    return size / 2;
  },
};

class Logger {
  log(text: boolean): boolean {
    console.log('>', text);
    return true;
  }
}
```

### `propertyDeclaration`

Whether to enforce type annotations for properties of interfaces and types.

Examples of **incorrect** code with `{ "propertyDeclaration": true }`:

```ts
type Members = {
  member;
  otherMember;
};
```

Examples of **correct** code with `{ "propertyDeclaration": true }`:

```ts
type Members = {
  member: boolean;
  otherMember: string;
};
```

### `variableDeclaration`

Whether to enforce type annotations for variable declarations, excluding array and object destructuring.

Examples of **incorrect** code with `{ "variableDeclaration": true }`:

```ts
const text = 'text';
let initialText = 'text';
let delayedText;
```

Examples of **correct** code with `{ "variableDeclaration": true }`:

```ts
const text: string = 'text';
let initialText: string = 'text';
let delayedText: string;
```

### `variableDeclarationIgnoreFunction`

Ignore variable declarations for non-arrow and arrow functions.

Examples of **incorrect** code with `{ "variableDeclaration": true, "variableDeclarationIgnoreFunction": true }`:

```ts
const text = 'text';
```

Examples of **correct** code with `{ "variableDeclaration": true, "variableDeclarationIgnoreFunction": true }`:

```ts
const a = (): void => {};
const b = function (): void => {};
const c: () => void = (): void => {};

class Foo {
  a = (): void => {};
  b = function (): void => {};
  c = () => void = (): void => {};
}
```

## When Not To Use It

If you are using stricter TypeScript compiler options, particularly `--noImplicitAny` and/or `--strictPropertyInitialization`, you likely don't need this rule.

In general, if you do not consider the cost of writing unnecessary type annotations reasonable, then do not use this rule.

## Further Reading

- [TypeScript Type System](https://basarat.gitbooks.io/typescript/docs/types/type-system.html)
- [Type Inference](https://www.typescriptlang.org/docs/handbook/type-inference.html)

## Compatibility

- TSLint: [`typedef`](https://palantir.github.io/tslint/rules/typedef)


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-3437',
  templateUrl: './comp-3437.component.html',
  styleUrls: ['./comp-3437.component.css']
})
export class Comp3437Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


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

@Component({
	template: '
This is the Home page
',
})
export class HomeComponent {}


text:
package gameAuthoring.scenes;

import gameAuthoring.mainclasses.AuthorController;
import gameAuthoring.mainclasses.Constants;
import gameAuthoring.mainclasses.controllerInterfaces.IGeneralSettingsConfiguring;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import utilities.GSON.objectWrappers.GeneralSettingsWrapper;
import utilities.JavaFXutilities.numericalTextFields.NumericalTextField;
import utilities.multilanguage.MultiLanguageUtility;

public class GeneralSettingScene {

    private static final int BTN_SPACE = 140;
    private static final String GENERAL_SETTINGS_IMG_PATH =
            "gameAuthoring/scenes/GeneralSettingsImage.png";
    private static final double FIELD_WIDTH = AuthorController.SCREEN_WIDTH / 4;
    private static final String MULTIPLAYER = "Coop";
    private static final String SINGLEPLAYER = "SinglePlayer";
    private IGeneralSettingsConfiguring myGeneralSettingsController;
    private Scene myScene;
    private VBox myVBox;
    private TextField myNameTextField;
    private NumericalTextField myStartingHealthField;
    private NumericalTextField myStartingCashField;
    private ComboBox<String> myGameTypeComboBox;
    private Group root;

    public GeneralSettingScene (IGeneralSettingsConfiguring controller) {
        myGeneralSettingsController = controller;
        root = new Group();
        myScene = new Scene(root, AuthorController.SCREEN_WIDTH,
                            AuthorController.SCREEN_HEIGHT);
        myVBox = new VBox(25);
        myVBox.setPrefWidth(AuthorController.SCREEN_WIDTH / 2);
        myVBox.setPadding(new Insets(100));
        myVBox.setAlignment(Pos.CENTER);

        createHeadingLabel();
        createOptionFields();
        createOptions();
        createNextButton();
        createRightImage();
    }

    private void createHeadingLabel () {
        Label headingLabel = new Label();
        headingLabel.textProperty().bind(MultiLanguageUtility.getInstance()
                                         .getStringProperty(Constants.GENERAL_SETTING_MSG));
        headingLabel.setStyle("-fx-font-size: 24px");
        myVBox.getChildren().add(headingLabel);
    }

    private void createOptionFields () {
        myNameTextField = new TextField();
        myNameTextField.setPrefWidth(AuthorController.SCREEN_WIDTH / 3);
        myStartingHealthField = new NumericalTextField(FIELD_WIDTH);
        myStartingCashField = new NumericalTextField(FIELD_WIDTH);
        myGameTypeComboBox = new ComboBox<String>();
        myGameTypeComboBox.getItems().addAll(SINGLEPLAYER, MULTIPLAYER);
    }

    private void createOptions () {
        myVBox.getChildren().addAll(createFieldWithLabel(Constants.NAME_OF_GAME,
                                                         myNameTextField),
                                    createFieldWithLabel(Constants.STARTING_HEALTH,
                                                         myStartingHealthField),
                                    createFieldWithLabel(Constants.STARTING_CASH,
                                                         myStartingCashField));
        HBox box = new HBox(BTN_SPACE);
        box.getChildren().addAll(createFieldWithLabel(Constants.SELECT_GAME_TYPE,
                                                      myGameTypeComboBox),
                                 createNextButton());
        myVBox.getChildren().add(box);
    }

    private VBox createFieldWithLabel (String labelName, Node node) {
        VBox box = new VBox(Constants.MED_PADDING);
        Label optionLabel = new Label();
        optionLabel.textProperty().bind(MultiLanguageUtility.getInstance()
                .getStringProperty(labelName));
        box.getChildren().addAll(optionLabel, node);
        return box;
    }

    private VBox createNextButton () {
        VBox box = new VBox(Constants.MED_PADDING);
        Button nextButton = new Button();
        nextButton.textProperty().bind(MultiLanguageUtility.getInstance()
                .getStringProperty(Constants.START_BUILDING));
        nextButton.setOnAction(event -> handleButtonClick());
        box.getChildren().addAll(new Label(""), nextButton);
        return box;
    }

    private void handleButtonClick () {
        String gameNameText = myNameTextField.getText();
        String gameType = myGameTypeComboBox.getValue();
        if (!gameNameText.isEmpty() && !gameType.isEmpty() &&
            myStartingCashField.isValueEntered() && myStartingHealthField.isValueEntered()) {
            myGeneralSettingsController.makeDirectory(gameNameText, gameType);
            GeneralSettingsWrapper wrapper =
                    new GeneralSettingsWrapper(myStartingHealthField.getNumber(),
                                               myStartingCashField.getNumber());
            myGeneralSettingsController.setGeneralSettings(wrapper);
        }
    }

    public void createRightImage () {
        HBox hb = new HBox();
        Image img = new Image(GENERAL_SETTINGS_IMG_PATH);
        ImageView imgView = new ImageView(img);
        imgView.setFitWidth(AuthorController.SCREEN_WIDTH / 2);
        imgView.setFitHeight(AuthorController.SCREEN_HEIGHT);
        hb.getChildren().addAll(myVBox, imgView);
        root.getChildren().add(hb);
    }

    public Scene getScene () {
        return myScene;
    }
}


text:
#pragma once

#include "dproc_config.h"
#include "dproc_constants.h"
#include "dptypes.h"
#include "dpdevice.h"
#include "dp_pixmanip.h"

#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

// This indicates that the machine the code is running on
// is a little endian machine, therefore, when laying out
// the values of a pixel in terms of bytes, the blue component
// is in the least significant byte of a 4 byte integer value.
#define BGR_DOMINANT 1

#include "dproc_types.h"

inline bool isBigEndian() {int t = 1;return (*(char*)&t == 0);}

inline real DEGREES(const real radians) { return (real)(G_RTOD * radians); }
inline real RADIANS(const real degrees) { return (real)(G_DTOR * degrees); }

// utils
#define min3(a,b,c) __min(__min(a,b),c)
#define max3(a,b,c) __max(__max(a,b),c)
#define MIN(a,b) __min(a,b)
#define MAX(a,b) __max(a,b)

// Map a value from one range to another
// A fraction is created to relate value (a) to the range (rlo - rhi).  This fraction
// is then applied to the second range (slo - shi).
// This will work for values of a both inside and outside the range itself
//inline double MAP(double a, double rlo, double rhi, double slo, double shi) { return slo + (a - rlo) * (shi - slo) / (rhi - rlo); }
#define MAP(a, rlo, rhi, slo, shi) (slo + (a - rlo) * (shi - slo) / (rhi - rlo))
#define map MAP

// Return a value between the rlo and rhi
inline double CLAMP(double a, double rlo, double rhi){ return a < rlo ? rlo : (a>rhi ? rhi : a); }

// turn a division by 255 into something
// much cheaper to calculate
// for values between 0 and 65534
#define div255(num) ((num + (num >> 8)) >> 8)

// perform a linear interpolation between a value 'a'
// a background value, and a foreground value, using
// fast div255
#define lerp255(bg, fg, a) ((uint8_t)div255((fg*a+bg*(255-a))))

// returns the sign of the value
// value  < 0 --> -1
// value  > 0 -->  1
// value == 0 -->  0
// this will only work in cases where 0 represents false
// and 1 represents true
inline int sgn(real val) { return ((0 < val) - (val < 0)); }

#ifdef BGR_DOMINANT
inline DPPIXELVAL RGBA(const int r, const int g, const int b, const int a)
{
	//return ARGB2PIXELABGR(a, r, g, b);
	return ARGB2PIXEL8888(a, r, g, b);
}

inline uint8_t GET_B(const uint32_t value) {return ((uint32_t)value & 0xff);}
inline uint8_t GET_G(const uint32_t value) {return (((uint32_t)value & 0xff00) >> 8);}
inline uint8_t GET_R(const uint32_t value) {return (((uint32_t)value & 0xff0000) >> 16);}
inline uint8_t GET_A(const uint32_t value) {return (((uint32_t)value & 0xff000000) >> 24);}
#else
#define RGBA(r,g,b,a) ((uint32_t)(a<<24|b<<16|g<<8|r))
#define GET_R(value) ((uint32_t)value &0xff)
#define GET_G(value) (((uint32_t)value &0xff00) >> 8)
#define GET_B(value) (((uint32_t)value &0xff0000) >> 16)
#define GET_A(value) (((uint32_t)value &0xff000000) >> 24)
#endif

#ifdef __cplusplus
extern "C" {
#endif

DPROC_API int pb_rgba_init(pb_rgba *pb, const unsigned int width, const unsigned int height);
DPROC_API int pb_rgba_free(pb_rgba *pb);

DPROC_API int pb_rgba_get_frame(pb_rgba *src, const DPCOORD x, const DPCOORD y, const size_t width, const size_t height, pb_rgba *pf);

DPROC_API void pb_rgba_cover_pixel(pb_rgba *pb, const DPCOORD x, const DPCOORD y, const DPPIXELVAL value);

#ifdef __cplusplus
}
#endif

inline DPPIXELVAL pb_rgba_get_pixel(pb_rgba *pb, const DPCOORD x, const DPCOORD y)
{
	return ((uint32_t *)(pb)->data)[(y*(pb)->pixelpitch) + x];
}

inline void pb_rgba_set_pixel(pb_rgba *pb, const DPCOORD x, const DPCOORD y, const DPPIXELVAL value)
{
	((uint32_t *)(pb)->data)[(y*(pb)->pixelpitch) + x] = value;
}

#ifdef __cplusplus
extern "C" {
#endif

	void font_t_init(font_t *f, const uint8_t *data);

	void glyph_t_prepare(const font_t *font, const glyph_t *ginfo, struct glyph_rect* r, double x, double y, bool flip);
	void glyph_t_init(const font_t *f, glyph_t *ginfo, const unsigned int glyph);
	size_t font_t_glyph_width(const font_t *f, const unsigned int glyph);
	size_t font_t_str_width(const font_t *f, const char * str);
	//void font_str_box(const font_t *f, const char * str, int *x, int *y, int *swidth, int *sheight);

	void glyph_t_span(const font_t *f, glyph_t *g, unsigned i, cover_type *m_span);
	int scan_glyph(pb_rgba *pb, font_t *font, glyph_t *glyph, const int x, const int y, const uint32_t color);
	int scan_str(pb_rgba *pb, font_t *font, const int x, const int y, const char *chars, const uint32_t color);

#ifdef __cplusplus
}
#endif

// PBM Handling
#ifdef __cplusplus
extern "C" {
#endif

	DPROC_API int PPM_read_binary(const char *filename, pb_rgba *fb);			// will read P6
	DPROC_API int write_PPM_binary(const char *filename, pb_rgba *fb);	// write a P6 file
	DPROC_API int write_PPM_ascii(const char *filename, pb_rgba *fb);		// write a P3 file

#ifdef __cplusplus
}
#endif


text:
<?php
namespace Payum\Core\Bridge\Twig;

use Twig\Environment;
use Twig\Loader\ChainLoader;
use Twig\Loader\FilesystemLoader;

class TwigUtil
{
    /**
     * @var \SplObjectStorage
     */
    protected static $storage;

    /**
     * @param Environment $twig
     * @param string[] $paths
     */
    public static function registerPaths(Environment $twig, array $paths)
    {
        if (false == static::$storage) {
            static::$storage = new \SplObjectStorage();
        }

        $storage = static::$storage;

        /** @var FilesystemLoader $payumLoader */
        $payumLoader = $twig && isset($storage[$twig]) ? $storage[$twig] : new FilesystemLoader();
        foreach ($paths as $namespace => $path) {
            $payumLoader->addPath($path, $namespace);
        }

        if (false == isset($storage[$twig])) {
            $currentLoader = $twig->getLoader();
            if ($currentLoader instanceof ChainLoader) {
                $currentLoader->addLoader($payumLoader);
            } else {
                $twig->setLoader(new ChainLoader([$currentLoader, $payumLoader]));
            }

            $storage->attach($twig, $payumLoader);
        }
    }
}


text:
"""
test_WunderListManagement
----------------------------------

Tests for `WunderListManagement` module.
"""

import unittest

from WunderListManagement import WunderListManagement

class TestWunderlistmanagement(unittest.TestCase):

    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass

if __name__ == '__main__':
    unittest.main()


text:
.grid {
  padding: 0 30px;
}
/* clearfix */
.grid:after {
  content: '';
  display: block;
  clear: both;
}
/* ---- grid-item ---- */
.grid-sizer,
.grid-item-1 {
  width: 300px;
  height: 570px;
}
.grid-item-2 {
  width: 470px;
  height: 570px;
}
.grid-item-3 {
  width: 500px;
  height: 620px;
}
.grid-item-4 {
  width: 300px;
  height: 800px;
}
.grid-item-5 {
  width: 300px;
  height: 570px;
}
.grid-item {
  float: left;
  background: #e4e4e4;
  border: 1px solid #333;
  border-color: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
}
.grid-item .playerImage img {
  width: 300px;
}
.grid-item .headerText {
  font-family: 'Dosis', sans-serif;
  font-size: 32px;
}
.grid-item .playerImage,
.grid-item .headerText {
  text-align: center;
}
.grid-item .playerInformation {
  width: 100%;
  display: table;
}
.grid-item .playerInformation .left {
  float: left;
  margin-left: 5px;
}
.grid-item .playerInformation .right {
  float: right;
  margin-right: 5px;
}
.grid-item .playerInformation .left,
.grid-item .playerInformation .right {
  font-size: 14px;
}
.grid-item .playerInformation p {
  margin: 0;
  padding: 10px 0;
}
.grid-item .playerInformation:nth-child(odd) {
  background-color: #cccccc;
}
.grid-item tbody .heroCategoryHero {
  width: 71px;
}
.grid-item tbody .heroCategoryStatus {
  width: 140px;
}
.grid-item tbody .heroCategoryKillRatio {
  width: 89px;
}
.grid-item tbody .heroCategoryNetworth {
  width: 95px;
}
.grid-item tbody .heroCategoryTime {
  width: 75px;
}
.grid-item tbody tr .won {
  color: #44b863;
}
.grid-item tbody tr .lost {
  color: #d13232;
}
.grid-item tbody tr td {
  text-align: center;
  font-family: 'Fira Sans', sans-serif;
  font-weight: 600;
}
.grid-item tbody tr td img {
  width: 60px;
  display: block;
  float: left;
  margin-left: 5px;
}
.grid-item tbody tr td p {
  margin: 0;
  padding-top: 6px;
}
.grid-item tbody tr th,
.grid-item tbody tr td {
  height: 45px;
}
.grid-item tbody tr:nth-child(even) {
  background-color: #cccccc;
}
.grid-item tbody .latestMatchResult:hover {
  background-color: #f1f1f1;
  cursor: pointer;
}
.grid-item .headerText {
  margin-top: 12px;
}
.grid-item .listContent {
  height: 497px;
  padding: 0 10px;
  overflow: scroll;
}
.grid-item .listContent .list {
  margin-bottom: 40px;
  list-style: none;
}
.grid-item .listContent .list .listLink {
  text-decoration: none;
  color: #000;
}
.grid-item .listContent .list .listLink .listText {
  margin-bottom: 10px;
  font-weight: bold;
}
.grid-item .listContent .list .listLink .underListText {
  color: #8e8e8e;
  font-size: 12px;
}
.grid-item .listContent .list .listLink span {
  font-family: 'Fira Sans', sans-serif;
}
.grid-item .list:hover .listText {
  color: #c73737;
}
.grid-item .twitterContent {
  height: 570px;
  overflow: scroll;
}
.space {
  margin: 0 20px 20px 0;
}


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Nuve.Tokenizers;

namespace Nuve.Client.Benchmark
{
    internal class TokenizerBenchmark
    {
        private const string path = @"C:\Users\hrzafer\Dropbox\nuve\veri\tcNormalized.txt";

        public static void TestWithAMillionWords(ITokenizer tokenizer)
        {
            string text = File.ReadAllText(path, Encoding.UTF8);
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < 1000; i++)
            {
                tokenizer.Tokenize(text);
            }
            sw.Stop();
            Console.WriteLine("Time taken to tokenizer 85 MB text: {0}ms", sw.Elapsed.TotalMilliseconds);
            GC.Collect();
        }
    }
}


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_SSL_HTTPS_ONLY_MODE_UPGRADE_URL_LOADER_H_
#define CHROME_BROWSER_SSL_HTTPS_ONLY_MODE_UPGRADE_URL_LOADER_H_

#include "content/public/browser/url_loader_request_interceptor.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/url_request/redirect_info.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

using HandleRequest = base::OnceCallback<void(
    content::URLLoaderRequestInterceptor::RequestHandler handler)>;

// A URLLoader that serves an artificial redirect to the HTTPS version of an
// HTTP URL to upgrade requests to HTTPS.
class HttpsOnlyModeUpgradeURLLoader : public network::mojom::URLLoader {
 public:
  HttpsOnlyModeUpgradeURLLoader(
      const network::ResourceRequest& tentative_resource_request,
      HandleRequest callback);
  ~HttpsOnlyModeUpgradeURLLoader() override;

  HttpsOnlyModeUpgradeURLLoader(const HttpsOnlyModeUpgradeURLLoader&) = delete;
  HttpsOnlyModeUpgradeURLLoader& operator=(
      const HttpsOnlyModeUpgradeURLLoader&) = delete;

  void StartRedirectToHttps(int frame_tree_node_id);

  void StartRedirectToOriginalURL(const GURL& original_url);

 private:
  // network::mojom::URLLoader:
  void FollowRedirect(
      const std::vector<std::string>& removed_headers,
      const net::HttpRequestHeaders& modified_headers,
      const net::HttpRequestHeaders& modified_cors_exempt_headers,
      const absl::optional<GURL>& new_url) override;
  void SetPriority(net::RequestPriority priority,
                   int32_t intra_priority_value) override;
  void PauseReadingBodyFromNet() override;
  void ResumeReadingBodyFromNet() override;

  // Serves a redirect to the HTTPS version of the URL.
  void StartHandlingRedirectToModifiedRequest(
      const network::ResourceRequest& resource_request,
      mojo::PendingReceiver<network::mojom::URLLoader> receiver,
      mojo::PendingRemote<network::mojom::URLLoaderClient> client);

  // Helper method for setting up and serving `redirect_info` to `client`.
  void StartHandlingRedirect(
      const network::ResourceRequest& /* resource_request */,
      mojo::PendingReceiver<network::mojom::URLLoader> receiver,
      mojo::PendingRemote<network::mojom::URLLoaderClient> client);

  // Helper method to create redirect information to `redirect_url` and modify
  // `redirect_info_` and `modified_resource_request_`.
  void CreateRedirectInformation(const GURL& redirect_url);

  // Mojo error handling. Deletes `this`.
  void OnConnectionClosed();

  // A copy of the initial resource request that has been modified to fetch
  // the HTTPS page.
  network::ResourceRequest modified_resource_request_;

  // Stores the response details for the artificial redirect.
  network::mojom::URLResponseHeadPtr response_head_ =
      network::mojom::URLResponseHead::New();

  // Information about the redirect to the upgraded HTTPS URL.
  net::RedirectInfo redirect_info_;

  // Called upon success or failure to let content/ know whether this class
  // intends to intercept the request. Must be passed a handler if this class
  // intends to intercept the request.
  HandleRequest callback_;

  // Receiver for the URLLoader interface.
  mojo::Receiver<network::mojom::URLLoader> receiver_{this};

  // The owning client. Used for serving redirects.
  mojo::Remote<network::mojom::URLLoaderClient> client_;

  SEQUENCE_CHECKER(sequence_checker_);

  base::WeakPtrFactory<HttpsOnlyModeUpgradeURLLoader> weak_ptr_factory_{this};
};

#endif  // CHROME_BROWSER_SSL_HTTPS_ONLY_MODE_UPGRADE_URL_LOADER_H_