text:
package testlib

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"net"
	"sync"
	"testing"
	"time"

	"github.com/spf13/pflag"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"

	"vitess.io/vitess/go/vt/logutil"
	"vitess.io/vitess/go/vt/servenv"
	"vitess.io/vitess/go/vt/topo"
	"vitess.io/vitess/go/vt/vtctl/grpcvtctlserver"
	"vitess.io/vitess/go/vt/vtctl/vtctlclient"

	// we need to import the grpcvtctlclient library so the gRPC
	// vtctl client is registered and can be used.
	_ "vitess.io/vitess/go/vt/vtctl/grpcvtctlclient"
)

var servenvInitialized sync.Once

// VtctlPipe is a vtctl server based on a topo server, and a client that
// is connected to it via gRPC.
type VtctlPipe struct {
	listener net.Listener
	client   vtctlclient.VtctlClient
	t        *testing.T
}

// NewVtctlPipe creates a new VtctlPipe based on the given topo server.
func NewVtctlPipe(t *testing.T, ts *topo.Server) *VtctlPipe {
	// Register all vtctl commands
	servenvInitialized.Do(func() {
		// make sure we use the right protocol
		fs := pflag.NewFlagSet("", pflag.ContinueOnError)
		vtctlclient.RegisterFlags(fs)

		err := fs.Parse([]string{
			"--vtctl_client_protocol",
			"grpc",
		})
		require.NoError(t, err, "failed to set `--vtctl_client_protocol=%s`", "grpc")

		servenv.FireRunHooks()
	})

	// Listen on a random port
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("Cannot listen: %v", err)
	}

	// Create a gRPC server and listen on the port
	server := grpc.NewServer()
	grpcvtctlserver.StartServer(server, ts)
	go server.Serve(listener)

	// Create a VtctlClient gRPC client to talk to the fake server
	client, err := vtctlclient.New(listener.Addr().String())
	if err != nil {
		t.Fatalf("Cannot create client: %v", err)
	}

	return &VtctlPipe{
		listener: listener,
		client:   client,
		t:        t,
	}
}

// Close will stop listening and free up all resources.
func (vp *VtctlPipe) Close() {
	vp.client.Close()
	vp.listener.Close()
}

// Run executes the provided command remotely, logs the output in the
// test logs, and returns the command error.
func (vp *VtctlPipe) Run(args []string) error {
	return vp.run(args, func(line string) {
		vp.t.Log(line)
	})
}

// RunAndOutput is similar to Run, but returns the output as a multi-line string
// instead of logging it.
func (vp *VtctlPipe) RunAndOutput(args []string) (string, error) {
	var output bytes.Buffer
	err := vp.run(args, func(line string) {
		output.WriteString(line)
	})
	return output.String(), err
}

func (vp *VtctlPipe) run(args []string, outputFunc func(string)) error {
	actionTimeout := 30 * time.Second
	ctx := context.Background()

	stream, err := vp.client.ExecuteVtctlCommand(ctx, args, actionTimeout)
	if err != nil {
		return fmt.Errorf("VtctlPipe.Run() failed: %v", err)
	}
	for {
		le, err := stream.Recv()
		switch err {
		case nil:
			outputFunc(logutil.EventString(le))
		case io.EOF:
			return nil
		default:
			return err
		}
	}
}

// RunAndStreamOutput returns the output of the vtctl command as a channel.
// When the channcel is closed, the command did finish.
func (vp *VtctlPipe) RunAndStreamOutput(args []string) (logutil.EventStream, error) {
	actionTimeout := 30 * time.Second
	ctx := context.Background()

	return vp.client.ExecuteVtctlCommand(ctx, args, actionTimeout)
}


text:
#pragma once
#include <aws/elasticmapreduce/EMR_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/elasticmapreduce/model/ScriptBootstrapActionConfig.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace EMR
{
namespace Model
{
  /*

Configuration of a bootstrap action.

  */
  class AWS_EMR_API BootstrapActionConfig
  {
  public:
    BootstrapActionConfig();
    BootstrapActionConfig(const Aws::Utils::Json::JsonValue& jsonValue);
    BootstrapActionConfig& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /*

The name of the bootstrap action.

    */
    inline const Aws::String& GetName() const{ return m_name; }

    /*

The name of the bootstrap action.

    */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /*

The name of the bootstrap action.

    */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = value; }

    /*

The name of the bootstrap action.

    */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /*

The name of the bootstrap action.

    */
    inline BootstrapActionConfig& WithName(const Aws::String& value) { SetName(value); return *this;}

    /*

The name of the bootstrap action.

    */
    inline BootstrapActionConfig& WithName(Aws::String&& value) { SetName(value); return *this;}

    /*

The name of the bootstrap action.

    */
    inline BootstrapActionConfig& WithName(const char* value) { SetName(value); return *this;}

    /*

The script run by the bootstrap action.

    */
    inline const ScriptBootstrapActionConfig& GetScriptBootstrapAction() const{ return m_scriptBootstrapAction; }

    /*

The script run by the bootstrap action.

    */
    inline void SetScriptBootstrapAction(const ScriptBootstrapActionConfig& value) { m_scriptBootstrapActionHasBeenSet = true; m_scriptBootstrapAction = value; }

    /*

The script run by the bootstrap action.

    */
    inline void SetScriptBootstrapAction(ScriptBootstrapActionConfig&& value) { m_scriptBootstrapActionHasBeenSet = true; m_scriptBootstrapAction = value; }

    /*

The script run by the bootstrap action.

    */
    inline BootstrapActionConfig& WithScriptBootstrapAction(const ScriptBootstrapActionConfig& value) { SetScriptBootstrapAction(value); return *this;}

    /*

The script run by the bootstrap action.

    */
    inline BootstrapActionConfig& WithScriptBootstrapAction(ScriptBootstrapActionConfig&& value) { SetScriptBootstrapAction(value); return *this;}

  private:
    Aws::String m_name;
    bool m_nameHasBeenSet;
    ScriptBootstrapActionConfig m_scriptBootstrapAction;
    bool m_scriptBootstrapActionHasBeenSet;
  };

} // namespace Model
} // namespace EMR
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by Hooken on 15/8/6.
 */
var generators = require('yeoman-generator');

module.exports = generators.Base.extend({

    writing: function () {
        this.log('start writing');
        var done = this.async();
        this.log(this.sourceRoot());
        var files = this.expandFiles('**/*', {cwd: this.sourceRoot(), dot: true});
        this.log(files);
        files.forEach(function (file) {
            this.copy(file, file);
        }, this);
        done();

    },
    end: function () {
        this.log('end');
        this.installDependencies();
    }
});


text:
const { fixingNodes } = require('./es-beautifier-common.js');

const create = (context) => {
  const option = context.options[0] || {
    allowSingleLine: true,
    maxStatementsInSingleLine: 2,
    maxlenInSingleLine: 80,
  };
  const {
    allowSingleLine,
    maxStatementsInSingleLine: maxStatements,
    maxLenInSingleLine: maxLen,
  } = option;

  const sourceCode = context.getSourceCode();

  const enterSwitchStatement = (node) => {
    let prev = null;
    node.cases.forEach((curr) => {
      if (prev && prev.loc.end.line === curr.loc.start.line) {
        context.report({
          node,
          message: 'Switch case in a switch statement must be on a new line.',
          loc: curr.loc.start,
          fix: fixer => fixer.insertTextBefore(curr, '\n'),
        });
      }
      prev = curr;
    });
  };

  const enterSwitchCase = (node) => {
    if (allowSingleLine
      && node.loc.start.line === node.loc.end.line
      && (!maxStatements || node.consequent.length <= maxStatements)
      && (!maxLen || sourceCode.lines[node.loc.end.line - 1].length < maxLen)) {
      // we accept one line
      // but require a space
      if (node.consequent.length) {
        const punctuator = sourceCode.getTokenBefore(node.consequent[0]);
        if (punctuator.type === 'Punctuator' && punctuator.range[1] === node.consequent[0].range[0]) {
          context.report({
            node,
            message: 'Test in a switch case shoule follow a space.',
            loc: punctuator.loc.end,
            fix: fixer => fixer.insertTextAfter(punctuator, ' '),
          });
        }
      }
      return;
    }

    if (allowSingleLine) {
      let { parent } = node;
      while (parent && parent.loc.start.line === node.loc.start.line) {
        if (fixingNodes.has(parent)) {
          // we ignore this time as we are still in the process
          return;
        }
        ({ parent } = parent);
      }
    }

    let fixed = false;
    let prev = null;
    node.consequent.forEach((curr) => {
      if (prev && prev.loc.end.line === curr.loc.start.line) {
        context.report({
          node,
          message: 'Statement in a switch case must be on a new line.',
          loc: curr.loc.start,
          fix: fixer => fixer.insertTextBefore(curr, '\n'),
        });
        fixed = true;
      }
      prev = curr;
    });

    if (node.consequent.length) {
      const firstToken = sourceCode.getFirstToken(node);
      const firstChild = node.consequent[0];
      if (firstToken.loc.end.line === firstChild.loc.start.line) {
        context.report({
          node,
          message: 'Statement in a switch case must be on a new line.',
          loc: firstToken.loc.start,
          fix: fixer => fixer.insertTextBefore(firstChild, '\n'),
        });
        fixed = true;
      }
    }

    if (fixed) fixingNodes.add(node);
  };

  return {
    SwitchStatement: enterSwitchStatement,
    SwitchCase: enterSwitchCase,
  };
};

module.exports = {
  meta: {
    docs: {
      description: 'enforce multi-line switch cases in a switch statement',
      category: 'Stylistic Issues',
    },
    fixable: 'whitespace',
    schema: [{
      type: 'object',
      properties: {
        allowSingleLine: { type: 'boolean' },
        maxStatementsInSingleLine: { type: 'integer' },
        maxLenInSingleLine: { type: 'integer' },
      },
      additionalProperties: false,
    }],
  },
  create,
};


text:
package org.apache.poi.hsmf.datatypes;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.poi.hsmf.MAPIMessage;
import org.apache.poi.hsmf.datatypes.Types.MAPIType;
import org.apache.poi.poifs.filesystem.DirectoryNode;

/**
 * A Chunk that is just a placeholder in the MAPIMessage directory structure,
 * which contains children. This is most commonly used with nested MAPIMessages
 */
public class DirectoryChunk extends Chunk {
    private DirectoryNode dir;

    public DirectoryChunk(DirectoryNode dir, String namePrefix, int chunkId, MAPIType type) {
        super(namePrefix, chunkId, type);
        this.dir = dir;
    }

    /**
     * Returns the directory entry for this chunk. You can then use standard
     * POIFS methods to enumerate the entries in it.
     */
    public DirectoryNode getDirectory() {
        return dir;
    }

    /**
     * Treats the directory as an embeded MAPIMessage (it normally is one), and
     * returns a MAPIMessage object to process it with.
     */
    public MAPIMessage getAsEmbededMessage() throws IOException {
        return new MAPIMessage(dir);
    }

    @Override
    public void readValue(InputStream value) {
        // DirectoryChunks have 0 byte contents
    }

    @Override
    public void writeValue(OutputStream out) {
        // DirectoryChunks have 0 byte contents
    }
}


text:
package com.theah64.ets.api.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by theapache64 on 11/22/2015.
 */
public class Request {

    private final HttpServletRequest request;
    private final String[] requiredParams;
    private List<String> missingOrInvalidParams;

    public Request(HttpServletRequest request, String[] requiredParams) throws Exception {
        this.request = request;
        this.requiredParams = requiredParams;

        if (!hasAllParams()) {
            throw new Exception(getErrorReport());
        }
    }

    /**
     * True if all the requiredParam exist and !empty other wise false
     *
     * @return Boolean
     */
    public boolean hasAllParams() {
        return has(requiredParams);
    }

    private String getErrorReport() {

        if (missingOrInvalidParams != null && !missingOrInvalidParams.isEmpty()) {
            final StringBuilder errorReportBuilder = new StringBuilder("Missing or empty value for ");
            for (final String param : missingOrInvalidParams) {
                errorReportBuilder.append(param).append(",");
            }
            //Removing last comma and returns the error report.
            return errorReportBuilder.substring(0, errorReportBuilder.length() - 1);
        }

        return null;
    }

    public String getStringParameter(String key) {
        return this.request.getParameter(key);
    }

    public boolean getBooleanParameter(String key) {
        return Boolean.parseBoolean(getStringParameter(key));
    }

    public boolean has(final String... requiredParamKeys) {

        Map<String, String[]> paramMap = request.getParameterMap();

        if (this.missingOrInvalidParams != null && !this.missingOrInvalidParams.isEmpty()) {
            //Clears old history if exist.
            this.missingOrInvalidParams.clear();
        }

        for (final String reqParam : requiredParamKeys) {

            final String[] reqParamValue = paramMap.get(reqParam);

            if (reqParamValue == null || reqParamValue[0].trim().isEmpty()) {

                //Lazy init
                if (this.missingOrInvalidParams == null) {
                    this.missingOrInvalidParams = new ArrayList<>();
                }

                //Invalid or missing Adding bad param name to list
                this.missingOrInvalidParams.add(reqParam);
            }
        }

        return this.missingOrInvalidParams == null || missingOrInvalidParams.isEmpty();
    }

    /**
     * Used to check if the parameter not null and not empty
     */
    public boolean has(final String paramKey) {
        final String paramValue = this.request.getParameter(paramKey);
        return paramValue != null && !paramValue.trim().isEmpty();
    }

    public long getLongParameter(String key) {
        final String value = getStringParameter(key);
        return value != null ? Long.parseLong(value) : -1;
    }

    public static class RequestException extends Exception{
        public RequestException(String message) {
            super(message);
        }
    }
}


text:
package scala.compat.java8.converterImpl

import scala.compat.java8.collectionImpl._

trait AccumulatesFromStepper[@specialized(Double, Int, Long) A, Acc <: AccumulatorLike[A, Acc]] {
  def apply(stepper: Stepper[A]): Acc
}

final class CollectionCanAccumulate[A](private val underlying: TraversableOnce[A]) extends AnyVal {
  def accumulate: Accumulator[A] = {
    val a = new Accumulator[A]
    underlying.foreach(a += _)
    a
  }
}

final class AccumulateDoubleCollection(private val underlying: TraversableOnce[Double]) extends AnyVal {
  def accumulate: DoubleAccumulator = {
    val da = new DoubleAccumulator
    underlying.foreach(da += _)
    da
  }
}

final class AccumulateIntCollection(private val underlying: TraversableOnce[Int]) extends AnyVal {
  def accumulate: IntAccumulator = {
    val da = new IntAccumulator
    underlying.foreach(da += _)
    da
  }
}

final class AccumulateLongCollection(private val underlying: TraversableOnce[Long]) extends AnyVal {
  def accumulate: LongAccumulator = {
    val da = new LongAccumulator
    underlying.foreach(da += _)
    da
  }
}

final class AccumulateAnyArray[A](private val underlying: Array[A]) extends AnyVal {
  def accumulate: Accumulator[A] = {
    val a = new Accumulator[A]
    var i = 0
    while (i < underlying.length) { a += underlying(i); i += 1 }
    a
  }
}

final class AccumulateDoubleArray(private val underlying: Array[Double]) extends AnyVal {
  def accumulate: DoubleAccumulator = {
    val da = new DoubleAccumulator
    var i = 0
    while (i < underlying.length) { da += underlying(i); i += 1 }
    da
  }
}

final class AccumulateIntArray(private val underlying: Array[Int]) extends AnyVal {
  def accumulate: IntAccumulator = {
    val da = new IntAccumulator
    var i = 0
    while (i < underlying.length) { da += underlying(i); i += 1 }
    da
  }
}

final class AccumulateLongArray(private val underlying: Array[Long]) extends AnyVal {
  def accumulate: LongAccumulator = {
    val da = new LongAccumulator
    var i = 0
    while (i < underlying.length) { da += underlying(i); i += 1 }
    da
  }
}


text:
#include <ph.h>
#include <kphuser.h>
#include <kphuserp.h>

HANDLE PhKphHandle = NULL;
BOOLEAN PhKphVerified = FALSE;
KPH_KEY PhKphL1Key = 0;

NTSTATUS KphConnect(
    _In_opt_ PWSTR DeviceName
    )
{
    NTSTATUS status;
    HANDLE kphHandle;
    UNICODE_STRING objectName;
    OBJECT_ATTRIBUTES objectAttributes;
    IO_STATUS_BLOCK isb;
    OBJECT_HANDLE_FLAG_INFORMATION handleFlagInfo;

    if (PhKphHandle)
        return STATUS_ADDRESS_ALREADY_EXISTS;

    if (DeviceName)
        RtlInitUnicodeString(&objectName, DeviceName);
    else
        RtlInitUnicodeString(&objectName, KPH_DEVICE_NAME);

    InitializeObjectAttributes(
        &objectAttributes,
        &objectName,
        OBJ_CASE_INSENSITIVE,
        NULL,
        NULL
        );

    status = NtOpenFile(
        &kphHandle,
        FILE_GENERIC_READ | FILE_GENERIC_WRITE,
        &objectAttributes,
        &isb,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        FILE_NON_DIRECTORY_FILE
        );

    if (NT_SUCCESS(status))
    {
        // Protect the handle from being closed.

        handleFlagInfo.Inherit = FALSE;
        handleFlagInfo.ProtectFromClose = TRUE;

        NtSetInformationObject(
            kphHandle,
            ObjectHandleFlagInformation,
            &handleFlagInfo,
            sizeof(OBJECT_HANDLE_FLAG_INFORMATION)
            );

        PhKphHandle = kphHandle;
        PhKphVerified = FALSE;
        PhKphL1Key = 0;
    }

    return status;
}

NTSTATUS KphConnect2(
    _In_opt_ PWSTR DeviceName,
    _In_ PWSTR FileName
    )
{
    return KphConnect2Ex(DeviceName, FileName, NULL);
}

NTSTATUS KphConnect2Ex(
    _In_opt_ PWSTR DeviceName,
    _In_ PWSTR FileName,
    _In_opt_ PKPH_PARAMETERS Parameters
    )
{
    NTSTATUS status;
    WCHAR fullDeviceName[256];
    PH_FORMAT format[2];
    SC_HANDLE scmHandle;
    SC_HANDLE serviceHandle;
    BOOLEAN started = FALSE;
    BOOLEAN created = FALSE;

    if (!DeviceName)
        DeviceName = KPH_DEVICE_SHORT_NAME;

    PhInitFormatS(&format[0], L"\\Device\\");
    PhInitFormatS(&format[1], DeviceName);

    if (!PhFormatToBuffer(format, 2, fullDeviceName, sizeof(fullDeviceName), NULL))
        return STATUS_NAME_TOO_LONG;

    // Try to open the device.
    status = KphConnect(fullDeviceName);

    if (NT_SUCCESS(status) || status == STATUS_ADDRESS_ALREADY_EXISTS)
        return status;

    if (
        status != STATUS_NO_SUCH_DEVICE &&
        status != STATUS_NO_SUCH_FILE &&
        status != STATUS_OBJECT_NAME_NOT_FOUND &&
        status != STATUS_OBJECT_PATH_NOT_FOUND
        )
        return status;

    // Load the driver, and try again.

    // Try to start the service, if it exists.

    scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);

    if (scmHandle)
    {
        serviceHandle = OpenService(scmHandle, DeviceName, SERVICE_START);

        if (serviceHandle)
        {
            if (StartService(serviceHandle, 0, NULL))
                started = TRUE;

            CloseServiceHandle(serviceHandle);
        }

        CloseServiceHandle(scmHandle);
    }

    if (!started && RtlDoesFileExists_U(FileName))
    {
        // Try to create the service.

        scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);

        if (scmHandle)
        {
            serviceHandle = CreateService(
                scmHandle,
                DeviceName,
                DeviceName,
                SERVICE_ALL_ACCESS,
                SERVICE_KERNEL_DRIVER,
                SERVICE_DEMAND_START,
                SERVICE_ERROR_IGNORE,
                FileName,
                NULL,
                NULL,
                NULL,
                NULL,
                L""
                );

            if (serviceHandle)
            {
                created = TRUE;

                KphSetServiceSecurity(serviceHandle);

                // Set parameters if the caller supplied them. Note that we fail the entire function
                // if this fails, because failing to set parameters like SecurityLevel may result in
                // security vulnerabilities.
                if (Parameters)
                {
                    status = KphSetParameters(DeviceName, Parameters);

                    if (!NT_SUCCESS(status))
                    {
                        // Delete the service and fail.
                        goto CreateAndConnectEnd;
                    }
                }

                if (StartService(serviceHandle, 0, NULL))
                    started = TRUE;
                else
                    status = PhGetLastWin32ErrorAsNtStatus();
            }
            else
            {
                status = PhGetLastWin32ErrorAsNtStatus();
            }

            CloseServiceHandle(scmHandle);
        }
    }

    if (started)
    {
        // Try to open the device again.
        status = KphConnect(fullDeviceName);
    }

CreateAndConnectEnd:
    if (created && serviceHandle)
    {
        // "Delete" the service. Since we (may) have a handle to the device, the SCM will delete the
        // service automatically when it is stopped (upon reboot). If we don't have a handle to the
        // device, the service will get deleted immediately, which is a good thing anyway.
        DeleteService(serviceHandle);
        CloseServiceHandle(serviceHandle);
    }

    return status;
}

NTSTATUS KphDisconnect(
    VOID
    )
{
    NTSTATUS status;
    OBJECT_HANDLE_FLAG_INFORMATION handleFlagInfo;

    if (!PhKphHandle)
        return STATUS_ALREADY_DISCONNECTED;

    // Unprotect the handle.

    handleFlagInfo.Inherit = FALSE;
    handleFlagInfo.ProtectFromClose = FALSE;

    NtSetInformationObject(
        PhKphHandle,
        ObjectHandleFlagInformation,
        &handleFlagInfo,
        sizeof(OBJECT_HANDLE_FLAG_INFORMATION)
        );

    status = NtClose(PhKphHandle);
    PhKphHandle = NULL;
    PhKphVerified = FALSE;
    PhKphL1Key = 0;

    return status;
}

BOOLEAN KphIsConnected(
    VOID
    )
{
    return PhKphHandle != NULL;
}

BOOLEAN KphIsVerified(
    VOID
    )
{
    return PhKphVerified;
}

NTSTATUS KphSetParameters(
    _In_opt_ PWSTR DeviceName,
    _In_ PKPH_PARAMETERS Parameters
    )
{
    NTSTATUS status;
    HANDLE parametersKeyHandle = NULL;
    PPH_STRING parametersKeyName;
    ULONG disposition;
    UNICODE_STRING valueName;

    if (!DeviceName)
        DeviceName = KPH_DEVICE_SHORT_NAME;

    parametersKeyName = PhConcatStrings(
        3,
        L"System\\CurrentControlSet\\Services\\",
        DeviceName,
        L"\\Parameters"
        );
    status = PhCreateKey(
        &parametersKeyHandle,
        KEY_WRITE | DELETE,
        PH_KEY_LOCAL_MACHINE,
        &parametersKeyName->sr,
        0,
        0,
        &disposition
        );
    PhDereferenceObject(parametersKeyName);

    if (!NT_SUCCESS(status))
        return status;

    RtlInitUnicodeString(&valueName, L"SecurityLevel");
    status = NtSetValueKey(parametersKeyHandle, &valueName, 0, REG_DWORD, &Parameters->SecurityLevel, sizeof(ULONG));

    if (!NT_SUCCESS(status))
        goto SetValuesEnd;

    if (Parameters->CreateDynamicConfiguration)
    {
        KPH_DYN_CONFIGURATION configuration;

        RtlInitUnicodeString(&valueName, L"DynamicConfiguration");

        configuration.Version = KPH_DYN_CONFIGURATION_VERSION;
        configuration.NumberOfPackages = 1;

        if (NT_SUCCESS(KphInitializeDynamicPackage(&configuration.Packages[0])))
        {
            status = NtSetValueKey(parametersKeyHandle, &valueName, 0, REG_BINARY, &configuration, sizeof(KPH_DYN_CONFIGURATION));

            if (!NT_SUCCESS(status))
                goto SetValuesEnd;
        }
    }

    // Put more parameters here...

SetValuesEnd:
    if (!NT_SUCCESS(status))
    {
        // Delete the key if we created it.
        if (disposition == REG_CREATED_NEW_KEY)
            NtDeleteKey(parametersKeyHandle);
    }

    NtClose(parametersKeyHandle);

    return status;
}

VOID KphSetServiceSecurity(
    _In_ SC_HANDLE ServiceHandle
    )
{
    static SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
    PSECURITY_DESCRIPTOR securityDescriptor;
    ULONG sdAllocationLength;
    UCHAR administratorsSidBuffer[FIELD_OFFSET(SID, SubAuthority) + sizeof(ULONG) * 2];
    PSID administratorsSid;
    PACL dacl;

    administratorsSid = (PSID)administratorsSidBuffer;
    RtlInitializeSid(administratorsSid, &ntAuthority, 2);
    *RtlSubAuthoritySid(administratorsSid, 0) = SECURITY_BUILTIN_DOMAIN_RID;
    *RtlSubAuthoritySid(administratorsSid, 1) = DOMAIN_ALIAS_RID_ADMINS;

    sdAllocationLength = SECURITY_DESCRIPTOR_MIN_LENGTH +
        (ULONG)sizeof(ACL) +
        (ULONG)sizeof(ACCESS_ALLOWED_ACE) +
        RtlLengthSid(&PhSeServiceSid) +
        (ULONG)sizeof(ACCESS_ALLOWED_ACE) +
        RtlLengthSid(administratorsSid) +
        (ULONG)sizeof(ACCESS_ALLOWED_ACE) +
        RtlLengthSid(&PhSeInteractiveSid);

    securityDescriptor = PhAllocate(sdAllocationLength);
    dacl = (PACL)PTR_ADD_OFFSET(securityDescriptor, SECURITY_DESCRIPTOR_MIN_LENGTH);

    RtlCreateSecurityDescriptor(securityDescriptor, SECURITY_DESCRIPTOR_REVISION);
    RtlCreateAcl(dacl, sdAllocationLength - SECURITY_DESCRIPTOR_MIN_LENGTH, ACL_REVISION);
    RtlAddAccessAllowedAce(dacl, ACL_REVISION, SERVICE_ALL_ACCESS, &PhSeServiceSid);
    RtlAddAccessAllowedAce(dacl, ACL_REVISION, SERVICE_ALL_ACCESS, administratorsSid);
    RtlAddAccessAllowedAce(dacl, ACL_REVISION,
        SERVICE_QUERY_CONFIG |
        SERVICE_QUERY_STATUS |
        SERVICE_START |
        SERVICE_STOP |
        SERVICE_INTERROGATE |
        DELETE,
        &PhSeInteractiveSid
        );
    RtlSetDaclSecurityDescriptor(securityDescriptor, TRUE, dacl, FALSE);

    SetServiceObjectSecurity(ServiceHandle, DACL_SECURITY_INFORMATION, securityDescriptor);

    PhFree(securityDescriptor);
}

NTSTATUS KphInstall(
    _In_opt_ PWSTR DeviceName,
    _In_ PWSTR FileName
    )
{
    return KphInstallEx(DeviceName, FileName, NULL);
}

NTSTATUS KphInstallEx(
    _In_opt_ PWSTR DeviceName,
    _In_ PWSTR FileName,
    _In_opt_ PKPH_PARAMETERS Parameters
    )
{
    NTSTATUS status = STATUS_SUCCESS;
    SC_HANDLE scmHandle;
    SC_HANDLE serviceHandle;

    if (!DeviceName)
        DeviceName = KPH_DEVICE_SHORT_NAME;

    scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);

    if (!scmHandle)
        return PhGetLastWin32ErrorAsNtStatus();

    serviceHandle = CreateService(
        scmHandle,
        DeviceName,
        DeviceName,
        SERVICE_ALL_ACCESS,
        SERVICE_KERNEL_DRIVER,
        SERVICE_SYSTEM_START,
        SERVICE_ERROR_IGNORE,
        FileName,
        NULL,
        NULL,
        NULL,
        NULL,
        L""
        );

    if (serviceHandle)
    {
        KphSetServiceSecurity(serviceHandle);

        // See KphConnect2Ex for more details.
        if (Parameters)
        {
            status = KphSetParameters(DeviceName, Parameters);

            if (!NT_SUCCESS(status))
            {
                DeleteService(serviceHandle);
                goto CreateEnd;
            }
        }

        if (!StartService(serviceHandle, 0, NULL))
            status = PhGetLastWin32ErrorAsNtStatus();

CreateEnd:
        CloseServiceHandle(serviceHandle);
    }
    else
    {
        status = PhGetLastWin32ErrorAsNtStatus();
    }

    CloseServiceHandle(scmHandle);

    return status;
}

NTSTATUS KphUninstall(
    _In_opt_ PWSTR DeviceName
    )
{
    NTSTATUS status = STATUS_SUCCESS;
    SC_HANDLE scmHandle;
    SC_HANDLE serviceHandle;

    if (!DeviceName)
        DeviceName = KPH_DEVICE_SHORT_NAME;

    scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);

    if (!scmHandle)
        return PhGetLastWin32ErrorAsNtStatus();

    serviceHandle = OpenService(scmHandle, DeviceName, SERVICE_STOP | DELETE);

    if (serviceHandle)
    {
        SERVICE_STATUS serviceStatus;

        ControlService(serviceHandle, SERVICE_CONTROL_STOP, &serviceStatus);

        if (!DeleteService(serviceHandle))
            status = PhGetLastWin32ErrorAsNtStatus();

        CloseServiceHandle(serviceHandle);
    }
    else
    {
        status = PhGetLastWin32ErrorAsNtStatus();
    }

    CloseServiceHandle(scmHandle);

    return status;
}

NTSTATUS KphGetFeatures(
    _Out_ PULONG Features
    )
{
    struct
    {
        PULONG Features;
    } input = { Features };

    return KphpDeviceIoControl(
        KPH_GETFEATURES,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphVerifyClient(
    _In_reads_bytes_(SignatureSize) PUCHAR Signature,
    _In_ ULONG SignatureSize
    )
{
    NTSTATUS status;
    struct
    {
        PVOID CodeAddress;
        PUCHAR Signature;
        ULONG SignatureSize;
    } input = { KphpWithKeyApcRoutine, Signature, SignatureSize };

    status = KphpDeviceIoControl(
        KPH_VERIFYCLIENT,
        &input,
        sizeof(input)
        );

    if (NT_SUCCESS(status))
        PhKphVerified = TRUE;

    return status;
}

NTSTATUS KphOpenProcess(
    _Out_ PHANDLE ProcessHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _In_ PCLIENT_ID ClientId
    )
{
    KPH_OPEN_PROCESS_INPUT input = { ProcessHandle, DesiredAccess, ClientId, 0 };

    if ((DesiredAccess & KPH_PROCESS_READ_ACCESS) == DesiredAccess)
    {
        KphpGetL1Key(&input.Key);
        return KphpDeviceIoControl(
            KPH_OPENPROCESS,
            &input,
            sizeof(input)
            );
    }
    else
    {
        return KphpWithKey(KphKeyLevel2, KphpOpenProcessContinuation, &input);
    }
}

NTSTATUS KphOpenProcessToken(
    _In_ HANDLE ProcessHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _Out_ PHANDLE TokenHandle
    )
{
    KPH_OPEN_PROCESS_TOKEN_INPUT input = { ProcessHandle, DesiredAccess, TokenHandle, 0 };

    if ((DesiredAccess & KPH_TOKEN_READ_ACCESS) == DesiredAccess)
    {
        KphpGetL1Key(&input.Key);
        return KphpDeviceIoControl(
            KPH_OPENPROCESSTOKEN,
            &input,
            sizeof(input)
            );
    }
    else
    {
        return KphpWithKey(KphKeyLevel2, KphpOpenProcessTokenContinuation, &input);
    }
}

NTSTATUS KphOpenProcessJob(
    _In_ HANDLE ProcessHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _Out_ PHANDLE JobHandle
    )
{
    struct
    {
        HANDLE ProcessHandle;
        ACCESS_MASK DesiredAccess;
        PHANDLE JobHandle;
    } input = { ProcessHandle, DesiredAccess, JobHandle };

    return KphpDeviceIoControl(
        KPH_OPENPROCESSJOB,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphTerminateProcess(
    _In_ HANDLE ProcessHandle,
    _In_ NTSTATUS ExitStatus
    )
{
    NTSTATUS status;
    KPH_TERMINATE_PROCESS_INPUT input = { ProcessHandle, ExitStatus, 0 };

    status = KphpWithKey(KphKeyLevel2, KphpTerminateProcessContinuation, &input);

    // Check if we're trying to terminate the current process, because kernel-mode can't do it.
    if (status == STATUS_CANT_TERMINATE_SELF)
    {
        RtlExitUserProcess(ExitStatus);
    }

    return status;
}

NTSTATUS KphReadVirtualMemoryUnsafe(
    _In_opt_ HANDLE ProcessHandle,
    _In_ PVOID BaseAddress,
    _Out_writes_bytes_(BufferSize) PVOID Buffer,
    _In_ SIZE_T BufferSize,
    _Out_opt_ PSIZE_T NumberOfBytesRead
    )
{
    KPH_READ_VIRTUAL_MEMORY_UNSAFE_INPUT input = { ProcessHandle, BaseAddress, Buffer, BufferSize, NumberOfBytesRead, 0 };

    return KphpWithKey(KphKeyLevel2, KphpReadVirtualMemoryUnsafeContinuation, &input);
}

NTSTATUS KphQueryInformationProcess(
    _In_ HANDLE ProcessHandle,
    _In_ KPH_PROCESS_INFORMATION_CLASS ProcessInformationClass,
    _Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,
    _In_ ULONG ProcessInformationLength,
    _Out_opt_ PULONG ReturnLength
    )
{
    struct
    {
        HANDLE ProcessHandle;
        KPH_PROCESS_INFORMATION_CLASS ProcessInformationClass;
        PVOID ProcessInformation;
        ULONG ProcessInformationLength;
        PULONG ReturnLength;
    } input = { ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength, ReturnLength };

    return KphpDeviceIoControl(
        KPH_QUERYINFORMATIONPROCESS,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphSetInformationProcess(
    _In_ HANDLE ProcessHandle,
    _In_ KPH_PROCESS_INFORMATION_CLASS ProcessInformationClass,
    _In_reads_bytes_(ProcessInformationLength) PVOID ProcessInformation,
    _In_ ULONG ProcessInformationLength
    )
{
    struct
    {
        HANDLE ProcessHandle;
        KPH_PROCESS_INFORMATION_CLASS ProcessInformationClass;
        PVOID ProcessInformation;
        ULONG ProcessInformationLength;
    } input = { ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength };

    return KphpDeviceIoControl(
        KPH_SETINFORMATIONPROCESS,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphOpenThread(
    _Out_ PHANDLE ThreadHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _In_ PCLIENT_ID ClientId
    )
{
    KPH_OPEN_THREAD_INPUT input = { ThreadHandle, DesiredAccess, ClientId, 0 };

    if ((DesiredAccess & KPH_THREAD_READ_ACCESS) == DesiredAccess)
    {
        KphpGetL1Key(&input.Key);
        return KphpDeviceIoControl(
            KPH_OPENTHREAD,
            &input,
            sizeof(input)
            );
    }
    else
    {
        return KphpWithKey(KphKeyLevel2, KphpOpenThreadContinuation, &input);
    }
}

NTSTATUS KphOpenThreadProcess(
    _In_ HANDLE ThreadHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _Out_ PHANDLE ProcessHandle
    )
{
    struct
    {
        HANDLE ThreadHandle;
        ACCESS_MASK DesiredAccess;
        PHANDLE ProcessHandle;
    } input = { ThreadHandle, DesiredAccess, ProcessHandle };

    return KphpDeviceIoControl(
        KPH_OPENTHREADPROCESS,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphCaptureStackBackTraceThread(
    _In_ HANDLE ThreadHandle,
    _In_ ULONG FramesToSkip,
    _In_ ULONG FramesToCapture,
    _Out_writes_(FramesToCapture) PVOID *BackTrace,
    _Out_opt_ PULONG CapturedFrames,
    _Out_opt_ PULONG BackTraceHash
    )
{
    struct
    {
        HANDLE ThreadHandle;
        ULONG FramesToSkip;
        ULONG FramesToCapture;
        PVOID *BackTrace;
        PULONG CapturedFrames;
        PULONG BackTraceHash;
    } input = { ThreadHandle, FramesToSkip, FramesToCapture, BackTrace, CapturedFrames, BackTraceHash };

    return KphpDeviceIoControl(
        KPH_CAPTURESTACKBACKTRACETHREAD,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphQueryInformationThread(
    _In_ HANDLE ThreadHandle,
    _In_ KPH_THREAD_INFORMATION_CLASS ThreadInformationClass,
    _Out_writes_bytes_(ThreadInformationLength) PVOID ThreadInformation,
    _In_ ULONG ThreadInformationLength,
    _Out_opt_ PULONG ReturnLength
    )
{
    struct
    {
        HANDLE ThreadHandle;
        KPH_THREAD_INFORMATION_CLASS ThreadInformationClass;
        PVOID ThreadInformation;
        ULONG ThreadInformationLength;
        PULONG ReturnLength;
    } input = { ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength, ReturnLength };

    return KphpDeviceIoControl(
        KPH_QUERYINFORMATIONTHREAD,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphSetInformationThread(
    _In_ HANDLE ThreadHandle,
    _In_ KPH_THREAD_INFORMATION_CLASS ThreadInformationClass,
    _In_reads_bytes_(ThreadInformationLength) PVOID ThreadInformation,
    _In_ ULONG ThreadInformationLength
    )
{
    struct
    {
        HANDLE ThreadHandle;
        KPH_THREAD_INFORMATION_CLASS ThreadInformationClass;
        PVOID ThreadInformation;
        ULONG ThreadInformationLength;
    } input = { ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength };

    return KphpDeviceIoControl(
        KPH_SETINFORMATIONTHREAD,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphEnumerateProcessHandles(
    _In_ HANDLE ProcessHandle,
    _Out_writes_bytes_(BufferLength) PVOID Buffer,
    _In_opt_ ULONG BufferLength,
    _Out_opt_ PULONG ReturnLength
    )
{
    struct
    {
        HANDLE ProcessHandle;
        PVOID Buffer;
        ULONG BufferLength;
        PULONG ReturnLength;
    } input = { ProcessHandle, Buffer, BufferLength, ReturnLength };

    return KphpDeviceIoControl(
        KPH_ENUMERATEPROCESSHANDLES,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphEnumerateProcessHandles2(
    _In_ HANDLE ProcessHandle,
    _Out_ PKPH_PROCESS_HANDLE_INFORMATION *Handles
    )
{
    NTSTATUS status;
    PVOID buffer;
    ULONG bufferSize = 2048;

    buffer = PhAllocate(bufferSize);

    while (TRUE)
    {
        status = KphEnumerateProcessHandles(
            ProcessHandle,
            buffer,
            bufferSize,
            &bufferSize
            );

        if (status == STATUS_BUFFER_TOO_SMALL)
        {
            PhFree(buffer);
            buffer = PhAllocate(bufferSize);
        }
        else
        {
            break;
        }
    }

    if (!NT_SUCCESS(status))
    {
        PhFree(buffer);
        return status;
    }

    *Handles = buffer;

    return status;
}

NTSTATUS KphQueryInformationObject(
    _In_ HANDLE ProcessHandle,
    _In_ HANDLE Handle,
    _In_ KPH_OBJECT_INFORMATION_CLASS ObjectInformationClass,
    _Out_writes_bytes_(ObjectInformationLength) PVOID ObjectInformation,
    _In_ ULONG ObjectInformationLength,
    _Out_opt_ PULONG ReturnLength
    )
{
    struct
    {
        HANDLE ProcessHandle;
        HANDLE Handle;
        KPH_OBJECT_INFORMATION_CLASS ObjectInformationClass;
        PVOID ObjectInformation;
        ULONG ObjectInformationLength;
        PULONG ReturnLength;
    } input = { ProcessHandle, Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength, ReturnLength };

    return KphpDeviceIoControl(
        KPH_QUERYINFORMATIONOBJECT,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphSetInformationObject(
    _In_ HANDLE ProcessHandle,
    _In_ HANDLE Handle,
    _In_ KPH_OBJECT_INFORMATION_CLASS ObjectInformationClass,
    _In_reads_bytes_(ObjectInformationLength) PVOID ObjectInformation,
    _In_ ULONG ObjectInformationLength
    )
{
    struct
    {
        HANDLE ProcessHandle;
        HANDLE Handle;
        KPH_OBJECT_INFORMATION_CLASS ObjectInformationClass;
        PVOID ObjectInformation;
        ULONG ObjectInformationLength;
    } input = { ProcessHandle, Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength };

    return KphpDeviceIoControl(
        KPH_SETINFORMATIONOBJECT,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphOpenDriver(
    _Out_ PHANDLE DriverHandle,
    _In_ ACCESS_MASK DesiredAccess,
    _In_ POBJECT_ATTRIBUTES ObjectAttributes
    )
{
    struct
    {
        PHANDLE DriverHandle;
        ACCESS_MASK DesiredAccess;
        POBJECT_ATTRIBUTES ObjectAttributes;
    } input = { DriverHandle, DesiredAccess, ObjectAttributes };

    return KphpDeviceIoControl(
        KPH_OPENDRIVER,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphQueryInformationDriver(
    _In_ HANDLE DriverHandle,
    _In_ DRIVER_INFORMATION_CLASS DriverInformationClass,
    _Out_writes_bytes_(DriverInformationLength) PVOID DriverInformation,
    _In_ ULONG DriverInformationLength,
    _Out_opt_ PULONG ReturnLength
    )
{
    struct
    {
        HANDLE DriverHandle;
        DRIVER_INFORMATION_CLASS DriverInformationClass;
        PVOID DriverInformation;
        ULONG DriverInformationLength;
        PULONG ReturnLength;
    } input = { DriverHandle, DriverInformationClass, DriverInformation, DriverInformationLength, ReturnLength };

    return KphpDeviceIoControl(
        KPH_QUERYINFORMATIONDRIVER,
        &input,
        sizeof(input)
        );
}

NTSTATUS KphpDeviceIoControl(
    _In_ ULONG KphControlCode,
    _In_ PVOID InBuffer,
    _In_ ULONG InBufferLength
    )
{
    IO_STATUS_BLOCK iosb;

    return NtDeviceIoControlFile(
        PhKphHandle,
        NULL,
        NULL,
        NULL,
        &iosb,
        KphControlCode,
        InBuffer,
        InBufferLength,
        NULL,
        0
        );
}

VOID KphpWithKeyApcRoutine(
    _In_ PVOID ApcContext,
    _In_ PIO_STATUS_BLOCK IoStatusBlock,
    _In_ ULONG Reserved
    )
{
    PKPHP_RETRIEVE_KEY_CONTEXT context = CONTAINING_RECORD(IoStatusBlock, KPHP_RETRIEVE_KEY_CONTEXT, Iosb);
    KPH_KEY key = PtrToUlong(ApcContext);

    if (context->Continuation != KphpGetL1KeyContinuation &&
        context->Continuation != KphpOpenProcessContinuation &&
        context->Continuation != KphpOpenProcessTokenContinuation &&
        context->Continuation != KphpTerminateProcessContinuation &&
        context->Continuation != KphpReadVirtualMemoryUnsafeContinuation &&
        context->Continuation != KphpOpenThreadContinuation)
    {
        PhRaiseStatus(STATUS_ACCESS_DENIED);
        context->Status = STATUS_ACCESS_DENIED;
        return;
    }

    context->Status = context->Continuation(key, context->Context);
}

NTSTATUS KphpWithKey(
    _In_ KPH_KEY_LEVEL KeyLevel,
    _In_ PKPHP_WITH_KEY_CONTINUATION Continuation,
    _In_ PVOID Context
    )
{
    NTSTATUS status;
    struct
    {
        KPH_KEY_LEVEL KeyLevel;
    } input = { KeyLevel };
    KPHP_RETRIEVE_KEY_CONTEXT context;

    context.Continuation = Continuation;
    context.Context = Context;
    context.Status = STATUS_UNSUCCESSFUL;

    status = NtDeviceIoControlFile(
        PhKphHandle,
        NULL,
        KphpWithKeyApcRoutine,
        NULL,
        &context.Iosb,
        KPH_RETRIEVEKEY,
        &input,
        sizeof(input),
        NULL,
        0
        );

    NtTestAlert();

    if (!NT_SUCCESS(status))
        return status;

    return context.Status;
}

NTSTATUS KphpGetL1KeyContinuation(
    _In_ KPH_KEY Key,
    _In_ PVOID Context
    )
{
    PKPHP_GET_L1_KEY_CONTEXT context = Context;

    *context->Key = Key;
    PhKphL1Key = Key;

    return STATUS_SUCCESS;
}

NTSTATUS KphpGetL1Key(
    _Out_ PKPH_KEY Key
    )
{
    KPHP_GET_L1_KEY_CONTEXT context;

    if (PhKphL1Key)
    {
        *Key = PhKphL1Key;
        return STATUS_SUCCESS;
    }

    context.Key = Key;

    return KphpWithKey(KphKeyLevel1, KphpGetL1KeyContinuation, &context);
}

NTSTATUS KphpOpenProcessContinuation(
    _In_ KPH_KEY Key,
    _In_ PVOID Context
    )
{
    PKPH_OPEN_PROCESS_INPUT input = Context;

    input->Key = Key;

    return KphpDeviceIoControl(
        KPH_OPENPROCESS,
        input,
        sizeof(*input)
        );
}

NTSTATUS KphpOpenProcessTokenContinuation(
    _In_ KPH_KEY Key,
    _In_ PVOID Context
    )
{
    PKPH_OPEN_PROCESS_TOKEN_INPUT input = Context;

    input->Key = Key;

    return KphpDeviceIoControl(
        KPH_OPENPROCESSTOKEN,
        input,
        sizeof(*input)
        );
}

NTSTATUS KphpTerminateProcessContinuation(
    _In_ KPH_KEY Key,
    _In_ PVOID Context
    )
{
    PKPH_TERMINATE_PROCESS_INPUT input = Context;

    input->Key = Key;

    return KphpDeviceIoControl(
        KPH_TERMINATEPROCESS,
        input,
        sizeof(*input)
        );
}

NTSTATUS KphpReadVirtualMemoryUnsafeContinuation(
    _In_ KPH_KEY Key,
    _In_ PVOID Context
    )
{
    PKPH_READ_VIRTUAL_MEMORY_UNSAFE_INPUT input = Context;

    input->Key = Key;

    return KphpDeviceIoControl(
        KPH_READVIRTUALMEMORYUNSAFE,
        input,
        sizeof(*input)
        );
}

NTSTATUS KphpOpenThreadContinuation(
    _In_ KPH_KEY Key,
    _In_ PVOID Context
    )
{
    PKPH_OPEN_PROCESS_INPUT input = Context;

    input->Key = Key;

    return KphpDeviceIoControl(
        KPH_OPENTHREAD,
        input,
        sizeof(*input)
        );
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import Icon from '../icon';
import Input from '../input';
import Button from '../button';
import { login } from '../../actions/user';
import "./style.scss";
import logoPath from "../../img/logo_big.png";

interface LoginPageProps {
    loggingIn: boolean;
    loginError: string;
    login: (username: string, redirect: string) => void;
    redirect?: string;
}

interface LoginPageState {
    username: string;
}

export class LoginPage extends React.Component<LoginPageProps, LoginPageState> {
    constructor(props) {
        super(props);
        this.state = {
            username: ''
        };
    }

    onChangeUsername = (username: string) => {
        this.setState({ username });
    };

    login = () => {
        if (!this.props.loggingIn) {
            this.props.login(this.state.username, this.props.redirect || '');
        }
    };

    render() {
        return (

                <form className="login-form" onSubmit={this.login}>

                    <fieldset>
                        {this.props.loginError ?
                            {this.props.loginError} :
                            null
                        }
                        <Input name="username"
                               value={this.state.username}
                               onChange={this.onChangeUsername}
                               placeholder="Enter user name" />
                        <Button onClick={this.login}>
                            {this.props.loggingIn ?
                                <Icon name="loading" /> :
                                Login}
                        </Button>

Having issues? Check our bug tracker.

                    </fieldset>
                </form>

        );
    }
}

const mapStateToProps = (state, ownProps) => ({
    loggingIn: state.user.loggingIn,
    loginError: state.user.loginError,
    redirect: ownProps.location.query.redirect
});

const mapDispatchToProps = (dispatch) => ({
    login: (username: string, redirect: string) => {
        dispatch(login(username, redirect));
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);


text:
import React from 'react';

import SearchField from './SearchField';

export default {
  title: 'Admin/Form/SearchField',
  component: SearchField,
};

const Template = args => <SearchField {...args} />;

export const Basic = Template.bind({});

Basic.args = {};

export const WithLabel = Template.bind({});

WithLabel.args = {
  label: 'Search for something',
};

export const WithLabelAndDescription = Template.bind({});

WithLabelAndDescription.args = {
  callback: () => {},
  id: 'search',
  label: 'Search for something',
  description: 'Use this search input to help search for a campaign.',
  setQuery: () => {},
  query: 'searching something',
};


text:
var assert = require('assert');
var index = require('./../index');
var request = require('supertest');

describe('Example web app', function() {
  it('should square numbers', function(done) {
    request(index) //<co id="callout-testing-mocha-web-refactor-1" />
      .get('/square/4')
      .expect(200) //<co id="callout-testing-mocha-web-refactor-2" />
      .expect(/16/, done); //<co id="callout-testing-mocha-web-refactor-3" />
  });

  it('should return a 500 for invalid square requests', function(done) {
    request(index)
      .get('/square')
      .expect(500, done); //<co id="callout-testing-mocha-web-refactor-4" />
  });
});


text:
using System;

namespace ZXing.Common.ReedSolomon
{
    ///
    ///
This class contains utility methods for performing mathematical operations over
    /// the Galois Fields. Operations use a given primitive polynomial in calculations.

    ///
Throughout this package, elements of the GF are represented as an {@code int}
    /// for convenience and speed (but at the cost of memory).
    ///

    ///
    /// <author>Sean Owen</author>
    public sealed class GenericGF
    {
        public static GenericGF AZTEC_DATA_12 = new GenericGF(0x1069, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1
        public static GenericGF AZTEC_DATA_10 = new GenericGF(0x409, 1024, 1); // x^10 + x^3 + 1
        public static GenericGF AZTEC_DATA_6 = new GenericGF(0x43, 64, 1); // x^6 + x + 1
        public static GenericGF AZTEC_PARAM = new GenericGF(0x13, 16, 1); // x^4 + x + 1
        public static GenericGF QR_CODE_FIELD_256 = new GenericGF(0x011D, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1
        public static GenericGF DATA_MATRIX_FIELD_256 = new GenericGF(0x012D, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1
        public static GenericGF AZTEC_DATA_8 = DATA_MATRIX_FIELD_256;
        public static GenericGF MAXICODE_FIELD_64 = AZTEC_DATA_6;

        private int[] expTable;
        private int[] logTable;
        private GenericGFPoly zero;
        private GenericGFPoly one;
        private readonly int size;
        private readonly int primitive;
        private readonly int generatorBase;

        ///
        /// Create a representation of GF(size) using the given primitive polynomial.
        ///
        /// <param name="primitive">irreducible polynomial whose coefficients are represented by
        /// *  the bits of an int, where the least-significant bit represents the constant
        /// *  coefficient</param>
        /// <param name="size">the size of the field</param>
        /// <param name="genBase">the factor b in the generator polynomial can be 0- or 1-based
        /// *  (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))).
        /// *  In most cases it should be 1, but for QR code it is 0.</param>
        public GenericGF(int primitive, int size, int genBase)
        {
            this.primitive = primitive;
            this.size = size;
            this.generatorBase = genBase;

            expTable = new int[size];
            logTable = new int[size];
            int x = 1;
            for (int i = 0; i < size; i++)
            {
                expTable[i] = x;
                x <<= 1; // x = x * 2; we're assuming the generator alpha is 2
                if (x >= size)
                {
                    x ^= primitive;
                    x &= size - 1;
                }
            }
            for (int i = 0; i < size - 1; i++)
            {
                logTable[expTable[i]] = i;
            }
            // logTable[0] == 0 but this should never be used
            zero = new GenericGFPoly(this, new int[] { 0 });
            one = new GenericGFPoly(this, new int[] { 1 });
        }

        internal GenericGFPoly Zero
        {
            get
            {
                return zero;
            }
        }

        internal GenericGFPoly One
        {
            get
            {
                return one;
            }
        }

        ///
        /// Builds the monomial.
        ///
        /// <param name="degree">The degree.</param>
        /// <param name="coefficient">The coefficient.</param>
        /// <returns>the monomial representing coefficient * x^degree</returns>
        internal GenericGFPoly buildMonomial(int degree, int coefficient)
        {
            if (degree < 0)
            {
                throw new ArgumentException();
            }
            if (coefficient == 0)
            {
                return zero;
            }
            int[] coefficients = new int[degree + 1];
            coefficients[0] = coefficient;
            return new GenericGFPoly(this, coefficients);
        }

        ///
        /// Implements both addition and subtraction -- they are the same in GF(size).
        ///
        /// <returns>sum/difference of a and b</returns>
        static internal int addOrSubtract(int a, int b)
        {
            return a ^ b;
        }

        ///
        /// Exps the specified a.
        ///
        /// <returns>2 to the power of a in GF(size)</returns>
        internal int exp(int a)
        {
            return expTable[a];
        }

        ///
        /// Logs the specified a.
        ///
        /// <param name="a">A.</param>
        /// <returns>base 2 log of a in GF(size)</returns>
        internal int log(int a)
        {
            if (a == 0)
            {
                throw new ArgumentException();
            }
            return logTable[a];
        }

        ///
        /// Inverses the specified a.
        ///
        /// <returns>multiplicative inverse of a</returns>
        internal int inverse(int a)
        {
            if (a == 0)
            {
                throw new ArithmeticException();
            }
            return expTable[size - logTable[a] - 1];
        }

        ///
        /// Multiplies the specified a with b.
        ///
        /// <param name="a">A.</param>
        /// <param name="b">The b.</param>
        /// <returns>product of a and b in GF(size)</returns>
        internal int multiply(int a, int b)
        {
            if (a == 0 || b == 0)
            {
                return 0;
            }
            return expTable[(logTable[a] + logTable[b]) % (size - 1)];
        }

        ///
        /// Gets the size.
        ///
        public int Size
        {
            get { return size; }
        }

        ///
        /// Gets the generator base.
        ///
        public int GeneratorBase
        {
            get { return generatorBase; }
        }

        ///
        /// Returns a <see cref="System.String"/> that represents this instance.
        ///
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        override public String ToString()
        {
            return "GF(0x" + primitive.ToString("X") + ',' + size + ')';
        }
    }
}


text:
✅ This rule is enabled in the `recommended` [config](https://github.com/avajs/eslint-plugin-ava#recommended-config).

🔧💡 This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix) and manually fixable by [editor suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).

<!-- end auto-generated rule header -->

Translations: [Français](https://github.com/avajs/ava-docs/blob/main/fr_FR/related/eslint-plugin-ava/docs/rules/no-skip-test.md)

It's easy to make a test skipped with `test.skip()` and then forget about it. It's visible in the results, but still easily missed.

## Fail

```js
const test = require('ava');

test('foo', t => {
	t.pass();
});

test.skip('bar', t => {
	t.pass();
});
```

## Pass

```js
const test = require('ava');

test('foo', t => {
	t.pass();
});

test('bar', t => {
	t.pass();
});
```


text:
package org.aksw.coyotecache.cache;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

import objectexplorer.MemoryMeasurer;

/**
 * @author rspeck
 */
public class GDStar extends AbstractGD {

    public Double m_beta = 1D;

    public GDStar(int size, int evictCount) {
        super(size, evictCount);
    }

    @Override
    protected void hitAccess(Object key) {
        ((GDStarElement) m_accessMap.get(key)).update(((Element) key).getCost());
    }

    @Override
    protected void evict() {
        // set age and remove min element
        if (m_evictCount < m_accessMap.values().size()) {

            List<GDElement> evictElements = new LinkedList<GDElement>(m_accessMap.values());
            Collections.sort(evictElements);
            // LFU_DA_Element objects
            evictElements = evictElements.subList(0, m_evictCount);
            // min credit
            m_cacheAge = evictElements.get(0).getCredit();
            Iterator<Entry<Object, GDElement>> accessIter = m_accessMap.entrySet().iterator();
            while (accessIter.hasNext() && !evictElements.isEmpty()) {
                Entry<Object, GDElement> entry = accessIter.next();

                if (evictElements.contains(entry.getValue())) {
                    evictElements.remove(entry.getValue());
                    m_cacheMap.remove(entry.getKey());
                    accessIter.remove();
                }
            }

        } else {
            m_cacheMap.clear();
            m_accessMap.clear();
        }
    }

    @Override
    public List<Object> removeValues(Object value) {

        List<Object> removed = super.removeValues(value);
        for (Object o : removed)
            m_accessMap.remove(o);

        return removed;
    }

    /**
     * return false, on an error.
     */
    @Override
    public boolean test() {
        return (size() > m_cacheMaxSize ||
                m_accessMap.size() > m_cacheMaxSize || m_accessMap.size() > size()

        ) ? false : true;
    }

    @Override
    protected void putAccess(Object key) {
        Long mem = MemoryMeasurer.measureBytes(((Element) key).getObject());
        m_accessMap.put(key, new GDStarElement(
                m_cacheAge,
                ((Element) key).getCost(),
                mem.doubleValue()
                // Double.valueOf(((Set) ((Element) key).getObject()).size())
                )
                );
    }

    /**
     * Refined inner class for an element to compare on special value depends on
     * hits
     */
    protected class GDStarElement extends GDElement {

        private Integer m_hits = 0;
        private Double  m_size = 0D;
        private Double  m_cost = 0D;

        public GDStarElement(Double age, Double cost, Double size) {
            m_size = size;
            m_cost = cost;
            update(cost);
        }

        @Override
        public void update(Double cost) {

            m_cost += cost;
            m_cost /= 2;
            m_hits++;

            super.update(Math.pow(((cost * m_hits) / m_size), 1 / m_beta));
        }
    }
}


text:
extern mod anonexternmod;

pub fn main() { }


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Windows_organizer.Downloaders;
using Windows_organizer.interfaces;
using Windows_organizer.server;
using Windows_organizer.Views;

namespace Windows_organizer {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void button1_Click( object sender , EventArgs e ) {
            Form f = new preconfig_packages();
            f.Show();
            Hide();
        }

        private void button4_Click( object sender , EventArgs e ) {
            new StartmenuTest().Show();
            Hide();
        }

        private void button3_Click( object sender , EventArgs e ) {
            /*var g = new GoogleDownlaoder();
            new package_form(g.getProducts()).Show();
            Hide();*/

        }

        private void button5_Click( object sender , EventArgs e ) {
            var me = new MainEdit();
            me.Show();

        }

        private void button6_Click( object sender , EventArgs e )
        {
            var list =apiconnector.GetInstallables();
            new package_form(list).Show();
        }
    }
}


text:
* Merge in prettyclass package -- new Text.PrettyPrint.HughesPHClass.
* Add in 'maybe\*' variants of various bracket functins.
* Add Generic instances for appropriate data types.
* Fix compilation under GHC 7.10

## 1.1.1.3 -- 21st December, 2014

* Remove upper bound on `deepseq` package to fix build issues with
  latest GHC.

## 1.1.1.2 -- 18th August, 2014

* Add NFData and Eq instances (by Ivan Lazar Miljenovic).

## 1.1.1.1 -- 27th October, 2013

* Update pretty cabal file and readme.
* Fix tests to work with latest quickcheck.

## Version 3.0, 28 May 1987

* Cured massive performance bug. If you write:

    foldl <> empty (map (text.show) [1..10000])

  You get quadratic behaviour with V2.0. Why? For just the same
  reason as you get quadratic behaviour with left-associated (++)
  chains.

  This is really bad news. One thing a pretty-printer abstraction
  should certainly guarantee is insensitivity to associativity. It
  matters: suddenly GHC's compilation times went up by a factor of
  100 when I switched to the new pretty printer.

  I fixed it with a bit of a hack (because I wanted to get GHC back
  on the road). I added two new constructors to the Doc type, Above
  and Beside:

    <> = Beside
    $$ = Above

  Then, where I need to get to a "TextBeside" or "NilAbove" form I
  "force" the Doc to squeeze out these suspended calls to Beside and
  Above; but in so doing I re-associate. It's quite simple, but I'm
  not satisfied that I've done the best possible job. I'll send you
  the code if you are interested.

* Added new exports:
    punctuate, hang
    int, integer, float, double, rational,
    lparen, rparen, lbrack, rbrack, lbrace, rbrace,

* fullRender's type signature has changed. Rather than producing a
  string it now takes an extra couple of arguments that tells it how
  to glue fragments of output together:

    fullRender :: Mode
               -> Int                       -- Line length
               -> Float                     -- Ribbons per line
               -> (TextDetails -> a -> a)   -- What to do with text
               -> a                         -- What to do at the end
               -> Doc
               -> a                         -- Result

  The "fragments" are encapsulated in the TextDetails data type:

    data TextDetails = Chr  Char
                     | Str  String
                     | PStr FAST_STRING

  The Chr and Str constructors are obvious enough. The PStr
  constructor has a packed string (FAST_STRING) inside it. It's
  generated by using the new "ptext" export.

  An advantage of this new setup is that you can get the renderer to
  do output directly (by passing in a function of type (TextDetails
  -> IO () -> IO ()), rather than producing a string that you then
  print.

## Version 3.0, 28 May 1987

* Made empty into a left unit for <> as well as a right unit;
  it is also now true that
    nest k empty = empty
  which wasn't true before.

* Fixed an obscure bug in sep that occasionally gave very weird behaviour

* Added $+$

* Corrected and tidied up the laws and invariants

## Version 1.0

Relative to John's original paper, there are the following new features:

1. There's an empty document, "empty". It's a left and right unit for
   both <> and $$, and anywhere in the argument list for
   sep, hcat, hsep, vcat, fcat etc.

   It is Really Useful in practice.

2. There is a paragraph-fill combinator, fsep, that's much like sep,
   only it keeps fitting things on one line until it can't fit any more.

3. Some random useful extra combinators are provided.
     <+> puts its arguments beside each other with a space between them,
         unless either argument is empty in which case it returns the other

     hcat is a list version of <>
     hsep is a list version of <+>
     vcat is a list version of $$

     sep (separate) is either like hsep or like vcat, depending on what fits

     cat  behaves like sep,  but it uses <> for horizontal composition
     fcat behaves like fsep, but it uses <> for horizontal composition

     These new ones do the obvious things:
       char, semi, comma, colon, space,
       parens, brackets, braces,
       quotes, doubleQuotes

4. The "above" combinator, $$, now overlaps its two arguments if the
   last line of the top argument stops before the first line of the
   second begins.

     For example:  text "hi" $$ nest 5 (text "there")
     lays out as
                   hi   there
     rather than
                   hi
                        there

   There are two places this is really useful

     a) When making labelled blocks, like this:
            Left ->   code for left
            Right ->  code for right
            LongLongLongLabel ->
                      code for longlonglonglabel
        The block is on the same line as the label if the label is
        short, but on the next line otherwise.

     b) When laying out lists like this:
            [ first
            , second
            , third
            ]
        which some people like. But if the list fits on one line you
        want [first, second, third]. You can't do this with John's
        original combinators, but it's quite easy with the new $$.

   The combinator $+$ gives the original "never-overlap" behaviour.

5. Several different renderers are provided:
     * a standard one
     * one that uses cut-marks to avoid deeply-nested documents
       simply piling up in the right-hand margin
     * one that ignores indentation (fewer chars output; good for machines)
     * one that ignores indentation and newlines (ditto, only more so)

6. Numerous implementation tidy-ups
   Use of unboxed data types to speed up the implementation


text:
<?php

namespace litle\sdk;

require_once realpath(__DIR__).'/../../vendor/autoload.php';
# use Auth batch to get the session Id
$request = new LitleRequest();
$batch = new BatchRequest();
    $hash_in = [
        'card' => ['type'           => 'VI',
                'number'            => '4100000000000001',
                'expDate'           => '1213',
                'cardValidationNum' => '1213', ],
        'orderId'     => '2111',
        'orderSource' => 'ecommerce',
        'id'          => '654',
        'amount'      => '123', ];
    $batch->addAuth($hash_in);
    $request->addBatchRequest($batch);
    $responseFileLoc = $request->sendToLitleStream();
    $resp = new LitleResponseProcessor($responseFileLoc);
    $xmlReader = $resp->getXmlReader();
    $sessionId = $xmlReader->getAttribute('litleSessionId');
    echo 'sessionId:' + $sessionId;

     #Process RFR request
     $request = new LitleRequest();
     $request->createRFRRequest(['litleSessionId' => $sessionId]);
     $response_file = $request->sendToLitleStream();
     $processor = new LitleResponseProcessor($response_file);
     $res = $processor->nextTransaction(true);
     echo $res;
     $xml = simplexml_load_string($res);
    if ($xml->message[0] != 'Approved') {
        throw new \Exception('RfrRequest does not get the right response');
    }

     // if($xmlReader->getAttribute("message")!='Approved')
      // throw new \Exception('RfrRequest does not get the right response');
//


text:
/**
 * Provides exactly-once JDBC sink implementation using Java XA transactions API (JTA).
 *
 * @see org.apache.flink.connector.jdbc.xa.JdbcXaSinkFunction JdbcXaExactlyOnceSinkFunction
 */
package org.apache.flink.connector.jdbc.xa;


text:
{% extends "base.html" %}

{% load staticfiles %}
{% load crispy_forms_tags %}

{% block content %}

 Delete Request?

              <form action="" method="post">{% csrf_token %}

Are you sure you want to delete "{{ object }}"?

                  <input type="submit" class="btn btn-danger btn-sm" value="Confirm Delete" />

   Cancel

              </form>

{% endblock %}


text:
Tutorial
--------

En el tutorial previo sobre [Arreglos](https://www.learn-c.org/en/Arrays), cubrimos los arreglos y cómo funcionan. Los arreglos que vimos eran unidimensionales, pero C puede crear y usar arreglos multidimensionales. Aquí está la forma general de una declaración de un arreglo multidimensional:

	tipo nombre[tamaño1][tamaño2]...[tamañoN];

Por ejemplo, aquí hay uno básico para que lo veas -

	int foo[1][2][3];

o tal vez éste -

	char vowels[1][5] = {
		{'a', 'e', 'i', 'o', 'u'}
	};

### Arreglos bidimensionales

La forma más simple de los arreglos multidimensionales son los arreglos bidimensionales. Un arreglo bidimensionales es básicamente una lista de arreglos unidimensionales. Para declarar un arreglo bidimensionales de enteros de tamaño [ x ][ y ], lo escribirías algo así −

	tipo nombreDeArreglo [x][y];

Donde __tipo__ puede ser cualquier tipo de datos de C (int, char, long, long long, double, etc.) y __nombreDeArreglo__ será un identificador válido de C, o variable. Un arreglo bidimensional puede ser considerado como una tabla que tendrá [ x ] número de hileras y [ y ] número de columnas. Un arreglo bidimensional "a", el cual contiene tres hileras y cuatro columnas puede ser visto y pensado de la siguiente manera −

![Table 1A](https://www.tutorialspoint.com/cprogramming/images/two_dimensional_arrays.jpg)

En este sentido, todos los elementos en el arreglo a son identificados por un nombre de elemento en la forma __a[i][j]__, donde 'a' es el nombre del arreglo, y 'i' y 'j' son los índices que identifican, o muestran, cada elemento en 'a'.

Y realmente no necesitas poner un valor [ x ], porque si hicieses algo así -

	char vowels[][5] = {
		{'A', 'E', 'I', 'O', 'U'},
		{'a', 'e', 'i', 'o', 'u'}
	};

podríamos decir que el compilador ya sabría que hay dos "dimensiones", pero, necesitas necesitas __NECESITAS__ un valor [ y ]!! El compilador puede ser inteligente, pero _no sabrá_ cuantos enteros, caracteres, floats, lo que sea que estés usando tienes en las dimensiones. Ten eso en cuenta.

### Inicializando arreglos bidimensionales

Los arreglos multidimensionales pueden ser inicializados usando valores encorchados[] por cada hilera. Debajo hay un arreglo con 3 hileras y cada hilera tiene 4 columnas. Para hacerlo más sencillo, te puedes olvidar del 3 y dejarlo en blanco, todavía funcionaría.

	int a[3][4] = {
	   {0, 1, 2, 3} ,   /*  inicializadores para la hilera con indice 0 */
	   {4, 5, 6, 7} ,   /*  inicializadores para la hilera con indice 1 */
	   {8, 9, 10, 11}   /*  inicializadores para la hilera con indice 2 */
	};

Las llaves internas, las cuales indican la hilera deseada, son opcionales. La siguiente inicialización es la misma a la del ejemplo previo −

	int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

### Accediendo a elementos de arreglos bidimensionales

Un elemento de un arreglo bidimensional es accedido usando los suscriptos, e.g., índice de la hilera e índice de la columna del arreglo. Por ejemplo −

	int val = a[2][3];

La previa sentencia tomará el 4to elemento de la 3er hilera del arreglo.

Ejercicio
--------

Intentemos encontrar las calificaciones promedio de un grupo de cinco estudiantes para dos materias, Matemática y Física. Para hacer esto, Usamos un arreglo bidimensional llamado ```grades```. Las calificaciones que corresponden a Matemática serán guardadas en la primer hilera (```grades[0]```), mientras que las correspondientes a Física serán guardadas en la segunda hilera (```grades[1]```). Completa los siguientes pasos así podrás ejecutar este programa.

- Declara grades como un arreglo bidimensional de enteros
- Completa los bucles for especificando sus condiciones finalizadoras
- Calcula las calificaciones promedio obtenidas en cada materia

Tutorial Code
-------------

	#include <stdio.h>

	int main() {
		/* TODO: declara el arreglo 2D grades aquí */
		float average;
		int i;
		int j;

		grades[0][0] = 80;
		grades[0][1] = 70;
		grades[0][2] = 65;
		grades[0][3] = 89;
		grades[0][4] = 90;

		grades[1][0] = 85;
		grades[1][1] = 80;
		grades[1][2] = 80;
		grades[1][3] = 82;
		grades[1][4] = 87;

		/* TODO: completa el bucle for con las condiciones finalizadoras apropiadas */
		for (i = 0; i < ; i++) {
			average = 0;
			for (j = 0; j < ; j++) {
				average += grades[i][j];
			}

			/* TODO: calcula las calificaciones promedio para la materia i */
			printf("La calificación promedio de la materia %d es: %.2f\n", i, average);
		}

		return 0;
	}

Expected Output
---------------

    La calificación promedio de la materia 0 es: 78.80
    La calificación promedio de la materia 1 es: 82.80

Solution
--------

	#include <stdio.h>

	int main() {
		int grades[2][5];
		float average;
		int i;
		int j;

		grades[0][0] = 80;
		grades[0][1] = 70;
		grades[0][2] = 65;
		grades[0][3] = 89;
		grades[0][4] = 90;

		grades[1][0] = 85;
		grades[1][1] = 80;
		grades[1][2] = 80;
		grades[1][3] = 82;
		grades[1][4] = 87;

		for (i = 0; i < 2; i++) {
			average = 0;

			for (j = 0; j < 5; j++) {
				average += grades[i][j];
			}

			average /= 5.0;
			printf("La calificación promedio de la materia %d es: %.2f\n", i, average);
		}

		return 0;
	}


text:
package com.tomgibara.algebra.group;

abstract class AbstractCoset<E> implements Coset<E> {

	@Override
	public int hashCode() {
		return equality().getHasher().intHashValue(getRepresentative());
	}
}


text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    [Rest.Serialization.JsonTransformation]
    public partial class LoginScopes : ProxyOnlyResource
    {
        /// <summary>
        /// Initializes a new instance of the LoginScopes class.
        /// </summary>
        public LoginScopes()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the LoginScopes class.
        /// </summary>
        /// <param name="id">Resource Id.</param>
        /// <param name="name">Resource Name.</param>
        /// <param name="kind">Kind of resource.</param>
        /// <param name="type">Resource type.</param>
        public LoginScopes(string id = default(string), string name = default(string), string kind = default(string), string type = default(string), IList<string> scopes = default(IList<string>))
            : base(id, name, kind, type)
        {
            Scopes = scopes;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "properties.scopes")]
        public IList<string> Scopes { get; set; }

    }
}


text:
package org.coderswithoutborders.deglancer.func_debug.presenter;

import org.coderswithoutborders.deglancer.model.Stage;
import org.coderswithoutborders.deglancer.func_debug.view.IStatsView;

/**
 * Created by Renier on 2016/05/06.
 */
public interface IStatsViewPresenter {
    void setView(IStatsView view);
    void clearView();
    void onAttached();
    void onDetached();
    void refresh();
    void setStage(Stage stage);
    void clearDayClicked();
    void clearHourClicked();
    void clearStageClicked();
}


text:
/**
 *
 */
package com.nagarro.ycompany.ehr.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.nagarro.ycompany.ehr.service.impl.LoginServiceImpl;

/**
 * @author vivekmalhotra
 *
 */
@Controller
public class LoginController {

	@Autowired
	@Qualifier(value = "loginService")
	private LoginServiceImpl loginService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView loginPage() {
		return new ModelAndView("login");
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logoutPage(HttpServletRequest request,
			HttpServletResponse response) {
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		if (auth != null) {
			new SecurityContextLogoutHandler().logout(request, response, auth);
		}
		return "redirect:/login?logout";
	}

	// get the current user from Security context
	private String getPrincipal() {
		String userName = null;
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		if (principal instanceof UserDetails) {
			userName = ((UserDetails) principal).getUsername();
		} else {
			userName = principal.toString();
		}
		return userName;
	}

}


text:
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Sparow
{
	/// <summary>
	/// Title screen.
	/// </summary>
	public class EndGameScreen : MonoBehaviour
	{
		/// <summary>
		/// Update in each frame
		/// </summary>

		MusicControl musicSystem;

		void Start(){
			musicSystem = GameObject.Find("MusicSystem").GetComponent<MusicControl>();
			musicSystem.InGameMusic (0.0f);
		}

		void Update()
		{
			if (Input.GetButtonDown("Jump"))
			{
				StartCoroutine(LoadTitle());
			}
		}

		/// <summary>
		/// Loads the title scene
		/// </summary>
		/// <returns>IEnumerator for coroutine</returns>
		IEnumerator LoadTitle()
		{
			yield return SceneManager.LoadSceneAsync("TitleScreen");
		}
	}
}


text:
import Compromise from 'nlp_compromise';
import Chrono from 'chrono-node';
// -- Internal
const TERMS_RELATIONS = {
  person: 'subject',
  adverb: 'adverb',
  verb: 'action',
  noun: 'object',
  date: 'when',
  place: 'location',
  city: 'location',
  value: 'value',
};
const lexicon = Compromise.lexicon();
lexicon.ava = 'Person';
lexicon.here = 'Place';

// -- Private methods
const extractRelation = (tag, term, previous) => {
  const relation = {};
  let text = term.normal || term.text;

  switch (tag) {
    case 'date': {
      text = Chrono.parseDate(text);
      break;
    }

    case 'verb': {
      const compromiseVerb = Compromise.verb(term.expansion || term.text);
      if (!previous) {
        relation.verb = {
          tense: compromiseVerb.conjugation().toLowerCase().split('tense')[0],
          negative: compromiseVerb.isNegative(),
        };
      } else {
        relation.verb = previous.verb;
      }
      text = compromiseVerb.conjugate().infinitive;
      break;
    }

    case 'noun': {
      text = Compromise.text(text).root();
      break;
    }

    case 'person': {
      tag = term.pos.Pronoun ? 'pronoun' : tag;
      break;
    }

    default:
      break;
  }

  relation.tag = tag;
  relation.text = text;

  return relation;
};

export default (state) => {
  const sentence = state.sentence || Compromise.text(state.sentence).normal();
  const compromiseSentences = Compromise.text(sentence, { lexicon }).sentences;
  const terms = (compromiseSentences[0]) ? compromiseSentences[0].terms : [];
  const relations = {};

  terms.forEach(term => {
    const tag = (term.pos.Verb ? 'verb' : term.tag).toLowerCase();
    let relation = TERMS_RELATIONS[tag];

    if (relation) {
      if (relation === TERMS_RELATIONS.person && relations[relation]) {
        relation = (relations[relation] !== (term.normal || term.text)) ? TERMS_RELATIONS.noun : undefined;
      }
      if (relation) relations[relation] = extractRelation(tag, term, relations[relation]);
    }
  });
  state.relations = relations;

  return (state);
};


text:
class RemoveUserIdFromBottles < ActiveRecord::Migration[5.1]
  def change
    remove_column :bottles, :user_id, :integer
  end
end


text:
<?php

namespace Crackle\Authentication {

	/**
	 * Represents authentication data.
	 * @author George Brighton
	 */
	abstract class Credentials {

		/**
		 * The username to send.
		 * @var string
		 */
		private $username;

		/**
		 * The password to send.
		 * @var string
		 */
		private $password;

		/**
		 * Initialise this class with an optional username and password.
		 * @param string $username The username to send.
		 * @param string $password The password to send.
		 */
		public function __construct($username = null, $password = null) {
			if ($username !== null) {
				$this->setUsername($username);
			}
			if ($password !== null) {
				$this->setPassword($password);
			}
		}

		/**
		 * Get the username to send.
		 * @return string The username to send.
		 */
		private final function getUsername() {
			return $this->username;
		}

		/**
		 * Set the username to send.
		 * @param string $username The username to send.
		 */
		public final function setUsername($username) {
			$this->username = (string)$username;
		}

		/**
		 * Get the password to send.
		 * @return string The password to send.
		 */
		private final function getPassword() {
			return $this->password;
		}

		/**
		 * Set the password to send.
		 * @param string $password The password to send.
		 */
		public final function setPassword($password) {
			$this->password = (string)$password;
		}

		/**
		 * Retrieve the credentials represented by this object as a string.
		 * @return string The credentials in the form '[username]:[password]'.
		 */
		public function __toString() {
			$username = $this->getUsername() == '' ? 'X' : $this->getUsername();
			$password = $this->getPassword() == '' ? 'X' : $this->getPassword();
			return $username . ':' . $password;
		}
	}
}


text:
import { ServiceCollection } from './serviceCollection';
import * as descriptors from './descriptors';

// ------ internal util

export namespace _util {

	export const serviceIds = new Map<string, ServiceIdentifier<any>>();

	export const DI_TARGET = '$di$target';
	export const DI_DEPENDENCIES = '$di$dependencies';

	export function getServiceDependencies(ctor: any): { id: ServiceIdentifier<any>, index: number, optional: boolean }[] {
		return ctor[DI_DEPENDENCIES] || [];
	}
}

// --- interfaces ------

export type BrandedService = { _serviceBrand: undefined };

export interface IConstructorSignature0<T> {
	new(...services: BrandedService[]): T;
}

export interface IConstructorSignature1<A1, T> {
	new <Services extends BrandedService[]>(first: A1, ...services: Services): T;
}

export interface IConstructorSignature2<A1, A2, T> {
	new(first: A1, second: A2, ...services: BrandedService[]): T;
}

export interface IConstructorSignature3<A1, A2, A3, T> {
	new(first: A1, second: A2, third: A3, ...services: BrandedService[]): T;
}

export interface IConstructorSignature4<A1, A2, A3, A4, T> {
	new(first: A1, second: A2, third: A3, fourth: A4, ...services: BrandedService[]): T;
}

export interface IConstructorSignature5<A1, A2, A3, A4, A5, T> {
	new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, ...services: BrandedService[]): T;
}

export interface IConstructorSignature6<A1, A2, A3, A4, A5, A6, T> {
	new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, ...services: BrandedService[]): T;
}

export interface IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T> {
	new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: BrandedService[]): T;
}

export interface IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T> {
	new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8, ...services: BrandedService[]): T;
}

export interface ServicesAccessor {
	get<T>(id: ServiceIdentifier<T>): T;
	get<T>(id: ServiceIdentifier<T>, isOptional: typeof optional): T | undefined;
}

export const IInstantiationService = createDecorator<IInstantiationService>('instantiationService');

/**
 * Given a list of arguments as a tuple, attempt to extract the leading, non-service arguments
 * to their own tuple.
 */
type GetLeadingNonServiceArgs<Args> =
	Args extends [...BrandedService[]] ? []
	: Args extends [infer A1, ...BrandedService[]] ? [A1]
	: Args extends [infer A1, infer A2, ...BrandedService[]] ? [A1, A2]
	: Args extends [infer A1, infer A2, infer A3, ...BrandedService[]] ? [A1, A2, A3]
	: Args extends [infer A1, infer A2, infer A3, infer A4, ...BrandedService[]] ? [A1, A2, A3, A4]
	: Args extends [infer A1, infer A2, infer A3, infer A4, infer A5, ...BrandedService[]] ? [A1, A2, A3, A4, A5]
	: Args extends [infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, ...BrandedService[]] ? [A1, A2, A3, A4, A5, A6]
	: Args extends [infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7, ...BrandedService[]] ? [A1, A2, A3, A4, A5, A6, A7]
	: Args extends [infer A1, infer A2, infer A3, infer A4, infer A5, infer A6, infer A7, infer A8, ...BrandedService[]] ? [A1, A2, A3, A4, A5, A6, A7, A8]
	: never;

export interface IInstantiationService {

	_serviceBrand: undefined;

	/**
	 * Synchronously creates an instance that is denoted by
	 * the descriptor
	 */
	createInstance<T>(descriptor: descriptors.SyncDescriptor0<T>): T;
	createInstance<A1, T>(descriptor: descriptors.SyncDescriptor1<A1, T>, a1: A1): T;
	createInstance<A1, A2, T>(descriptor: descriptors.SyncDescriptor2<A1, A2, T>, a1: A1, a2: A2): T;
	createInstance<A1, A2, A3, T>(descriptor: descriptors.SyncDescriptor3<A1, A2, A3, T>, a1: A1, a2: A2, a3: A3): T;
	createInstance<A1, A2, A3, A4, T>(descriptor: descriptors.SyncDescriptor4<A1, A2, A3, A4, T>, a1: A1, a2: A2, a3: A3, a4: A4): T;
	createInstance<A1, A2, A3, A4, A5, T>(descriptor: descriptors.SyncDescriptor5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): T;
	createInstance<A1, A2, A3, A4, A5, A6, T>(descriptor: descriptors.SyncDescriptor6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): T;
	createInstance<A1, A2, A3, A4, A5, A6, A7, T>(descriptor: descriptors.SyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): T;
	createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(descriptor: descriptors.SyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): T;

	createInstance<Ctor extends new (...args: any[]) => any, R extends InstanceType<Ctor>>(t: Ctor, ...args: GetLeadingNonServiceArgs<ConstructorParameters<Ctor>>): R;

	/**
	 *
	 */
	invokeFunction<R, TS extends any[] = []>(fn: (accessor: ServicesAccessor, ...args: TS) => R, ...args: TS): R;

	/**
	 * Creates a child of this service which inherts all current services
	 * and adds/overwrites the given services
	 */
	createChild(services: ServiceCollection): IInstantiationService;
}

/**
 * Identifies a service of type T
 */
export interface ServiceIdentifier<T> {
	(...args: any[]): void;
	type: T;
}

function storeServiceDependency(id: Function, target: Function, index: number, optional: boolean): void {
	if ((target as any)[_util.DI_TARGET] === target) {
		(target as any)[_util.DI_DEPENDENCIES].push({ id, index, optional });
	} else {
		(target as any)[_util.DI_DEPENDENCIES] = [{ id, index, optional }];
		(target as any)[_util.DI_TARGET] = target;
	}
}

/**
 * The *only* valid way to create a {{ServiceIdentifier}}.
 */
export function createDecorator<T>(serviceId: string): ServiceIdentifier<T> {

	if (_util.serviceIds.has(serviceId)) {
		return _util.serviceIds.get(serviceId)!;
	}

	const id = <any>function (target: Function, key: string, index: number): any {
		if (arguments.length !== 3) {
			throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
		}
		storeServiceDependency(id, target, index, false);
	};

	id.toString = () => serviceId;

	_util.serviceIds.set(serviceId, id);
	return id;
}

/**
 * Mark a service dependency as optional.
 */
export function optional<T>(serviceIdentifier: ServiceIdentifier<T>) {

	return function (target: Function, key: string, index: number) {
		if (arguments.length !== 3) {
			throw new Error('@optional-decorator can only be used to decorate a parameter');
		}
		storeServiceDependency(serviceIdentifier, target, index, true);
	};
}


text: Práctica 20. Pausar o reanudar multimedia de acuerdo al ciclo de actividad.


text:
using WJStore.Application.Interfaces.Common;
using WJStore.Domain.Entities;

namespace WJStore.Application.Interfaces
{
    public interface IOrderDetailAppService : IAppService<OrderDetail>
    {

    }
}


text:
package org.neo4j.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.Collections;

/**
 * Implementation of JDBC Statement.
 */
public class Neo4jStatement
        implements Statement
{
    protected Neo4jConnection connection;
    protected ResultSet resultSet;
    protected SQLWarning sqlWarning;

    public Neo4jStatement( Neo4jConnection connection )
    {
        this.connection = connection;
    }

    @Override
    public ResultSet executeQuery( String s ) throws SQLException
    {
        execute( s );
        return resultSet;
    }

    @Override
    public int executeUpdate( String s ) throws SQLException
    {
        execute( s );
        // TODO return actual update count
        return 0;
    }

    @Override
    public void close() throws SQLException
    {
        if ( resultSet != null )
        {
            resultSet.close();
        }
        connection = null;
        resultSet = null;
        sqlWarning = null;
    }

    @Override
    public int getMaxFieldSize() throws SQLException
    {
        throw unsupported( "getMaxFieldSize" );
    }

    @Override
    public void setMaxFieldSize( int i ) throws SQLException
    {
        throw unsupported( "setMaxFieldSize " );
    }

    @Override
    public int getMaxRows() throws SQLException
    {
        throw unsupported( "getMaxRows" );
    }

    @Override
    public void setMaxRows( int i ) throws SQLException
    {
        throw unsupported( "setMaxRows" );
    }

    @Override
    public void setEscapeProcessing( boolean b ) throws SQLException
    {
        throw unsupported( "setEscapeProcessing" );
    }

    @Override
    public int getQueryTimeout() throws SQLException
    {
        throw unsupported( "getQueryTimeout" );
    }

    @Override
    public void setQueryTimeout( int i ) throws SQLException
    {
        throw unsupported( "setQueryTimeout" );
    }

    @Override
    public void cancel() throws SQLException
    {
        throw unsupported( "cancel" );
    }

    @Override
    public SQLWarning getWarnings() throws SQLException
    {
        return sqlWarning;
    }

    @Override
    public void clearWarnings() throws SQLException
    {
        sqlWarning = null;
    }

    @Override
    public void setCursorName( String s ) throws SQLException
    {
        throw unsupported( "setCursorName" );
    }

    @Override
    public boolean execute( String s ) throws SQLException
    {
        try
        {
            resultSet = connection.executeQuery( connection.nativeSQL( s ), Collections.<String, Object>emptyMap() );
            return true;
        }
        catch ( SQLWarning e )
        {
            if ( sqlWarning == null )
            {
                sqlWarning = e;
            }
            else
            {
                sqlWarning.setNextWarning( e );
            }
            throw e;
        }
        catch ( SQLException e )
        {
            throw e;
        }
        catch ( Throwable e )
        {
            throw new SQLException( e );
        }
    }

    @Override
    public ResultSet getResultSet() throws SQLException
    {
        return resultSet;
    }

    @Override
    public int getUpdateCount() throws SQLException
    {
        // TODO return actual update count
        // throw unsupported( "getUpdateCount" );
        return -1;
    }

    @Override
    public boolean getMoreResults() throws SQLException
    {
        resultSet = null;
        return false;
    }

    @Override
    public void setFetchDirection( int i ) throws SQLException
    {
        throw unsupported( "setFetchDirection" );
    }

    @Override
    public int getFetchDirection() throws SQLException
    {
        return ResultSet.FETCH_UNKNOWN;
    }

    @Override
    public void setFetchSize( int i ) throws SQLException
    {
        throw unsupported( "setFetchSize" );
    }

    @Override
    public int getFetchSize() throws SQLException
    {
        throw unsupported( "getFetchSize" );
    }

    @Override
    public int getResultSetConcurrency() throws SQLException
    {
        return ResultSet.CONCUR_READ_ONLY;
    }

    @Override
    public int getResultSetType() throws SQLException
    {
        return ResultSet.TYPE_FORWARD_ONLY;
    }

    @Override
    public void addBatch( String s ) throws SQLException
    {
        throw unsupported( "addBatch" );
    }

    @Override
    public void clearBatch() throws SQLException
    {
        throw unsupported( "clearBatch" );
    }

    @Override
    public int[] executeBatch() throws SQLException
    {
        throw unsupported( "executeBatch" );
    }

    @Override
    public Connection getConnection() throws SQLException
    {
        return connection;
    }

    @Override
    public boolean getMoreResults( int i ) throws SQLException
    {
        return getMoreResults();
    }

    @Override
    public ResultSet getGeneratedKeys() throws SQLException
    {
        return new ResultSetBuilder().newResultSet( connection );
    }

    @Override
    public int executeUpdate( String s, int i ) throws SQLException
    {
        return executeUpdate( s );
    }

    @Override
    public int executeUpdate( String s, int[] ints ) throws SQLException
    {
        return executeUpdate( s );
    }

    @Override
    public int executeUpdate( String s, String[] strings ) throws SQLException
    {
        return executeUpdate( s );
    }

    @Override
    public boolean execute( String s, int i ) throws SQLException
    {
        return execute( s );
    }

    @Override
    public boolean execute( String s, int[] ints ) throws SQLException
    {
        return execute( s );
    }

    @Override
    public boolean execute( String s, String[] strings ) throws SQLException
    {
        return execute( s );
    }

    @Override
    public int getResultSetHoldability() throws SQLException
    {
        return ResultSet.CLOSE_CURSORS_AT_COMMIT;
    }

    @Override
    public boolean isClosed() throws SQLException
    {
        return connection == null;
    }

    @Override
    public void setPoolable( boolean b ) throws SQLException
    {
        throw unsupported( "setPoolable" );
    }

    @Override
    public boolean isPoolable() throws SQLException
    {
        return false;
    }

    @Override
    public <T> T unwrap( Class<T> tClass ) throws SQLException
    {
        return (T) this;
    }

    @Override
    public boolean isWrapperFor( Class<?> aClass ) throws SQLException
    {
        return false;
    }

    public void closeOnCompletion() throws SQLException
    {
        throw unsupported( "closeOnCompletion" );
    }

    public boolean isCloseOnCompletion() throws SQLException
    {
        return false;
    }

    private static SQLFeatureNotSupportedException unsupported( String methodName )
    {
        return new SQLFeatureNotSupportedException( methodName + " is not supported by Neo4jStatement." );
    }
}


text:
/*
 * File:   RoutingTableTest.h
 * Author: Rolando Martins (rolando.martins@gmail.com)
 *
 * Created on May 19, 2010, 12:31:05 PM
 */

#ifndef ROUTINGTABLETEST_H
#define	ROUTINGTABLETEST_H

#include <cppunit/extensions/HelperMacros.h>

class RoutingTableTest : public CPPUNIT_NS::TestFixture {
    CPPUNIT_TEST_SUITE(RoutingTableTest);

    CPPUNIT_TEST(testMethod);

    CPPUNIT_TEST_SUITE_END();

public:
    RoutingTableTest();
    virtual ~RoutingTableTest();
    void setUp();
    void tearDown();

private:
    void testMethod();

};

#endif	/* ROUTINGTABLETEST_H */


text:
function locs=dotdiscr(dd,d,dots)

% LOCS=DOTDISCR - Internal function for dotdiscriminator - does discrimination
%
% LOCS = DOTDISCR(DD,D,DOTS)
%

locs = dotdisc(d,dots);

p = getparameters(dd);

di = diff(locs);
ind = find(di>p.refractory_period);
while ~isempty(locs)&(length(ind)~=length(locs)-1),
		% runs <refrectory_period times
	di = diff(locs);
	ind = find(di>p.refractory_period);
	locs = locs([1 ind'+1]);
end;


text:
namespace Olaru.Village.Model {
	public class BaseModel {
		public int Id { get; set; }
	}
}


text:
'use strict';

const request = require('../helpers/context').request;

describe('req.secure', function(){
  it('should return true when encrypted', function(){
    const req = request();
    req.req.socket = { encrypted: true };
    req.secure.should.be.true;
  });
});


text:
Ti=Footnote 54

sec=Guidance on the preparation of an action plan for radon is provided in Ref. [6], for example.

=[G/Z/Base]


text:
FROM node

WORKDIR /usr/server

ADD ./package.json /usr/server/package.json
RUN npm install

ADD . /usr/server

EXPOSE 8081

CMD [ "node", "./app/server.js" ]


text:
fancytree-rails is a simple gem to add [FancyTree](https://github.com/mar10/fancytree) vendor files to the
Rails asset pipeline.

## Installation

Add this line to your application's Gemfile:

    gem 'fancytree-rails'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install fancytree-rails

## Usage

In your Gemfile, add:

```ruby
gem 'fancytree-rails'
```

Note that also [jquery-ui-rails](https://github.com/joliss/jquery-ui-rails) needs to be available.

Require javascript to ```app/assets/javascripts/application.js```:

```
//= require fancytree
```

In case you want to use *gridnav* add also ```//=require fancytree/jquery.fancytree.gridnav.js```

Extend stylesheet assets ```app/assets/stylesheets/application.css```
by:

```
*= require ui.fancytree
```

or if you want to use another style include it directly:
```
*= require fancytree/skin-awesome/ui.fancytree
```
Note that for awesome style (extension) to work you to:

1. Add ```font-awesome-rails``` gem (and include its style in application.css)
2. Enable ```awesome``` extension in Fancytree.
3. Include extension code (```//= require fancytree/jquery.fancytree.awesome```) to ```app/assets/javascripts/application.js```.

## Credits

Piece of code of Rakefile copied from joliss/jquery-ui-rails. See
3th-party for its license.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`). You
   can use rake fancytree:update for semiautomatic update of mar10/fancytree
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
add_library(openthread-rcp)

set_target_properties(
    openthread-rcp
    PROPERTIES
        C_STANDARD 99
        CXX_STANDARD 11
)

target_compile_definitions(openthread-rcp PRIVATE
    OPENTHREAD_RADIO=1
    OPENTHREAD_CONFIG_NCP_UART_ENABLE=1
)

target_compile_options(openthread-rcp PRIVATE
    ${OT_CFLAGS}
)

target_include_directories(openthread-rcp PUBLIC ${OT_PUBLIC_INCLUDES} PRIVATE ${COMMON_INCLUDES})

target_sources(openthread-rcp PRIVATE ${COMMON_SOURCES})
target_include_directories(openthread-rcp PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})

target_link_libraries(openthread-rcp
    PUBLIC
        openthread-radio
    PRIVATE
        openthread-hdlc
        openthread-spinel-rcp
        ot-config
)