text:
package abi42_0_0.expo.modules.contacts.models;
import android.database.Cursor;
import android.provider.ContactsContract;

import abi42_0_0.expo.modules.contacts.EXColumns;

import static android.provider.ContactsContract.*;

public class UrlAddressModel extends BaseModel {
    @Override
    public String getContentType() {
        return CommonDataKinds.Website.CONTENT_ITEM_TYPE;
    }

    @Override
    public String getDataAlias() {
        return "url";
    }

    @Override
    protected String getLabelFromCursor(Cursor cursor) {
        String label = super.getLabelFromCursor(cursor);
        if (label != null)
            return label;
        switch (cursor.getInt(cursor.getColumnIndex(EXColumns.TYPE))) {
        case CommonDataKinds.Website.TYPE_HOME:
            return "home";
        case CommonDataKinds.Website.TYPE_WORK:
            return "work";
        case CommonDataKinds.Website.TYPE_BLOG:
            return "blog";
        case CommonDataKinds.Website.TYPE_FTP:
            return "ftp";
        case CommonDataKinds.Website.TYPE_HOMEPAGE:
            return "homepage";
        case CommonDataKinds.Website.TYPE_PROFILE:
            return "profile";
        case CommonDataKinds.Website.TYPE_OTHER:
            return "other";
        default:
            return "unknown";
        }
    }

}


text:
#pragma once

#include <yardstick/yardstick.h>

#include "webby/webby.h"

namespace _ys_ {

struct EventData;

class WebsocketSink
{
	struct Session;

	ysAllocator _allocator = nullptr;
	unsigned short _port = 0;

	struct WebbyServer* _server = nullptr;
	void* _memory = nullptr;

	Session* _sessions = nullptr;

	static void webby_log(const char* text);
	static int webby_dispatch(struct WebbyConnection *connection);
	static int webby_connect(struct WebbyConnection *connection);
	static void webby_connected(struct WebbyConnection *connection);
	static void webby_closed(struct WebbyConnection *connection);
	static int webby_frame(struct WebbyConnection *connection, const struct WebbyWsFrame *frame);

	Session* CreateSession(WebbyConnection* connection);
	Session* FindSession(WebbyConnection* connection);
	void DestroySession(Session* session);

	ysResult WriteSessionString(Session* session, char const* str);
	ysResult WriteSessionEvent(Session* session, EventData const& ev);
	ysResult FlushSession(Session* session);

public:
	WebsocketSink();
	~WebsocketSink();

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

	ysResult Listen(unsigned short port, ysAllocator alloc);
	ysResult Close();

	ysResult Update();
	ysResult WriteEvent(EventData const& ev);
	ysResult Flush();
};

}

redpajama_set_name: RedPajamaGithub


text:
from sqlalchemy import func

from babbage.model.concept import Concept

class Aggregate(Concept):
    """ An aggregates describes the application of an aggregate function (such
    as summing, averages, counts etc.) to a measure or the primary key of the
    cube. """

    def __init__(self, model, label, function, measure=None):
        super(Aggregate, self).__init__(model, None, {'label': label})
        self.function = function
        self.measure = measure

    @property
    def ref(self):
        if self.measure is not None:
            return '%s.%s' % (self.measure.ref, self.function)
        return '_%s' % self.function

    def bind(self, cube):
        """ When one column needs to match, use the key. """
        if self.measure:
            table, column = self.measure.bind(cube)
        else:
            table, column = cube.fact_table, cube.fact_pk
        # apply the SQL aggregation function:
        column = getattr(func, self.function)(column)
        column = column.label(self.ref)
        column.quote = True
        return table, column

    def __repr__(self):
        return "<Aggregate(%s)>" % self.ref

    def to_dict(self):
        data = self.spec.copy()
        data['ref'] = self.ref
        data['function'] = self.function
        if self.measure is not None:
            data['measure'] = self.measure.ref
        return data


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="au.net.danielparker.heightconvert" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ConvertActivity_"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/examples/network_tester/expected_output_data.h"
#include "tensorflow/lite/micro/examples/network_tester/input_data.h"
#include "tensorflow/lite/micro/examples/network_tester/network_model.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_utils.h"
#include "tensorflow/lite/micro/testing/micro_test.h"
#include "tensorflow/lite/micro/testing/test_utils.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/version.h"

#ifndef TENSOR_ARENA_SIZE
#define TENSOR_ARENA_SIZE (1024)
#endif

#ifndef NUM_INFERENCES
#define NUM_INFERENCES 1
#endif

uint8_t tensor_arena[TENSOR_ARENA_SIZE];

#ifdef NUM_BYTES_TO_PRINT
inline void print_output_data(TfLiteTensor* output) {
  int num_bytes_to_print =
      ((output->bytes < NUM_BYTES_TO_PRINT) || NUM_BYTES_TO_PRINT == 0)
          ? output->bytes
          : NUM_BYTES_TO_PRINT;

  int dims_size = output->dims->size;
  printf("{\n");
  printf("\"dims\": [%d,", dims_size);
  for (int i = 0; i < output->dims->size - 1; ++i) {
    printf("%d,", output->dims->data[i]);
  }
  printf("%d],\n", output->dims->data[dims_size - 1]);

  printf("\"data_address\": \"%p\",\n", output->data.raw);
  printf("\"data\":\"");
  for (int i = 0; i < num_bytes_to_print - 1; ++i) {
    if (i % 16 == 0 && i != 0) {
      printf("\n");
    }
    printf("0x%02x,", output->data.uint8[i]);
  }
  printf("0x%02x\"\n", output->data.uint8[num_bytes_to_print - 1]);
  printf("}");
}
#endif

template <typename T>
void check_output_elem(TfLiteTensor* output, const T* expected_output,
                       const int index) {
  TF_LITE_MICRO_EXPECT_EQ(tflite::GetTensorData<T>(output)[index],
                          expected_output[index]);
}

TF_LITE_MICRO_TESTS_BEGIN

TF_LITE_MICRO_TEST(TestInvoke) {
  tflite::MicroErrorReporter micro_error_reporter;

  const tflite::Model* model = ::tflite::GetModel(network_model);
  if (model->version() != TFLITE_SCHEMA_VERSION) {
    TF_LITE_REPORT_ERROR(&micro_error_reporter,
                         "Model provided is schema version %d not equal "
                         "to supported version %d.\n",
                         model->version(), TFLITE_SCHEMA_VERSION);
    return kTfLiteError;
  }

  tflite::AllOpsResolver resolver;

  tflite::MicroInterpreter interpreter(
      model, resolver, tensor_arena, TENSOR_ARENA_SIZE, &micro_error_reporter);

  TfLiteStatus allocate_status = interpreter.AllocateTensors();
  if (allocate_status != kTfLiteOk) {
    TF_LITE_REPORT_ERROR(&micro_error_reporter, "Tensor allocation failed\n");
    return kTfLiteError;
  }

  for (int n = 0; n < NUM_INFERENCES; n++) {
    for (size_t i = 0; i < interpreter.inputs_size(); ++i) {
      TfLiteTensor* input = interpreter.input(i);
      memcpy(input->data.data, input_data[i], input->bytes);
    }
    TfLiteStatus invoke_status = interpreter.Invoke();
    if (invoke_status != kTfLiteOk) {
      TF_LITE_REPORT_ERROR(&micro_error_reporter, "Invoke failed\n");
      return kTfLiteError;
    }
    TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, invoke_status);

#ifdef NUM_BYTES_TO_PRINT
    // Print all of the output data, or the first NUM_BYTES_TO_PRINT bytes,
    // whichever comes first as well as the output shape.
    printf("num_of_outputs: %d\n", interpreter.outputs_size());
    printf("output_begin\n");
    printf("[\n");
    for (int i = 0; i < interpreter.outputs_size(); i++) {
      TfLiteTensor* output = interpreter.output(i);
      print_output_data(output);
      if (i != interpreter.outputs_size() - 1) {
        printf(",\n");
      }
    }
    printf("]\n");
    printf("output_end\n");
#endif

#ifndef NO_COMPARE_OUTPUT_DATA
    for (size_t i = 0; i < interpreter.outputs_size(); i++) {
      TfLiteTensor* output = interpreter.output(i);
      for (int j = 0; j < tflite::ElementCount(*(output->dims)); ++j) {
        check_output_elem(output, expected_output_data[i], j);
      }
    }
#endif
  }
  TF_LITE_REPORT_ERROR(&micro_error_reporter, "Ran successfully\n");
}

TF_LITE_MICRO_TESTS_END


text:
package org.kuali.rice.kew.plugin;

import org.junit.Test;
import org.kuali.rice.core.api.util.ContextClassLoaderBinder;

import java.net.URL;
import java.net.URLClassLoader;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * Tests the ContextClassLoaderBinder
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class ContextClassLoaderBinderTest {

    /**
     * @deprecated {@link ContextClassLoaderBinder#doInContextClassLoader(ClassLoader, java.util.concurrent.Callable)} is the safe way to
     * run code under a specific Context ClassLoader that ensures the classloader is always set and unset properly.
     */
	@Test public void testBinding() {
        try {
            ContextClassLoaderBinder.unbind();
            fail("unbind succeeded without any prior bind");
        } catch (IllegalStateException ise) {
            // expect illegal state
        }

        ClassLoader cl0 = new URLClassLoader(new URL[] {});
        ClassLoader cl1 = new URLClassLoader(new URL[] {});
        ClassLoader cl2 = new URLClassLoader(new URL[] {});

        ClassLoader original = Thread.currentThread().getContextClassLoader();
        ContextClassLoaderBinder.bind(cl0);
        assertEquals(cl0, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.unbind();
        assertEquals(original, Thread.currentThread().getContextClassLoader());

        ContextClassLoaderBinder.bind(cl0);
        assertEquals(cl0, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.bind(cl1);
        assertEquals(cl1, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.unbind();
        assertEquals(cl0, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.unbind();
        assertEquals(original, Thread.currentThread().getContextClassLoader());

        ContextClassLoaderBinder.bind(cl0);
        assertEquals(cl0, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.bind(cl1);
        assertEquals(cl1, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.bind(cl2);
        assertEquals(cl2, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.unbind();
        assertEquals(cl1, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.unbind();
        assertEquals(cl0, Thread.currentThread().getContextClassLoader());
        ContextClassLoaderBinder.unbind();
        assertEquals(original, Thread.currentThread().getContextClassLoader());
    }
}


text:
require 'spec_helper'
require 'pathname'

context 'with configuration.yaml' do
  it 'exists' do
    configuration_file = Pathname.new(__FILE__).join '..', '..', '..', '..', 'lib', 'indoctrinatr', 'templates', 'configuration.yaml'
    expect(File.exist?(configuration_file)).to eq true
  end
end


text:
import angular from 'angular';

import component from './ngbTrackResizePreference.component';
import controller from './ngbTrackResizePreference.controller';
import run from './ngbTrackResizePreference.run';

export default angular.module('ngbTrackResizePreference', [])
    .controller(controller.UID, controller)
    .component('ngbTrackResizePreference', component)
    .run(run)
    .name;


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="dk.niclashorstad.pocketmoneybysaxo">

    <!-- To auto-complete the email text field in the login form with the user's emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/SaxoAppTheme">
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainMenuActivity" />
        <activity android:name=".ViewBalanceActivity"></activity>
    </application>

</manifest>


text:
/*	$OpenBSD: pccreg.h,v 1.3 1996/04/28 11:03:27 deraadt Exp $ */

/*
 * Copyright (c) 1995 Theo de Raadt
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed under OpenBSD by
 *	Theo de Raadt for Willowglen Singapore.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * MVME147 PCC chip
 */
struct pccreg {
	volatile u_long		pcc_dmataddr;	/* dma table address */
	volatile u_long		pcc_dmadaddr;	/* dma data address */
	volatile u_long		pcc_dmabcnt;	/* dma byte count */
	volatile u_long		pcc_dmahold;	/* dma data hold register */
	volatile u_short	pcc_t1pload;	/* timer1 preload */
	volatile u_short	pcc_t1count;	/* timer1 count */
	volatile u_short	pcc_t2pload;	/* timer2 preload */
	volatile u_short	pcc_t2count;	/* timer2 count */
	volatile u_char		pcc_t1irq;	/* timer1 interrupt ctrl */
	volatile u_char		pcc_t1ctl;	/* timer1 ctrl reg */
	volatile u_char		pcc_t2irq;	/* timer2 interrupt ctrl */
	volatile u_char		pcc_t2ctl;	/* timer2 ctrl reg */
	volatile u_char		pcc_acfirq;	/* acfail intr reg */
	volatile u_char		pcc_dogirq;	/* watchdog intr reg */
	volatile u_char		pcc_lpirq;	/* printer intr reg */
	volatile u_char		pcc_lpctl;	/* printer ctrl */
	volatile u_char		pcc_dmairq;	/* dma interrupt control */
	volatile u_char		pcc_dmacsr;	/* dma csr */
	volatile u_char		pcc_busirq;	/* bus error interrupt */
	volatile u_char		pcc_dmasr;	/* dma status register */
	volatile u_char		pcc_abortirq;	/* abort interrupt control reg */
	volatile u_char		pcc_tafcr;	/* table address function code reg */
	volatile u_char		pcc_zsirq;	/* serial interrupt reg */
	volatile u_char		pcc_genctl;	/* general control register */
	volatile u_char		pcc_leirq;	/* ethernet interrupt */
	volatile u_char		pcc_gensr;	/* general status */
	volatile u_char		pcc_sbicirq;	/* sbic interrupt reg */
	volatile u_char		pcc_slavebase;	/* slave base addr reg */
	volatile u_char		pcc_sw1inq;	/* software interrupt #1 cr */
	volatile u_char		pcc_vecbase;	/* interrupt base vector register */
	volatile u_char		pcc_sw2irq;	/* software interrupt #2 cr */
	volatile u_char		pcc_chiprev;	/* revision level */
};
#define PCCSPACE_PCCCHIP_OFF	0x1000

/*
 * points to system's PCC. This is not active until the pcc0 device
 * has been attached.
 */
extern struct pccreg *sys_pcc;

/*
 * We lock off our interrupt vector at 0x40.
 */
#define PCC_VECBASE	0x40
#define PCC_NVEC	12

/*
 * Vectors we use
 */
#define PCCV_ACFAIL	0
#define PCCV_BERR	1
#define PCCV_ABORT	2
#define PCCV_ZS		3
#define PCCV_LE		4
#define PCCV_SBIC	5
#define PCCV_DMA	6
#define PCCV_PRINTER	7
#define PCCV_TIMER1	8
#define PCCV_TIMER2	9
#define PCCV_SOFT1	10
#define PCCV_SOFT2	11

#define PCC_DMABCNT_MAKEFC(fcn)	((fcn) << 24)
#define PCC_DMABCNT_FCMASK	0x07000000
#define PCC_DMABCNT_L		0x80000000
#define PCC_DMABCNT_CNTMASK	0x00ffffff

#define PCC_DMACSR_DONE		0x80
#define PCC_DMACSR_ERR8BIT	0x40
#define PCC_DMACSR_TNOT32	0x20
#define PCC_DMACSR_DMAERRDATA	0x10
#define PCC_DMACSR_DMAERRTABLE	0x08
#define PCC_DMACSR_TOSCSI	0x04
#define PCC_DMACSR_USETABLE	0x02
#define PCC_DMACSR_DEN		0x01

#define PCC_SBIC_RESETIRQ	0x40
#define PCC_SBIC_RESETABS	0x20

/*
 * Fairly standard irq register bits.
 */
#define PCC_IRQ_IPL	0x07
#define PCC_IRQ_IEN	0x08
#define PCC_IRQ_INT	0x80

#define PCC_LPIRQ_ACK	0x20

/*
 * clock/timer
 */
#define PCC_TIMERACK	0x80	/* ack intr */
#define PCC_TIMERCLEAR	0x00	/* reset and clear timer */
#define PCC_TIMERSTART	0x03	/* start timer */

#define	pcc_timer_hz2lim(hz)	(65536 - (160000/(hz)))
#define	pcc_timer_us2lim(us)	(65536 - (160000/(1000000/(us))))

/*
 * serial control
 */
#define PCC_ZS_PCCVEC	0x10	/* let PCC supply vector */

/*
 * abort switch
 */
#define PCC_ABORT_IEN	0x08	/* enable interrupt */
#define PCC_ABORT_ABS	0x40	/* current state of switch */
#define PCC_ABORT_ACK	0x80	/* intr active; or write to ack */

/*
 * for the console we need zs phys addr
 */
#define ZS0_PHYS_147	(INTIOBASE_147 + 0x3000)
#define ZS1_PHYS_147	(INTIOBASE_147 + 0x3800)

/* XXX */
int	pccintr_establish __P((int vec, struct intrhand *ih));

#define PCC_GENCTL_IEN	0x10


text:
package uk.gov.phe.erdst.sc.awag.webapi.resource;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;

import uk.gov.phe.erdst.sc.awag.exceptions.AWInputValidationException;
import uk.gov.phe.erdst.sc.awag.service.export.ActivityLogExporter;
import uk.gov.phe.erdst.sc.awag.utils.Constants;
import uk.gov.phe.erdst.sc.awag.utils.Constants.WebApi;
import uk.gov.phe.erdst.sc.awag.utils.WebApiUtils;
import uk.gov.phe.erdst.sc.awag.utils.WebSecurityUtils;

@Path(WebApi.RESOURCE_ACTIVITY_LOG_API)
public class ActivityLogResource extends GlobalResource
{
    @Inject
    private ActivityLogExporter mActivityLogExporter;

    /**
     * Export activity logs. Call this endpoint with an HTML form.

     * dateFrom and dateTo mvnDateFormatJavaDoc

     * offset mvnPagingOffsetValidValueJavaDoc

     * limit mvnPagingLimitValidValueJavaDoc

     * When the request is served, a file download disposition will be set.
     * Also, a cookie with name: activityLogDownloadStatus will be returned by the server.
     * @param dateFrom
     * @param dateTo
     * @param offset
     * @param limit
     * @response mvn400ResponseJson
     * @response mvn500ResponseJson
     */
    @Path(Constants.WebApi.RESOURCE_EXPORT_PATH)
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void export(@DefaultValue(OPTIONAL_PARAM_VALUE) @FormParam(PARAM_DATE_FROM) String dateFrom,
        @DefaultValue(OPTIONAL_PARAM_VALUE) @FormParam(PARAM_DATE_TO) String dateTo,
        @DefaultValue(OPTIONAL_PARAM_VALUE) @FormParam(PAGING_REQUEST_OFFSET_QUERY_PARAM) Integer offset,
        @DefaultValue(OPTIONAL_PARAM_VALUE) @FormParam(PAGING_REQUEST_LIMIT_QUERY_PARAM) Integer limit,
        @Context HttpHeaders headers, @Context HttpServletResponse response, @Context SecurityContext sc)
        throws AWInputValidationException, IOException
    {
        String dateFromChecked = WebApiUtils.changeDateParamToNullIfEmpty(dateFrom);
        String dateToChecked = WebApiUtils.changeDateParamToNullIfEmpty(dateTo);

        setDownloadStatusCookie(response, mActivityLogExporter);

        mActivityLogExporter.exportData(dateFromChecked, dateToChecked, WebApiUtils.getPagingParams(offset, limit),
            response, WebSecurityUtils.getNewApiLoggedUser(sc));
    }

    private void setDownloadStatusCookie(HttpServletResponse response, ActivityLogExporter exporter)
    {
        Cookie cookie = new Cookie(exporter.getDownloadStatusCookieName(), exporter.getDownloadStatusCookieValue());
        cookie.setMaxAge(exporter.getDownloadStatusCookieExpirationTimeSeconds());
        cookie.setPath(Constants.WebApi.DOWNLOAD_STATUS_COOKIE_PATH);
        cookie.setHttpOnly(false);

        response.addCookie(cookie);
    }

}


text:
namespace boost { namespace numeric
{

template<class N>
struct bounds : boundsdetail::get_impl<N>::type
{} ;

} } // namespace boost::numeric

#endif


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

namespace Google.Apis.Upload
{
    /// <summary>
    /// Enum to communicate the status of an upload for progress reporting.
    /// </summary>
    public enum UploadStatus
    {
        /// <summary>
        /// The upload has not started.
        /// </summary>
        NotStarted,

        /// <summary>
        /// The upload is initializing.
        /// </summary>
        Starting,

        /// <summary>
        /// Data is being uploaded.
        /// </summary>
        Uploading,

        /// <summary>
        /// The upload completed successfully.
        /// </summary>
        Completed,

        /// <summary>
        /// The upload failed.
        /// </summary>
        Failed
    };

    /// <summary>
    /// Interface reporting upload progress.
    /// </summary>
    public interface IUploadProgress
    {
        /// <summary>
        /// Gets the current status of the upload
        /// </summary>
        UploadStatus Status { get; }

        /// <summary>
        /// Gets the approximate number of bytes sent to the server.
        /// </summary>
        long BytesSent { get; }

        /// <summary>
        /// Gets an exception if one occurred.
        /// </summary>
        Exception Exception { get; }
    }
}


text:
package org.apache.flink.api.common.typeutils.base;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeutils.TypeComparator;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.types.NormalizableKey;
import org.apache.flink.types.StringValue;

import java.io.IOException;

/** Specialized comparator for StringValue based on CopyableValueComparator. */
@Internal
public class StringValueComparator extends TypeComparator<StringValue> {

    private static final long serialVersionUID = 1L;

    private final boolean ascendingComparison;

    private final StringValue reference = new StringValue();

    private final StringValue tempReference = new StringValue();

    private final TypeComparator<?>[] comparators = new TypeComparator[] {this};

    public StringValueComparator(boolean ascending) {
        this.ascendingComparison = ascending;
    }

    @Override
    public int hash(StringValue record) {
        return record.hashCode();
    }

    @Override
    public void setReference(StringValue toCompare) {
        toCompare.copyTo(reference);
    }

    @Override
    public boolean equalToReference(StringValue candidate) {
        return candidate.equals(this.reference);
    }

    @Override
    public int compareToReference(TypeComparator<StringValue> referencedComparator) {
        StringValue otherRef = ((StringValueComparator) referencedComparator).reference;
        int comp = otherRef.compareTo(reference);
        return ascendingComparison ? comp : -comp;
    }

    @Override
    public int compare(StringValue first, StringValue second) {
        int comp = first.compareTo(second);
        return ascendingComparison ? comp : -comp;
    }

    @Override
    public int compareSerialized(DataInputView firstSource, DataInputView secondSource)
            throws IOException {
        reference.read(firstSource);
        tempReference.read(secondSource);
        int comp = reference.compareTo(tempReference);
        return ascendingComparison ? comp : -comp;
    }

    @Override
    public boolean supportsNormalizedKey() {
        return NormalizableKey.class.isAssignableFrom(StringValue.class);
    }

    @Override
    public int getNormalizeKeyLen() {
        return reference.getMaxNormalizedKeyLen();
    }

    @Override
    public boolean isNormalizedKeyPrefixOnly(int keyBytes) {
        return keyBytes < getNormalizeKeyLen();
    }

    @Override
    public void putNormalizedKey(
            StringValue record, MemorySegment target, int offset, int numBytes) {
        record.copyNormalizedKey(target, offset, numBytes);
    }

    @Override
    public boolean invertNormalizedKey() {
        return !ascendingComparison;
    }

    @Override
    public TypeComparator<StringValue> duplicate() {
        return new StringValueComparator(ascendingComparison);
    }

    @Override
    public int extractKeys(Object record, Object[] target, int index) {
        target[index] = record;
        return 1;
    }

    @Override
    public TypeComparator<?>[] getFlatComparators() {
        return comparators;
    }

    // --------------------------------------------------------------------------------------------
    // unsupported normalization
    // --------------------------------------------------------------------------------------------

    @Override
    public boolean supportsSerializationWithKeyNormalization() {
        return false;
    }

    @Override
    public void writeWithKeyNormalization(StringValue record, DataOutputView target)
            throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public StringValue readWithKeyDenormalization(StringValue reuse, DataInputView source)
            throws IOException {
        throw new UnsupportedOperationException();
    }
}


text:
package org.apache.hadoop.hdfs.server.namenode;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.permission.PermissionStatus;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NamenodeRole;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory;
import org.apache.hadoop.hdfs.server.namenode.JournalSet.JournalAndStream;
import org.apache.hadoop.hdfs.server.namenode.NNStorage.NameNodeDirType;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.Time;
import org.apache.log4j.Level;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/**
 * This class tests various synchronization bugs in FSEditLog rolling
 * and namespace saving.
 */
@RunWith(Parameterized.class)
public class TestEditLogRace {
  static {
    GenericTestUtils.setLogLevel(FSEditLog.LOG, Level.ALL);
  }

  @Parameters
  public static Collection<Object[]> data() {
    Collection<Object[]> params = new ArrayList<Object[]>();
    params.add(new Object[]{ false });
    params.add(new Object[]{ true });
    return params;
  }

  private static boolean useAsyncEditLog;

  public TestEditLogRace(boolean useAsyncEditLog) {
    TestEditLogRace.useAsyncEditLog = useAsyncEditLog;
  }

  private static final Log LOG = LogFactory.getLog(TestEditLogRace.class);

  // This test creates NUM_THREADS threads and each thread continuously writes
  // transactions
  static final int NUM_THREADS = 16;

  /**
   * The number of times to roll the edit log during the test. Since this
   * tests for a race condition, higher numbers are more likely to find
   * a bug if it exists, but the test will take longer.
   */
  static final int NUM_ROLLS = 30;

  /**
   * The number of times to save the fsimage and create an empty edit log.
   */
  static final int NUM_SAVE_IMAGE = 30;

  private final List<Transactions> workers = new ArrayList<Transactions>();

  private static final int NUM_DATA_NODES = 1;

  /**
   * Several of the test cases work by introducing a sleep
   * into an operation that is usually fast, and then verifying
   * that another operation blocks for at least this amount of time.
   * This value needs to be significantly longer than the average
   * time for an fsync() or enterSafeMode().
   */
  private static final int BLOCK_TIME = 4; // 4 sec pretty generous

  //
  // an object that does a bunch of transactions
  //
  static class Transactions implements Runnable {
    final NamenodeProtocols nn;
    final MiniDFSCluster cluster;
    FileSystem fs;
    short replication = 3;
    long blockSize = 64;
    volatile boolean stopped = false;
    volatile Thread thr;
    final AtomicReference<Throwable> caught;

    Transactions(MiniDFSCluster cluster, AtomicReference<Throwable> caught) {
      this.cluster = cluster;
      this.nn = cluster.getNameNodeRpc();
      try {
        this.fs = cluster.getFileSystem();
      } catch (IOException e) {
        caught.set(e);
      }
      this.caught = caught;
    }

    // add a bunch of transactions.
    @Override
    public void run() {
      thr = Thread.currentThread();
      FsPermission p = new FsPermission((short)0777);

      int i = 0;
      while (!stopped) {
        try {
          String dirname = "/thr-" + thr.getId() + "-dir-" + i;
          if (i % 2 == 0) {
            Path dirnamePath = new Path(dirname);
            fs.mkdirs(dirnamePath);
            fs.delete(dirnamePath, true);
          } else {
            nn.mkdirs(dirname, p, true);
            nn.delete(dirname, true);
          }
        } catch (SafeModeException sme) {
          // This is OK - the tests will bring NN in and out of safemode
        } catch (Throwable e) {
          // This is OK - the tests will bring NN in and out of safemode
          if (e instanceof RemoteException &&
              ((RemoteException)e).getClassName()
              .contains("SafeModeException")) {
            return;
          }
          LOG.warn("Got error in transaction thread", e);
          caught.compareAndSet(null, e);
          break;
        }
        i++;
      }
    }

    public void stop() {
      stopped = true;
    }

    public Thread getThread() {
      return thr;
    }
  }

  private void startTransactionWorkers(MiniDFSCluster cluster,
                                       AtomicReference<Throwable> caughtErr) {
    // Create threads and make them run transactions concurrently.
    for (int i = 0; i < NUM_THREADS; i++) {
      Transactions trans = new Transactions(cluster, caughtErr);
      new Thread(trans, "TransactionThread-" + i).start();
      workers.add(trans);
    }
  }

  private void stopTransactionWorkers() {
    // wait for all transactions to get over
    for (Transactions worker : workers) {
      worker.stop();
    }

    for (Transactions worker : workers) {
      Thread thr = worker.getThread();
      try {
        if (thr != null) thr.join();
      } catch (InterruptedException ignored) {}
    }
  }

  /**
   * Tests rolling edit logs while transactions are ongoing.
   */
  @Test
  public void testEditLogRolling() throws Exception {
    // start a cluster
    Configuration conf = getConf();
    final MiniDFSCluster cluster =
        new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DATA_NODES).build();
    FileSystem fileSys = null;

    AtomicReference<Throwable> caughtErr = new AtomicReference<Throwable>();
    try {
      cluster.waitActive();
      fileSys = cluster.getFileSystem();
      final NamenodeProtocols nn = cluster.getNameNode().getRpcServer();
      FSImage fsimage = cluster.getNamesystem().getFSImage();
      StorageDirectory sd = fsimage.getStorage().getStorageDir(0);

      startTransactionWorkers(cluster, caughtErr);

      long previousLogTxId = 1;

      for (int i = 0; i < NUM_ROLLS && caughtErr.get() == null; i++) {
        try {
          Thread.sleep(20);
        } catch (InterruptedException e) {}

        LOG.info("Starting roll " + i + ".");
        CheckpointSignature sig = nn.rollEditLog();

        long nextLog = sig.curSegmentTxId;
        String logFileName = NNStorage.getFinalizedEditsFileName(
            previousLogTxId, nextLog - 1);
        previousLogTxId += verifyEditLogs(cluster.getNamesystem(), fsimage,
          logFileName, previousLogTxId);

        assertEquals(previousLogTxId, nextLog);

        File expectedLog = NNStorage.getInProgressEditsFile(sd, previousLogTxId);
        assertTrue("Expect " + expectedLog + " to exist", expectedLog.exists());
      }
    } finally {
      stopTransactionWorkers();
      if (caughtErr.get() != null) {
        throw new RuntimeException(caughtErr.get());
      }

      if(fileSys != null) fileSys.close();
      if(cluster != null) cluster.shutdown();
    }
  }

  private long verifyEditLogs(FSNamesystem namesystem, FSImage fsimage,
                              String logFileName, long startTxId)
    throws IOException {

    long numEdits = -1;

    // Verify that we can read in all the transactions that we have written.
    // If there were any corruptions, it is likely that the reading in
    // of these transactions will throw an exception.
    for (StorageDirectory sd :
      fsimage.getStorage().dirIterable(NameNodeDirType.EDITS)) {

      File editFile = new File(sd.getCurrentDir(), logFileName);

      System.out.println("Verifying file: " + editFile);
      FSEditLogLoader loader = new FSEditLogLoader(namesystem, startTxId);
      long numEditsThisLog = loader.loadFSEdits(
          new EditLogFileInputStream(editFile), startTxId);

      System.out.println("Number of edits: " + numEditsThisLog);
      assertTrue(numEdits == -1 || numEditsThisLog == numEdits);
      numEdits = numEditsThisLog;
    }

    assertTrue(numEdits != -1);
    return numEdits;
  }

  /**
   * Tests saving fs image while transactions are ongoing.
   */
  @Test
  public void testSaveNamespace() throws Exception {
    // start a cluster
    Configuration conf = getConf();
    MiniDFSCluster cluster = null;
    FileSystem fileSys = null;

    AtomicReference<Throwable> caughtErr = new AtomicReference<Throwable>();
    try {
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DATA_NODES).build();
      cluster.waitActive();
      fileSys = cluster.getFileSystem();
      final FSNamesystem namesystem = cluster.getNamesystem();

      FSImage fsimage = namesystem.getFSImage();
      FSEditLog editLog = fsimage.getEditLog();

      startTransactionWorkers(cluster, caughtErr);

      for (int i = 0; i < NUM_SAVE_IMAGE && caughtErr.get() == null; i++) {
        try {
          Thread.sleep(20);
        } catch (InterruptedException ignored) {}

        LOG.info("Save " + i + ": entering safe mode");
        namesystem.enterSafeMode(false);

        // Verify edit logs before the save
        // They should start with the first edit after the checkpoint
        long logStartTxId = fsimage.getStorage().getMostRecentCheckpointTxId() + 1;
        verifyEditLogs(namesystem, fsimage,
            NNStorage.getInProgressEditsFileName(logStartTxId),
            logStartTxId);

        LOG.info("Save " + i + ": saving namespace");
        namesystem.saveNamespace();
        LOG.info("Save " + i + ": leaving safemode");

        long savedImageTxId = fsimage.getStorage().getMostRecentCheckpointTxId();

        // Verify that edit logs post save got finalized and aren't corrupt
        verifyEditLogs(namesystem, fsimage,
            NNStorage.getFinalizedEditsFileName(logStartTxId, savedImageTxId),
            logStartTxId);

        // The checkpoint id should be 1 less than the last written ID, since
        // the log roll writes the "BEGIN" transaction to the new log.
        assertEquals(fsimage.getStorage().getMostRecentCheckpointTxId(),
                     editLog.getLastWrittenTxId() - 1);

        namesystem.leaveSafeMode();
        LOG.info("Save " + i + ": complete");
      }
    } finally {
      stopTransactionWorkers();
      if (caughtErr.get() != null) {
        throw new RuntimeException(caughtErr.get());
      }
      if(fileSys != null) fileSys.close();
      if(cluster != null) cluster.shutdown();
    }
  }

  private Configuration getConf() {
    Configuration conf = new HdfsConfiguration();
    conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_EDITS_ASYNC_LOGGING,
        useAsyncEditLog);
    FileSystem.setDefaultUri(conf, "hdfs://localhost:0");
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "0.0.0.0:0");
    //conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, NAME_DIR);
    //conf.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY, NAME_DIR);
    conf.setBoolean(DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY, false);
    return conf;
  }

  /**
   * The logSync() method in FSEditLog is unsynchronized whiel syncing
   * so that other threads can concurrently enqueue edits while the prior
   * sync is ongoing. This test checks that the log is saved correctly
   * if the saveImage occurs while the syncing thread is in the unsynchronized middle section.
   *
   * This replicates the following manual test proposed by Konstantin:
   *   I start the name-node in debugger.
   *   I do -mkdir and stop the debugger in logSync() just before it does flush.
   *   Then I enter safe mode with another client
   *   I start saveNamepsace and stop the debugger in
   *     FSImage.saveFSImage() -> FSEditLog.createEditLogFile()
   *     -> EditLogFileOutputStream.create() ->
   *     after truncating the file but before writing LAYOUT_VERSION into it.
   *   Then I let logSync() run.
   *   Then I terminate the name-node.
   *   After that the name-node wont start, since the edits file is broken.
   */
  @Test
  public void testSaveImageWhileSyncInProgress() throws Exception {
    Configuration conf = getConf();
    NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
    DFSTestUtil.formatNameNode(conf);
    final FSNamesystem namesystem = FSNamesystem.loadFromDisk(conf);

    try {
      FSImage fsimage = namesystem.getFSImage();
      FSEditLog editLog = fsimage.getEditLog();

      JournalAndStream jas = editLog.getJournals().get(0);
      EditLogFileOutputStream spyElos =
          spy((EditLogFileOutputStream)jas.getCurrentStream());
      jas.setCurrentStreamForTests(spyElos);

      final AtomicReference<Throwable> deferredException =
          new AtomicReference<Throwable>();
      final CountDownLatch waitToEnterFlush = new CountDownLatch(1);

      final Thread doAnEditThread = new Thread() {
        @Override
        public void run() {
          try {
            LOG.info("Starting mkdirs");
            namesystem.mkdirs("/test",
                new PermissionStatus("test","test", new FsPermission((short)00755)),
                true);
            LOG.info("mkdirs complete");
          } catch (Throwable ioe) {
            LOG.fatal("Got exception", ioe);
            deferredException.set(ioe);
            waitToEnterFlush.countDown();
          }
        }
      };

      Answer<Void> blockingFlush = new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
          LOG.info("Flush called");
          if (useAsyncEditLog || Thread.currentThread() == doAnEditThread) {
            LOG.info("edit thread: Telling main thread we made it to flush section...");
            // Signal to main thread that the edit thread is in the racy section
            waitToEnterFlush.countDown();
            LOG.info("edit thread: sleeping for " + BLOCK_TIME + "secs");
            Thread.sleep(BLOCK_TIME*1000);
            LOG.info("Going through to flush. This will allow the main thread to continue.");
          }
          invocation.callRealMethod();
          LOG.info("Flush complete");
          return null;
        }
      };
      doAnswer(blockingFlush).when(spyElos).flush();

      doAnEditThread.start();
      // Wait for the edit thread to get to the logsync unsynchronized section
      LOG.info("Main thread: waiting to enter flush...");
      waitToEnterFlush.await();
      assertNull(deferredException.get());
      LOG.info("Main thread: detected that logSync is in unsynchronized section.");
      LOG.info("Trying to enter safe mode.");
      LOG.info("This should block for " + BLOCK_TIME + "sec, since flush will sleep that long");

      long st = Time.now();
      namesystem.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
      long et = Time.now();
      LOG.info("Entered safe mode");
      // Make sure we really waited for the flush to complete!
      assertTrue(et - st > (BLOCK_TIME - 1)*1000);

      // Once we're in safe mode, save namespace.
      namesystem.saveNamespace();

      LOG.info("Joining on edit thread...");
      doAnEditThread.join();
      assertNull(deferredException.get());

      // We did 3 edits: begin, txn, and end
      assertEquals(3, verifyEditLogs(namesystem, fsimage,
          NNStorage.getFinalizedEditsFileName(1, 3),
          1));
      // after the save, just the one "begin"
      assertEquals(1, verifyEditLogs(namesystem, fsimage,
          NNStorage.getInProgressEditsFileName(4),
          4));
    } finally {
      LOG.info("Closing nn");
      if(namesystem != null) namesystem.close();
    }
  }

  /**
   * Most of the FSNamesystem methods have a synchronized section where they
   * update the name system itself and write to the edit log, and then
   * unsynchronized, they call logSync. This test verifies that, if an
   * operation has written to the edit log but not yet synced it,
   * we wait for that sync before entering safe mode.
   */
  @Test
  public void testSaveRightBeforeSync() throws Exception {
    Configuration conf = getConf();
    NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
    DFSTestUtil.formatNameNode(conf);
    final FSNamesystem namesystem = FSNamesystem.loadFromDisk(conf);

    try {
      FSImage fsimage = namesystem.getFSImage();
      final FSEditLog editLog = fsimage.getEditLog();

      final AtomicReference<Throwable> deferredException =
          new AtomicReference<Throwable>();
      final CountDownLatch sleepingBeforeSync = new CountDownLatch(1);

      final Thread doAnEditThread = new Thread() {
        @Override
        public void run() {
          try {
            LOG.info("Starting setOwner");
            namesystem.writeLock();
            try {
              editLog.logSetOwner("/","test","test");
            } finally {
              namesystem.writeUnlock();
            }
            sleepingBeforeSync.countDown();
            LOG.info("edit thread: sleeping for " + BLOCK_TIME + "secs");
            Thread.sleep(BLOCK_TIME*1000);
            editLog.logSync();
            LOG.info("edit thread: logSync complete");
          } catch (Throwable ioe) {
            LOG.fatal("Got exception", ioe);
            deferredException.set(ioe);
            sleepingBeforeSync.countDown();
          }
        }
      };
      doAnEditThread.setDaemon(true);
      doAnEditThread.start();
      LOG.info("Main thread: waiting to just before logSync...");
      sleepingBeforeSync.await(200, TimeUnit.MILLISECONDS);
      assertNull(deferredException.get());
      LOG.info("Main thread: detected that logSync about to be called.");
      LOG.info("Trying to enter safe mode.");

      long st = Time.now();
      namesystem.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
      long et = Time.now();
      LOG.info("Entered safe mode after "+(et-st)+"ms");

      // Make sure we didn't wait for the thread that did a logEdit but
      // not logSync.  Going into safemode does a logSyncAll that will flush
      // its edit.
      assertTrue(et - st < (BLOCK_TIME/2)*1000);

      // Once we're in safe mode, save namespace.
      namesystem.saveNamespace();

      LOG.info("Joining on edit thread...");
      doAnEditThread.join();
      assertNull(deferredException.get());

      // We did 3 edits: begin, txn, and end
      assertEquals(3, verifyEditLogs(namesystem, fsimage,
          NNStorage.getFinalizedEditsFileName(1, 3),
          1));
      // after the save, just the one "begin"
      assertEquals(1, verifyEditLogs(namesystem, fsimage,
          NNStorage.getInProgressEditsFileName(4),
          4));
    } finally {
      LOG.info("Closing nn");
      if(namesystem != null) namesystem.close();
    }
  }
}


text:
#include "EfiShellLib.h"
#include "mm.h"

extern UINT8  STRING_ARRAY_NAME[];

//
// This is the generated header file which includes whatever needs to be exported (strings + IFR)
//
#include STRING_DEFINES_FILE

#include EFI_PROTOCOL_DEFINITION (PciRootBridgeIo)

typedef enum {
  EfiMemory,
  EFIMemoryMappedIo,
  EfiIo,
  EfiPciConfig,
  EfiPciEConfig
} EFI_ACCESS_TYPE;

EFI_STATUS
DumpIoModify (
  IN EFI_HANDLE           ImageHandle,
  IN EFI_SYSTEM_TABLE     *SystemTable
  );

VOID
ReadMem (
  IN  EFI_IO_WIDTH  Width,
  IN  UINT64        Address,
  IN  UINTN         Size,
  IN  VOID          *Buffer
  );

VOID
WriteMem (
  IN  EFI_IO_WIDTH  Width,
  IN  UINT64        Address,
  IN  UINTN         Size,
  IN  VOID          *Buffer
  );

STATIC
BOOLEAN
GetHex (
  IN  UINT16  *str,
  OUT UINT64  *data
  );

//
// Global Variables
//
EFI_HII_HANDLE HiiHandle;
EFI_GUID EfiIomodGuid = EFI_IOMOD_GUID;
SHELL_VAR_CHECK_ITEM    IomodCheckList[] = {
  {
    L"-MMIO",
    0x01,
    0x10E,
    FlagTypeSingle
  },
  {
    L"-MEM",
    0x02,
    0x10D,
    FlagTypeSingle
  },
  {
    L"-IO",
    0x04,
    0x10B,
    FlagTypeSingle
  },
  {
    L"-PCI",
    0x08,
    0x107,
    FlagTypeSingle
  },
  {
    L"-PCIE",
    0x100,
    0x0F,
    FlagTypeSingle
  },
  {
    L"-w",
    0x10,
    0,
    FlagTypeNeedVar
  },
  {
    L"-n",
    0x20,
    0,
    FlagTypeSingle
  },
  {
    L"-b",
    0x40,
    0,
    FlagTypeSingle
  },
  {
    L"-?",
    0x80,
    0,
    FlagTypeSingle
  },
  {
    NULL,
    0,
    0,
    0
  }
};

UINT64 MaxNum[9]      = { 0xff, 0xffff, 0xffffffff, 0xffffffffffffffff };

EFI_BOOTSHELL_CODE(
  EFI_APPLICATION_ENTRY_POINT(DumpIoModify)
)

EFI_STATUS
OldShellParserMM (
  OUT EFI_IO_WIDTH       *Width,
  OUT EFI_ACCESS_TYPE    *AccessType,
  OUT UINT64             *Address,
  OUT UINT64             *Value,
  OUT UINTN              *Size,
  OUT BOOLEAN            *Interactive,
  OUT CHAR16             **ValueStr
  );

EFI_STATUS
GetPciEAddressFromInputAddress (
  IN UINT64                 InputAddress,
  OUT UINT64                *PciEAddress
  );

EFI_STATUS
DumpIoModify (
  IN EFI_HANDLE           ImageHandle,
  IN EFI_SYSTEM_TABLE     *SystemTable
  )
/*++

Routine Description:
  Dump or modify MEM/IO/PCI/MMIO.

Arguments:
  ImageHandle     The image handle.
  SystemTable     The system table.

Returns:
  EFI_SUCCESS             - Command completed successfully
  EFI_INVALID_PARAMETER   - Command usage error

Notes:
  For Shell Mode 1.1.1:
  MM Address [Width] [;[MEM | MMIO | IO | PCI]] [:Value]
    1|2|4|8 supported byte widths - Default is 1 byte.
    ;MEM = Memory,
    ;MMIO = Memory Mapped IO,
    ;IO = in/out,
    ;PCI = PCI Config space (format: 000000ssbbddffrr)
    Default access type is memory (MEM)

  For Shell Mode 1.1.2:
    MM Address [Width] [-[MEM | MMIO | IO | PCI | PCIE]] [:Value]
    1|2|4|8 supported byte widths - Default is 1 byte.
    -MEM = Memory,
    -MMIO = Memory Mapped IO,
    -IO = in/out,
    -PCI = PCI Config space (format: 000000ssbbddffrr)
    -PCIE = PCIE Config space (format: 000000ssbbddffrrr)
    Default access type is memory (MEM)

--*/
{
  EFI_STATUS                      Status;
  EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *IoDev;
  UINT64                          Address;
  UINT64                          PciEAddress;
  UINT64                          Value;
  UINT32                          SegmentNumber;
  EFI_IO_WIDTH                    Width;
  EFI_ACCESS_TYPE                 AccessType;
  UINT64                          Buffer;
  UINTN                           Index;
  UINTN                           Size;
  CHAR16                          *AddressStr;
  CHAR16                          *ValueStr;
  BOOLEAN                         Complete;
  CHAR16                          InputStr[80];
  BOOLEAN                         Interactive;
  EFI_HANDLE                      *HandleBuffer;
  UINTN                           BufferSize;

  SHELL_VAR_CHECK_CODE            RetCode;
  CHAR16                          *Useful;
  SHELL_ARG_LIST                  *Item;
  UINTN                           ItemValue;
  SHELL_VAR_CHECK_PACKAGE         ChkPck;

  Address       = 0;
  PciEAddress   = 0;
  IoDev         = NULL;
  HandleBuffer  = NULL;
  BufferSize    = 0;
  SegmentNumber = 0;
  ZeroMem (&ChkPck, sizeof (SHELL_VAR_CHECK_PACKAGE));

  EFI_SHELL_APP_INIT (ImageHandle, SystemTable);

  //
  // Enable tab key which can pause the output
  //
  EnableOutputTabPause();

  Status = LibInitializeStrings (&HiiHandle, STRING_ARRAY_NAME, &EfiIomodGuid);

  if (EFI_ERROR (Status)) {
    return Status;
  }

  if (!EFI_PROPER_VERSION (1, 10)) {
    PrintToken (
      STRING_TOKEN (STR_SHELLENV_GNC_COMMAND_NOT_SUPPORT),
      HiiHandle,
      L"mm",
      EFI_VERSION_1_10
      );
    Status = EFI_UNSUPPORTED;
    goto Done;
  }

  if (IS_OLD_SHELL) {
    Status = OldShellParserMM (&Width, &AccessType, &Address, &Value, &Size, &Interactive, &ValueStr);
    if (EFI_ERROR (Status)) {
      if (-1 == Status) {
        PrintToken (STRING_TOKEN (STR_HELPINFO_MM_VERBOSEHELP), HiiHandle);
        Status = EFI_SUCCESS;
      }
      goto Done;
    }
  } else {
    //
    // Parse arguments
    //
    Width       = EfiPciWidthUint8;
    Size        = 1;
    AccessType  = EfiMemory;
    AddressStr  = NULL;
    ValueStr    = NULL;
    Interactive = TRUE;

    RetCode     = LibCheckVariables (SI, IomodCheckList, &ChkPck, &Useful);
    if (VarCheckOk != RetCode) {
      switch (RetCode) {
      case VarCheckUnknown:
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_UNKNOWN_FLAG), HiiHandle, L"mm", Useful);
        break;

      case VarCheckConflict:
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_FLAG_CONFLICT), HiiHandle, L"mm", Useful);
        break;

      case VarCheckDuplicate:
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_DUP_FLAG), HiiHandle, L"mm", Useful);
        break;

      case VarCheckLackValue:
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_LACK_ARG), HiiHandle, L"mm", Useful);
        break;

      default:
        break;
      }

      Status = EFI_INVALID_PARAMETER;
      goto Done;
    }
    //
    // Out put help.
    //
    if (LibCheckVarGetFlag (&ChkPck, L"-b") != NULL) {
      EnablePageBreak (DEFAULT_INIT_ROW, DEFAULT_AUTO_LF);
    }

    if (LibCheckVarGetFlag (&ChkPck, L"-?") != NULL) {
      if (ChkPck.ValueCount > 0 ||
          ChkPck.FlagCount > 2 ||
          (2 == ChkPck.FlagCount && !LibCheckVarGetFlag (&ChkPck, L"-b"))
          ) {
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_MANY), HiiHandle, L"mv");
        Status = EFI_INVALID_PARAMETER;
      } else {
        PrintToken (STRING_TOKEN (STR_HELPINFO_MM_VERBOSEHELP), HiiHandle);
        Status = EFI_SUCCESS;
      }
      goto Done;
    }

    if (ChkPck.ValueCount < 1) {
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_FEW), HiiHandle, L"mm");
      Status = EFI_INVALID_PARAMETER;
      goto Done;
    }

    if (ChkPck.ValueCount > 2) {
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_MANY), HiiHandle, L"mm");
      Status = EFI_INVALID_PARAMETER;
      goto Done;
    }

    if (LibCheckVarGetFlag (&ChkPck, L"-MMIO") != NULL) {
      AccessType = EFIMemoryMappedIo;
    } else if (LibCheckVarGetFlag (&ChkPck, L"-MEM") != NULL) {
      AccessType = EfiMemory;
    } else if (LibCheckVarGetFlag (&ChkPck, L"-IO") != NULL) {
      AccessType = EfiIo;
    } else if (LibCheckVarGetFlag (&ChkPck, L"-PCI") != NULL) {
      AccessType = EfiPciConfig;
    } else if (LibCheckVarGetFlag (&ChkPck, L"-PCIE") != NULL) {
      AccessType = EfiPciEConfig;
    }

    if (LibCheckVarGetFlag (&ChkPck, L"-n") != NULL) {
      Interactive = FALSE;
    }

    Item = LibCheckVarGetFlag (&ChkPck, L"-w");
    if (NULL != Item) {
      ItemValue = (UINTN) StrToUInteger (Item->VarStr, &Status);
      if (EFI_ERROR (Status)) {
        PrintToken (STRING_TOKEN (STR_IOMOD_INVALID_WIDTH), HiiHandle, L"mm");
        Status = EFI_INVALID_PARAMETER;
        goto Done;
      }

      switch (ItemValue) {
      case 1:
        Width = EfiPciWidthUint8;
        Size  = 1;
        break;

      case 2:
        Width = EfiPciWidthUint16;
        Size  = 2;
        break;

      case 4:
        Width = EfiPciWidthUint32;
        Size  = 4;
        break;

      case 8:
        Width = EfiPciWidthUint64;
        Size  = 8;
        break;

      default:
        PrintToken (STRING_TOKEN (STR_IOMOD_INVALID_WIDTH), HiiHandle, L"mm");
        Status = EFI_INVALID_PARAMETER;
        goto Done;
      }
    }

    Item = ChkPck.VarList;
    if (NULL != Item) {
      Address = (UINT64) (StrToUIntegerBase (Item->VarStr, 16, &Status));
      if (EFI_ERROR (Status)) {
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_INVALID_ARG), HiiHandle, L"mm", Item->VarStr);
        Status = EFI_INVALID_PARAMETER;
        goto Done;
      }

      Item = Item->Next;
    }

    if (NULL != Item) {
      Value = (UINT64) (StrToUIntegerBase (Item->VarStr, 16, &Status));
      if (EFI_ERROR (Status)) {
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_INVALID_ARG), HiiHandle, L"mm", Item->VarStr);
        Status = EFI_INVALID_PARAMETER;
        goto Done;
      } else {
        switch (Size) {
        case 1:
          if (Value > 0xFF) {
            Status = EFI_INVALID_PARAMETER;
          }
          break;

        case 2:
          if (Value > 0xFFFF) {
            Status = EFI_INVALID_PARAMETER;
          }
          break;

        case 4:
          if (Value > 0xFFFFFFFF) {
            Status = EFI_INVALID_PARAMETER;
          }
          break;

        default:
          break;
        }
      }

      if (EFI_ERROR (Status)) {
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_INVALID_ARG), HiiHandle, L"mm", Item->VarStr);
        Status = EFI_INVALID_PARAMETER;
        goto Done;
      }

      ValueStr = Item->VarStr;
    }
  }

  if ((Address & (Size - 1)) != 0) {
    PrintToken (STRING_TOKEN (STR_IOMOD_ADDRESS_NOT_ALIGNED), HiiHandle, L"mm", (UINTN) Address, Size);
    Status = EFI_INVALID_PARAMETER;
    goto Done;
  }
  //
  // locate DeviceIO protocol interface
  //
  if (AccessType != EfiMemory) {
    Status = LibLocateHandle (
               ByProtocol,
               &gEfiPciRootBridgeIoProtocolGuid,
               NULL,
               &BufferSize,
               &HandleBuffer
               );
    if (EFI_ERROR (Status)) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HANDLE_PCI), HiiHandle, L"mm", Status);
      goto Done;
    }
    //
    // In the case of PCI or PCIE
    // Get segment number and mask the segment bits in Address
    //
    if (AccessType == EfiPciEConfig) {
      SegmentNumber = (UINT32) RShiftU64 (Address, 36) & 0xff;
      Address      &= 0xfffffffff;
    } else {
      if (AccessType == EfiPciConfig) {
        SegmentNumber = (UINT32) RShiftU64 (Address, 32) & 0xff;
        Address      &= 0xffffffff;
      }
    }
    //
    // Find the EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL of the specified segment number
    //
    for (Index = 0; Index < BufferSize; Index++) {
      Status = BS->HandleProtocol (
                     HandleBuffer[Index],
                     &gEfiPciRootBridgeIoProtocolGuid,
                     (VOID *) &IoDev
                     );
      if (EFI_ERROR (Status)) {
        continue;
      }
      if (IoDev->SegmentNumber != SegmentNumber) {
        IoDev = NULL;
      }
    }
    if (IoDev == NULL) {
      // TODO add token
      PrintToken (STRING_TOKEN (STR_IOMOD_SEGMENT_NOT_FOUND), HiiHandle, SegmentNumber);
      Status = EFI_INVALID_PARAMETER;
      goto Done;
    }
  }

  if (AccessType == EfiIo && Address + Size > 0x10000) {
    PrintToken (STRING_TOKEN (STR_IOMOD_IO_ADDRESS), HiiHandle, L"mm");
    Status = EFI_INVALID_PARAMETER;
    goto Done;
  }

  if (AccessType == EfiPciEConfig) {
    GetPciEAddressFromInputAddress (Address, &PciEAddress);
  }

  //
  // Set value
  //
  if (ValueStr) {
    if (AccessType == EFIMemoryMappedIo) {
      IoDev->Mem.Write (IoDev, Width, Address, 1, &Value);
    } else if (AccessType == EfiIo) {
      IoDev->Io.Write (IoDev, Width, Address, 1, &Value);
    } else if (AccessType == EfiPciConfig) {
      IoDev->Pci.Write (IoDev, Width, Address, 1, &Value);
    } else if (AccessType == EfiPciEConfig) {
      IoDev->Pci.Write (IoDev, Width, PciEAddress, 1, &Buffer);
    } else {
      WriteMem (Width, Address, 1, &Value);
    }

    Status = EFI_SUCCESS;
    goto Done;
  }
  //
  // non-interactive mode
  //
  if (Interactive == FALSE) {
    Buffer = 0;
    if (AccessType == EFIMemoryMappedIo) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HMMIO), HiiHandle);
      IoDev->Mem.Read (IoDev, Width, Address, 1, &Buffer);
    } else if (AccessType == EfiIo) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HIO), HiiHandle);
      IoDev->Io.Read (IoDev, Width, Address, 1, &Buffer);
    } else if (AccessType == EfiPciConfig) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HPCI), HiiHandle);
      IoDev->Pci.Read (IoDev, Width, Address, 1, &Buffer);
    } else if (AccessType == EfiPciEConfig) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HPCIE), HiiHandle);
      IoDev->Pci.Read (IoDev, Width, PciEAddress, 1, &Buffer);
    } else {
      PrintToken (STRING_TOKEN (STR_IOMOD_HMEM), HiiHandle);
      ReadMem (Width, Address, 1, &Buffer);
    }

    PrintToken (STRING_TOKEN (STR_IOMOD_ADDRESS), HiiHandle, Address);
    if (Size == 1) {
      PrintToken (STRING_TOKEN (STR_IOMOD_BUFFER_2), HiiHandle, Buffer);
    } else if (Size == 2) {
      PrintToken (STRING_TOKEN (STR_IOMOD_BUFFER_4), HiiHandle, Buffer);
    } else if (Size == 4) {
      PrintToken (STRING_TOKEN (STR_IOMOD_BUFFER_8), HiiHandle, Buffer);
    } else if (Size == 8) {
      PrintToken (STRING_TOKEN (STR_IOMOD_BUFFER_16), HiiHandle, Buffer);
    }

    Print (L"\n");
    Status = EFI_SUCCESS;
    goto Done;
  }
  //
  // interactive mode
  //
  Complete = FALSE;
  do {
    if (AccessType == EfiIo && Address + Size > 0x10000) {
      PrintToken (STRING_TOKEN (STR_IOMOD_IO_ADDRESS_2), HiiHandle, L"mm");
      break;
    }

    Buffer = 0;
    if (AccessType == EFIMemoryMappedIo) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HMMIO), HiiHandle);
      IoDev->Mem.Read (IoDev, Width, Address, 1, &Buffer);
    } else if (AccessType == EfiIo) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HIO), HiiHandle);
      IoDev->Io.Read (IoDev, Width, Address, 1, &Buffer);
    } else if (AccessType == EfiPciConfig) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HPCI), HiiHandle);
      IoDev->Pci.Read (IoDev, Width, Address, 1, &Buffer);
    } else if (AccessType == EfiPciEConfig) {
      PrintToken (STRING_TOKEN (STR_IOMOD_HPCIE), HiiHandle);
      IoDev->Pci.Read (IoDev, Width, PciEAddress, 1, &Buffer);
    } else {
      PrintToken (STRING_TOKEN (STR_IOMOD_HMEM), HiiHandle);
      ReadMem (Width, Address, 1, &Buffer);
    }

    PrintToken (STRING_TOKEN (STR_IOMOD_ADDRESS), HiiHandle, Address);

    if (Size == 1) {
      PrintToken (STRING_TOKEN (STR_IOMOD_BUFFER_2), HiiHandle, Buffer);
    } else if (Size == 2) {
      PrintToken (STRING_TOKEN (STR_IOMOD_BUFFER_4), HiiHandle, Buffer);
    } else if (Size == 4) {
      PrintToken (STRING_TOKEN (STR_IOMOD_BUFFER_8), HiiHandle, Buffer);
    } else if (Size == 8) {
      PrintToken (STRING_TOKEN (STR_IOMOD_BUFFER_16), HiiHandle, Buffer);
    }
    //
    // wait user input to modify
    //
    Input (L" > ", InputStr, sizeof (InputStr) / sizeof (CHAR16));

    //
    // skip space characters
    //
    for (Index = 0; InputStr[Index] == ' '; Index++)
      ;

    //
    // parse input string
    //
    if (InputStr[Index] == '.' || InputStr[Index] == 'q' || InputStr[Index] == 'Q') {
      Complete = TRUE;
    } else if (InputStr[Index] == CHAR_NULL) {
      //
      // Continue to next address
      //
    } else if (GetHex (InputStr + Index, &Buffer) && Buffer <= MaxNum[Width]) {
      if (AccessType == EFIMemoryMappedIo) {
        IoDev->Mem.Write (IoDev, Width, Address, 1, &Buffer);
      } else if (AccessType == EfiIo) {
        IoDev->Io.Write (IoDev, Width, Address, 1, &Buffer);
      } else if (AccessType == EfiPciConfig) {
        IoDev->Pci.Write (IoDev, Width, Address, 1, &Buffer);
      } else if (AccessType == EfiPciEConfig) {
        IoDev->Pci.Write (IoDev, Width, PciEAddress, 1, &Buffer);
      } else {
        WriteMem (Width, Address, 1, &Buffer);
      }
    } else {
      PrintToken (STRING_TOKEN (STR_IOMOD_ERROR), HiiHandle);
      continue;
    }

    Address += Size;
    if (AccessType == EfiPciEConfig) {
      GetPciEAddressFromInputAddress (Address, &PciEAddress);
    }
    Print (L"\n");
  } while (!Complete);

  Status = EFI_SUCCESS;
Done:

  if (HandleBuffer != NULL) {
    FreePool (HandleBuffer);
  }
  LibCheckVarFreeVarList (&ChkPck);
  LibUnInitializeStrings ();
  return Status;
}

VOID
ReadMem (
  IN  EFI_IO_WIDTH  Width,
  IN  UINT64        Address,
  IN  UINTN         Size,
  IN  VOID          *Buffer
  )
{
  do {
    if (Width == EfiPciWidthUint8) {
      *(UINT8 *) Buffer = *(UINT8 *) (UINTN) Address;
      Address -= 1;
    } else if (Width == EfiPciWidthUint16) {
      *(UINT16 *) Buffer = *(UINT16 *) (UINTN) Address;
      Address -= 2;
    } else if (Width == EfiPciWidthUint32) {
      *(UINT32 *) Buffer = *(UINT32 *) (UINTN) Address;
      Address -= 4;
    } else if (Width == EfiPciWidthUint64) {
      *(UINT64 *) Buffer = *(UINT64 *) (UINTN) Address;
      Address -= 8;
    } else {
      PrintToken (STRING_TOKEN (STR_IOMOD_READ_MEM_ERROR), HiiHandle);
      break;
    }
    //
    //
    //
    Size--;
  } while (Size > 0);
}

VOID
WriteMem (
  IN  EFI_IO_WIDTH  Width,
  IN  UINT64        Address,
  IN  UINTN         Size,
  IN  VOID          *Buffer
  )
{
  do {
    if (Width == EfiPciWidthUint8) {
      *(UINT8 *) (UINTN) Address = *(UINT8 *) Buffer;
      Address += 1;
    } else if (Width == EfiPciWidthUint16) {
      *(UINT16 *) (UINTN) Address = *(UINT16 *) Buffer;
      Address += 2;
    } else if (Width == EfiPciWidthUint32) {
      *(UINT32 *) (UINTN) Address = *(UINT32 *) Buffer;
      Address += 4;
    } else if (Width == EfiPciWidthUint64) {
      *(UINT64 *) (UINTN) Address = *(UINT64 *) Buffer;
      Address += 8;
    } else {
      ASSERT (FALSE);
    }
    //
    //
    //
    Size--;
  } while (Size > 0);
}

STATIC
BOOLEAN
GetHex (
  IN  UINT16  *str,
  OUT UINT64  *data
  )
{
  UINTN   u;
  CHAR16  c;
  BOOLEAN Find;

  Find = FALSE;
  //
  // convert hex digits
  //
  u = 0;
  c = *(str++);
  while (c) {
    if (c >= 'a' && c <= 'f') {
      c -= 'a' - 'A';
    }

    if (c == ' ') {
      break;
    }

    if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
      u     = u << 4 | c - (c >= 'A' ? 'A' - 10 : '0');

      Find  = TRUE;
    } else {
      return FALSE;
    }

    c = *(str++);
  }

  *data = u;
  return Find;
}

EFI_STATUS
OldShellParserMM (
  OUT EFI_IO_WIDTH       *Width,
  OUT EFI_ACCESS_TYPE    *AccessType,
  OUT UINT64             *Address,
  OUT UINT64             *Value,
  OUT UINTN              *Size,
  OUT BOOLEAN            *Interactive,
  OUT CHAR16             **ValueStr
  )
/*++

Routine Description:

  Parse the command line with old shell command grammar

Arguments:

  Width              - The memory width
  AccessType         - The memory access type
  Address            - The memory address
  Value              - The memory value
  Size               - The memory size
  Interactive        - Interactive
  ValueStr           - The value string

Returns:

  EFI_SUCCESS   - Success

--*/
{
  CHAR16  *AddressStr;
  CHAR16  *WidthStr;
  CHAR16  *Ptr;
  UINTN   Index;
  BOOLEAN PrtHelp;
  //
  // Parse arguments
  //
  *Width                = EfiPciWidthUint8;
  *Size                 = 1;
  *AccessType           = EfiMemory;
  AddressStr            = WidthStr = NULL;
  *ValueStr             = NULL;
  *Interactive          = TRUE;
  PrtHelp               = FALSE;
  for (Index = 1; Index < SI->Argc; Index += 1) {
    Ptr = SI->Argv[Index];
    //
    // access type
    //
    if (*Ptr == L';') {
      if (StriCmp (Ptr, L";IO") == 0) {
        *AccessType = EfiIo;
        continue;
      } else if (StriCmp (Ptr, L";PCI") == 0) {
        *AccessType = EfiPciConfig;
        continue;
      } else if (StriCmp (Ptr, L";MEM") == 0) {
        *AccessType = EfiMemory;
        continue;
      } else if (StriCmp (Ptr, L";MMIO") == 0) {
        *AccessType = EFIMemoryMappedIo;
        continue;
      } else {
        PrintToken (STRING_TOKEN (STR_IOMOD_UNKNOWN_ACCESS), HiiHandle, L"mm", Ptr);
        return EFI_INVALID_PARAMETER;
      }
    } else if (*Ptr == ':') {
      //
      // value
      //
      *ValueStr = &Ptr[1];
      *Value    = Xtoi (*ValueStr);
      continue;
    } else if (*Ptr == '-') {
      //
      // command option switch
      //
      switch (Ptr[1]) {
      case 'n':
      case 'N':
        *Interactive = FALSE;
        break;

      case '?':
        PrtHelp = TRUE;
        break;

      case 'b':
      case 'B':
        EnablePageBreak (DEFAULT_INIT_ROW, DEFAULT_AUTO_LF);
        break;

      default:
        PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_UNKNOWN_FLAG), HiiHandle, L"mm", Ptr);
        return EFI_INVALID_PARAMETER;
      };
      continue;
    }

    //
    // Start Address
    //
    if (!AddressStr) {
      AddressStr  = Ptr;
      *Address    = Xtoi (AddressStr);
      continue;
    }
    //
    // access width
    //
    if (!WidthStr) {
      WidthStr = Ptr;
      switch (Xtoi (WidthStr)) {
      case 1:
        *Width  = EfiPciWidthUint8;
        *Size   = 1;
        continue;

      case 2:
        *Width  = EfiPciWidthUint16;
        *Size   = 2;
        continue;

      case 4:
        *Width  = EfiPciWidthUint32;
        *Size   = 4;
        continue;

      case 8:
        *Width  = EfiPciWidthUint64;
        *Size   = 8;
        continue;

      default:
        PrintToken (STRING_TOKEN (STR_IOMOD_INVALID_WIDTH), HiiHandle, L"mm");
        return EFI_INVALID_PARAMETER;
      }
    }
  }

  if (PrtHelp) {
    return (EFI_STATUS) -1;
  }

  return EFI_SUCCESS;
}

EFI_STATUS
InitializeMMGetLineHelp (
  OUT CHAR16              **Str
  )
/*++

Routine Description:

  Get this command's line help

Arguments:

  Str - The line help

Returns:

  EFI_SUCCESS   - Success

--*/
{
  return LibCmdGetStringByToken (
          STRING_ARRAY_NAME,
          &EfiIomodGuid,
          STRING_TOKEN (STR_HELPINFO_MM_LINEHELP),
          Str
          );
}

EFI_STATUS
GetPciEAddressFromInputAddress (
  IN UINT64                 InputAddress,
  OUT UINT64                *PciEAddress
  )
/*++

Routine Description:

  Get the PCI-E Address from a PCI address format 0x0000ssbbddffrrr
  where ss is SEGMENT, bb is BUS, dd is DEVICE, ff is FUNCTION
  and rrr is REGISTER (extension format for PCI-E)

Arguments:

  InputAddress - PCI address format on input
  PciEAddress  - PCI-E address extention format

Returns:

  EFI_SUCCESS   - Success

--*/
{
  *PciEAddress = RShiftU64(InputAddress & ~(UINT64) 0xFFF, 4) +
    LShiftU64((UINT16) InputAddress & 0x0FFF, 32);
  return EFI_SUCCESS;
}


text:
package com.graphhopper.routing;

import com.graphhopper.routing.util.AlgorithmPreparation;
import com.graphhopper.routing.util.EdgeFilter;
import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.routing.util.NoOpAlgorithmPreparation;
import com.graphhopper.routing.util.Weighting;
import com.graphhopper.storage.Graph;
import com.graphhopper.storage.GraphBuilder;
import com.graphhopper.util.EdgeIteratorState;
import com.graphhopper.util.Helper;
import static org.junit.Assert.*;
import org.junit.Test;

/**
 *
 * @author Peter Karich
 */
public class DijkstraOneToManyTest extends AbstractRoutingAlgorithmTester
{
    @Override
    public AlgorithmPreparation prepareGraph( Graph defaultGraph, final FlagEncoder encoder, final Weighting w )
    {
        return new NoOpAlgorithmPreparation()
        {
            @Override
            public RoutingAlgorithm createAlgo()
            {
                return new DijkstraOneToMany(_graph, encoder, w);
            }
        }.setGraph(defaultGraph);
    }

    @Override
    public void testViaEdges_BiGraph()
    {
        // calcPath with QueryResult not supported
    }

    @Override
    public void testViaEdges_SpecialCases()
    {
        // calcPath with QueryResult not supported
    }

    @Override
    public void testViaEdges_FromEqualsTo()
    {
        // calcPath with QueryResult not supported
    }

    @Override
    public void testViaEdges_WithCoordinates()
    {
        // calcPath with QueryResult not supported
    }

    @Override
    public void testQueryGraphAndFastest()
    {
        // calcPath with QueryResult not supported
    }

    @Override
    public void testTwoWeightsPerEdge2()
    {
        // calcPath with QueryResult not supported
    }

    @Test
    public void testIssue182()
    {
        AlgorithmPreparation prep = prepareGraph(initGraph(createGraph(false)));
        RoutingAlgorithm algo = prep.createAlgo();
        Path p = algo.calcPath(0, 8);
        assertEquals(Helper.createTList(0, 7, 8), p.calcNodes());

        // expand SPT
        p = algo.calcPath(0, 10);
        assertEquals(Helper.createTList(0, 1, 2, 3, 4, 10), p.calcNodes());
    }

    @Test
    public void testIssue239()
    {
        Graph g = createGraph(false);
        g.edge(0, 1, 1, true);
        g.edge(1, 2, 1, true);
        g.edge(2, 0, 1, true);

        g.edge(4, 5, 1, true);
        g.edge(5, 6, 1, true);
        g.edge(6, 4, 1, true);

        AlgorithmPreparation prep = prepareGraph(g);
        DijkstraOneToMany algo = (DijkstraOneToMany) prep.createAlgo();
        assertEquals(-1, algo.findEndNode(0, 4));
        assertEquals(-1, algo.findEndNode(0, 4));
    }

    @Test
    public void testUseCache()
    {
        AlgorithmPreparation prep = prepareGraph(createTestGraph());
        RoutingAlgorithm algo = prep.createAlgo();
        Path p = algo.calcPath(0, 4);
        assertEquals(Helper.createTList(0, 4), p.calcNodes());

        // expand SPT
        p = algo.calcPath(0, 7);
        assertEquals(Helper.createTList(0, 4, 6, 5, 7), p.calcNodes());

        // use SPT
        p = algo.calcPath(0, 2);
        assertEquals(Helper.createTList(0, 1, 2), p.calcNodes());
    }

    @Test
    public void testDifferentEdgeFilter()
    {
        Graph g = new GraphBuilder(encodingManager).levelGraphCreate();
        g.edge(4, 3, 10, true);
        g.edge(3, 6, 10, true);

        g.edge(4, 5, 10, true);
        g.edge(5, 6, 10, true);

        AlgorithmPreparation prep = prepareGraph(g);
        DijkstraOneToMany algo = (DijkstraOneToMany) prep.createAlgo();
        algo.setEdgeFilter(new EdgeFilter()
        {
            @Override
            public boolean accept( EdgeIteratorState iter )
            {
                return iter.getAdjNode() != 5;
            }
        });
        Path p = algo.calcPath(4, 6);
        assertEquals(Helper.createTList(4, 3, 6), p.calcNodes());

        // important call!
        algo.clear();
        algo.setEdgeFilter(new EdgeFilter()
        {
            @Override
            public boolean accept( EdgeIteratorState iter )
            {
                return iter.getAdjNode() != 3;
            }
        });
        p = algo.calcPath(4, 6);
        assertEquals(Helper.createTList(4, 5, 6), p.calcNodes());
    }

    private Graph initGraph( Graph g )
    {
        // 0-1-2-3-4
        // |       /
        // 7-10----
        // \-8
        g.edge(0, 1, 1, true);
        g.edge(1, 2, 1, true);
        g.edge(2, 3, 1, true);
        g.edge(3, 4, 1, true);
        g.edge(4, 10, 1, true);

        g.edge(0, 7, 1, true);
        g.edge(7, 8, 1, true);
        g.edge(7, 10, 10, true);
        return g;
    }
}


text:
#include "ace/FoxReactor/FoxReactor.h"

FXDEFMAP(ACE_FoxReactor) ACE_FoxReactorMap[]={
  FXMAPFUNCS(SEL_IO_READ,0,MAXKEY,ACE_FoxReactor::onFileEvents),
  FXMAPFUNCS(SEL_IO_WRITE,0,MAXKEY,ACE_FoxReactor::onFileEvents),
  FXMAPFUNCS(SEL_IO_EXCEPT,0,MAXKEY,ACE_FoxReactor::onFileEvents),
  FXMAPFUNCS(SEL_TIMEOUT,0,MAXKEY,ACE_FoxReactor::onTimerEvents),
};

FXIMPLEMENT(ACE_FoxReactor,FXObject,ACE_FoxReactorMap,ARRAYNUMBER(ACE_FoxReactorMap))

ACE_ALLOC_HOOK_DEFINE (ACE_FoxReactor)

// Must be called with lock held
ACE_FoxReactor::ACE_FoxReactor (FXApp* a,
                                size_t size,
                                bool restart,
                                ACE_Sig_Handler *h)
  : ACE_Select_Reactor (size, restart, h), fxapp(a)
{
  // When the ACE_Select_Reactor is constructed it creates the notify
  // pipe and registers it with the register_handler_i() method. The
  // FoxReactor overloads this method BUT because the
  // register_handler_i occurs when constructing the base class
  // ACE_Select_Reactor, the ACE_Select_Reactor register_handler_i()
  // is called not the FoxReactor register_handler_i().  This means
  // that the notify pipe is registered with the ACE_Select_Reactor
  // event handling code not the FoxReactor and so notfications don't
  // work.  To get around this we simply close and re-opened the
  // notification handler in the constructor of the FoxReactor.

#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0)
  this->notify_handler_->close ();
  this->notify_handler_->open (this, 0);
#endif /* ACE_MT_SAFE */
}

ACE_FoxReactor::~ACE_FoxReactor (void)
{
}

void ACE_FoxReactor::fxapplication(FXApp *a)
{
   fxapp=a;
}

// This is just the <wait_for_multiple_events> from ace/Reactor.cpp
// but we use the Fox functions to wait for an event, not <select>

int
ACE_FoxReactor::wait_for_multiple_events (ACE_Select_Reactor_Handle_Set &handle_set,
                                         ACE_Time_Value *max_wait_time)
{
  ACE_TRACE( "ACE_FoxReactor::wait_for_multiple_events" );

  int nfound = 0;
  do
  {
    max_wait_time = this->timer_queue_->calculate_timeout (max_wait_time);
    size_t width = this->handler_rep_.max_handlep1 ();
    handle_set.rd_mask_ = this->wait_set_.rd_mask_;
    handle_set.wr_mask_ = this->wait_set_.wr_mask_;
    handle_set.ex_mask_ = this->wait_set_.ex_mask_;

    nfound = FoxWaitForMultipleEvents (width,
                                      handle_set,
                                      max_wait_time);

  } while( nfound == -1 && this->handle_error () > 0 );

  if (nfound > 0)
  {
#if !defined (ACE_WIN32)
    handle_set.rd_mask_.sync (this->handler_rep_.max_handlep1 ());
    handle_set.wr_mask_.sync (this->handler_rep_.max_handlep1 ());
    handle_set.ex_mask_.sync (this->handler_rep_.max_handlep1 ());
#endif /* ACE_WIN32 */
  }

  return nfound;
  // Timed out or input available
}

int
ACE_FoxReactor::FoxWaitForMultipleEvents (int width,
                                        ACE_Select_Reactor_Handle_Set &wait_set,
                                        ACE_Time_Value */*max_wait_time*/)
{
  // Check to make sure our handle's are all usable.
  ACE_Select_Reactor_Handle_Set temp_set = wait_set;

  if (ACE_OS::select (width,
                      temp_set.rd_mask_,
                      temp_set.wr_mask_,
                      temp_set.ex_mask_,
                      (ACE_Time_Value *) &ACE_Time_Value::zero ) == -1)
    return -1; // Bad file arguments...

  // Qt processing.
  this->fxapp->runOneEvent () ;

  // Reset the width, in case it changed during the upcalls.
  width = handler_rep_.max_handlep1 ();

  // Now actually read the result needed by the <Select_Reactor> using
  // <select>.
  return ACE_OS::select(width,
                        wait_set.rd_mask_,
                        wait_set.wr_mask_,
                        wait_set.ex_mask_,
                        (ACE_Time_Value *) &ACE_Time_Value::zero);
}

long ACE_FoxReactor::onFileEvents(FXObject* /* ob */, FXSelector se, void* handle){
  FXSelector sel=FXSELTYPE(se);
  ACE_Select_Reactor_Handle_Set dispatch_set;
  bool f=false;
  if(sel==SEL_IO_READ){
    dispatch_set.rd_mask_.set_bit(ACE_HANDLE(reinterpret_cast<FXival>(handle)));
    f=true;
  }
  else
  if(sel==SEL_IO_WRITE){
    dispatch_set.wr_mask_.set_bit(ACE_HANDLE(reinterpret_cast<FXival>(handle)));
    f=true;
  }
  else
  if(sel==SEL_IO_EXCEPT){
    dispatch_set.ex_mask_.set_bit(ACE_HANDLE(reinterpret_cast<FXival>(handle)));
    f=true;
  };
  if(f) dispatch (1, dispatch_set);

  return 1;
}

long ACE_FoxReactor::onTimerEvents(FXObject* /* ob */, FXSelector /* sel */, void* /* handle */)
{
  // Deal with any timer events
  ACE_Select_Reactor_Handle_Set handle_set;
  this->dispatch (0, handle_set );

  // Set next timeout signal
  this->reset_timeout ();

  return 0;
}

int
ACE_FoxReactor::register_handler_i (ACE_HANDLE handle,
                                    ACE_Event_Handler *handler,
                                    ACE_Reactor_Mask mask)
{
  ACE_TRACE ("ACE_FoxReactor::register_handler_i");

  int const result = ACE_Select_Reactor::register_handler_i (handle,
                                                             handler, mask);
  if (result == -1)
    return -1;

  unsigned long condition = 0;

  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::READ_MASK))
    ACE_SET_BITS (condition, FX::INPUT_READ);
  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::WRITE_MASK))
    ACE_SET_BITS (condition, FX::INPUT_WRITE);
  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::EXCEPT_MASK))
    ACE_SET_BITS (condition, FX::INPUT_EXCEPT);
  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::ACCEPT_MASK))
    ACE_SET_BITS (condition, FX::INPUT_READ);
  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::CONNECT_MASK))
    {
      ACE_SET_BITS (condition, FX::INPUT_WRITE); // connected, you may write
      ACE_SET_BITS (condition, FX::INPUT_READ);  // connected, you have data/err
    }

  if (condition != 0)
    {
     fxapp->addInput(handle, condition, this, 0);
    }
  return 0;
}

int
ACE_FoxReactor::register_handler_i (const ACE_Handle_Set &handles,
                                    ACE_Event_Handler *handler,
                                    ACE_Reactor_Mask mask)
{
  return ACE_Select_Reactor::register_handler_i (handles, handler, mask);
}

int
ACE_FoxReactor::remove_handler_i (ACE_HANDLE handle, ACE_Reactor_Mask mask)
{
  ACE_TRACE ("ACE_FoxReactor::remove_handler_i");

  // In the registration phase we registered first with
  // ACE_Select_Reactor and then with X.  Now we are now doing things
  // in reverse order.

  int condition = 0;

  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::READ_MASK))
    ACE_SET_BITS (condition, FX::INPUT_READ);
  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::WRITE_MASK))
    ACE_SET_BITS (condition, FX::INPUT_WRITE);
  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::EXCEPT_MASK))
    ACE_SET_BITS (condition, FX::INPUT_EXCEPT);
  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::ACCEPT_MASK))
    ACE_SET_BITS (condition, FX::INPUT_READ);
  if (ACE_BIT_ENABLED (mask, ACE_Event_Handler::CONNECT_MASK))
    {
      ACE_SET_BITS (condition, FX::INPUT_WRITE); // connected, you may write
      ACE_SET_BITS (condition, FX::INPUT_READ);  // connected, you have data/err
    }

  // First clean up the corresponding X11Input.
  fxapp->removeInput ((int)handle,condition); // ACE_reinterpret_cast(int,handle));

  // Now let the reactor do its work.
  return ACE_Select_Reactor::remove_handler_i (handle, mask);
}

int
ACE_FoxReactor::remove_handler_i (const ACE_Handle_Set &handles,
                               ACE_Reactor_Mask mask)
{
  return ACE_Select_Reactor::remove_handler_i (handles, mask);
}

// The following function ensures there's an Fox timeout for the first
// timeout in the Reactor's Timer_Queue.

void
ACE_FoxReactor::reset_timeout (void)
{
  ACE_Time_Value *max_wait_time =
    this->timer_queue_->calculate_timeout (0);

  if (max_wait_time != 0)
    {
      float t = max_wait_time->sec () +
        max_wait_time->usec () / 1000000.0F;
      fxapp->addTimeout (this, 0, t*1000);
    }
}

int
ACE_FoxReactor::reset_timer_interval
  (long timer_id,
   const ACE_Time_Value &interval)
{
  ACE_TRACE ("ACE_FoxReactor::reset_timer_interval");
  ACE_MT (ACE_GUARD_RETURN (ACE_Select_Reactor_Token, ace_mon, this->token_, -1));

  int const result =
    ACE_Select_Reactor::reset_timer_interval (timer_id,
                                              interval);

  if (result == -1)
    return -1;
  else
    {
      this->reset_timeout ();
      return result;
    }
}

long
ACE_FoxReactor::schedule_timer (ACE_Event_Handler *event_handler,
                                const void *arg,
                                const ACE_Time_Value &delay,
                                const ACE_Time_Value &interval)
{
  ACE_TRACE ("ACE_FoxReactor::schedule_timer");
  ACE_MT (ACE_GUARD_RETURN (ACE_Select_Reactor_Token, ace_mon, this->token_, -1));

  long result = ACE_Select_Reactor::schedule_timer (event_handler,
                                                    arg,
                                                    delay,
                                                    interval);
  if (result == -1)
    return -1;
  else
    {
      this->reset_timeout ();
      return result;
    }
}

int
ACE_FoxReactor::cancel_timer (ACE_Event_Handler *handler,
                              int dont_call_handle_close)
{
  ACE_TRACE ("ACE_FoxReactor::cancel_timer");

  if (ACE_Select_Reactor::cancel_timer (handler,
                                        dont_call_handle_close) == -1)
    return -1;
  else
    {
      this->reset_timeout ();
      return 0;
    }
}

int
ACE_FoxReactor::cancel_timer (long timer_id,
                              const void **arg,
                              int dont_call_handle_close)
{
  ACE_TRACE ("ACE_FoxReactor::cancel_timer");

  if (ACE_Select_Reactor::cancel_timer (timer_id,
                                        arg,
                                        dont_call_handle_close) == -1)
    return -1;
  else
    {
      this->reset_timeout ();
      return 0;
    }
}


text:
<?php

namespace Lam\MdlBundle\Entity;

use Doctrine\ORM\EntityRepository;

use Doctrine\ORM\QueryBuilder;

/**
 * FormationInformatiqueRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class FormationInformatiqueRepository extends EntityRepository
{
  public function listeFormationInformatique()
  {
        // On passe par le QueryBuilder vide de l'EntityManager pour l'exemple
        $req = $this->_em->createQueryBuilder();
        $req->select('fi')
            ->from('LamMdlBundle:formationinformatique', 'fi');

          return $req->getQuery()->getResult();
  }

    public function contenuFormationInformatique($num)
    {
    $query = $this->_em->createQuery("SELECT fi.Logo,fi.Titre, fi.id toto,fi.Objectif,fi.Public,fi.Prerequis, fi.nbPlace,t.NomTheme, c.Ordre, d.Libelle FROM LamMdlBundle:contenu c JOIN c.laFormationInformatique fi JOIN c.leTheme t  LEFT JOIN c.lesDetails d where c.laFormationInformatique='$num' order by c.Ordre");
    $resultats = $query->getResult();
    return $resultats;
  }

}


text:
'use strict';

module.exports = require('./base');

// Full generic BusinessProcess definition.
require('../business-process');

require('./fields');
require('./determinants');
require('./guide');
require('./certificates');
require('./requirements');
require('./requirement-uploads');
require('./payment-receipt-uploads');
require('./registrations');
require('./costs');
require('./data-forms');
require('./processing-steps');


text:
(
$~$ $\xmlstructref{oncodelineclickaction}$
| $\xmlstructref{onclickaction}$
)


text:
using System;
using System.Security.Cryptography;

namespace U2F.Client.Impl
{
	public class CryptoImpl : ICrypto
	{
		public byte[] ComputeSha256(String message)
		{
			try
			{
				var mySHA256 = SHA256Cng.Create();
				var hash = mySHA256.ComputeHash(message.GetBytes());
				return hash;
			}
			catch (Exception e)
			{
				throw new U2FException("Cannot compute SHA-256", e);
			}
		}
	}
}


text:
require_relative './example_helper'

screen_width = 800
screen_height = 600
ASPECT = screen_width.to_f / screen_height.to_f

scene = Mittsu::Scene.new
camera = Mittsu::PerspectiveCamera.new(75.0, ASPECT, 0.1, 1000.0)

renderer = Mittsu::OpenGLRenderer.new width: screen_width, height: screen_height, title: '15 Raycast Example'

cursor = Mittsu::Mesh.new(Mittsu::SphereGeometry.new(0.1), Mittsu::MeshBasicMaterial.new(color: 0x00ffff, wireframe: true))
scene.add(cursor)

cubes = Mittsu::Group.new
5.times { |i| 5.times { |j|
  geometry = Mittsu::BoxGeometry.new(0.5, 0.5, 0.5)
  material = Mittsu::MeshBasicMaterial.new(color: 0x00ff00)
  cube = Mittsu::Mesh.new(geometry, material)
  cube.position.set(-3.0 + i*1.5, -3.0 + j*1.5, rand)
  cube.rotation.set(rand, rand, rand)
  cubes.add(cube)
} }
scene.add(cubes)

camera.position.z = 5.0

mouse_position = Mittsu::Vector2.new

def screen_to_world(vector, camera)
  vector.unproject(camera).sub(camera.position).normalize()
  distance = -camera.position.z / vector.z
  vector.multiply_scalar(distance).add(camera.position)
end

renderer.window.on_mouse_move do |position|
  mouse_position.x = ((position.x/screen_width)*2.0-1.0)
  mouse_position.y = ((position.y/screen_height)*-2.0+1.0)
  screen_to_world(cursor.position.set(mouse_position.x, mouse_position.y, 0.5), camera)
  p cursor.position
end

renderer.window.on_resize do |width, height|
  screen_width, screen_height = width, height
  renderer.set_viewport(0, 0, width, height)
  camera.aspect = width.to_f / height.to_f
  camera.update_projection_matrix
end

raycaster = Mittsu::Raycaster.new

renderer.window.run do
  raycaster.set_from_camera(mouse_position, camera)
  intersects = raycaster.intersect_objects(cubes.children)

  cubes.children.each do |cube|
    cube.material.color.set(0x00ff00)
  end
  cursor.position.copy(intersects.first[:point]) unless intersects.empty?
  intersects.each do |intersect|
    intersect[:object].material.color.set(0xff00ff)
  end

  renderer.render(scene, camera)
end


text:
package com.cleeng.api.domain;

import java.io.Serializable;

public class CaptureQuestion implements Serializable {

    public String key;
    public boolean enabled;
    public boolean required;

    public CaptureQuestion(String key, boolean enabled, boolean required) {
        this.key = key;
        this.enabled = enabled;
        this.required = required;
    }
}


text:
FROM ubuntu:utopic
MAINTAINER Angus Lees <gus@inodes.org>

RUN \
 apt-get -q update && \
 apt-get -qy --no-install-recommends install \
 software-properties-common && \
 apt-key adv --recv-keys --keyserver \
 hkp://keyserver.ubuntu.com:80 0xcbcb082a1bb943db && \
 add-apt-repository \
 'deb http://mariadb.uberglobalmirror.com/repo/10.0/ubuntu utopic main' && \
 apt-get -q update && apt-get -qy upgrade && \
 apt-get -qy --no-install-recommends install \
 rsync mariadb-galera-server galera-arbitrator-3

COPY my.cnf /etc/mysql/

COMMAND /usr/bin/mysqldb
EXPOSE 3306 4444 4567 4568


text:
package org.postgresql.test.jdbc2;

import org.postgresql.jdbc2.AbstractJdbc2Connection;
import org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData;

import junit.framework.TestCase;

public class TestACL extends TestCase {

	@Override
	protected void setUp() throws Exception {
		// TODO Auto-generated method stub
		super.setUp();
	}

	@Override
	protected void tearDown() throws Exception {
		// TODO Auto-generated method stub
		super.tearDown();
	}
	public void testParseACL()
	{
		AbstractJdbc2Connection _a = null;
     	AbstractJdbc2DatabaseMetaData a = new AbstractJdbc2DatabaseMetaData(_a) {
 		};
         a.parseACL("{jurka=arwdRxt/jurka,permuser=rw*/jurka}","jurka");
         a.parseACL("{jurka=a*r*w*d*R*x*t*/jurka,permuser=rw*/jurka}", "jurka");
         a.parseACL("{=,jurka=arwdRxt,permuser=rw}","jurka");
         a.parseACL("{jurka=arwdRxt/jurka,permuser=rw*/jurka,grantuser=w/permuser}","jurka");
         a.parseACL("{jurka=a*r*w*d*R*x*t*/jurka,permuser=rw*/jurka,grantuser=w/permuser}","jurka");
         a.parseACL("{jurka=arwdRxt/jurka,permuser=rw*/jurka,grantuser=w/permuser,\"group permgroup=a/jurka\"}", "jurka");
         a.parseACL("{jurka=a*r*w*d*R*x*t*/jurka,permuser=rw*/jurka,grantuser=w/permuser,\"group permgroup=a/jurka\"}","jurka");
	}
}


text:
<?php namespace Redooor\Redminportal\Test;

use Redooor\Redminportal\App\Models\Order;
use Redooor\Redminportal\App\Models\Product;

class OrderControllerTest extends BaseControllerTest
{
    /**
     * Contructor
     */
    public function __construct()
    {
        $page = '/admin/orders';
        $viewhas = array(
            'singular' => 'order',
            'plural' => 'orders'
        );
        $input = array(
            'create' => array(
                'product_id' => array(1),
                'payment_status' => 'Completed',
                'paid'           => 1.99,
                'transaction_id' => 1,
                'email'          => 'admin@admin.com'
            ),
            'edit' => array(
                'id'   => 1,
                'product_id' => array(1),
                'payment_status' => 'Completed',
                'paid'           => 1.99,
                'transaction_id' => 1,
                'email'          => 'admin@admin.com'
            )
        );

        parent::__construct($page, $viewhas, $input);
    }

    /**
     * Destructor
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * Setup initial data for use in tests
     */
    public function setup()
    {
        parent::setup();

        $this->seed('RedminSeeder');

        // Add product
        $product = new Product;
        $product->name = 'This is title';
        $product->sku = 'UNIQUESKU001';
        $product->short_description = 'This is body';
        $product->active = true;
        $product->category_id = 1;
        $product->save();
    }

    /**
     * Test (Pass): access getEmails
     */
    public function testEmails()
    {
        $this->call('GET', '/admin/orders/emails');

        $this->assertResponseOk();
    }

    /**
     * Overwrite base functions, no edit for Order
     */
    public function testEditPass()
    {
        return;
    }

    /**
     * Overwrite base functions, no edit for Order
     */
    public function testStoreEdit()
    {
        return;
    }

    public function testStoreCreateFailedNoProduct()
    {
        $input = array(
            'product_id' => array(2),
            'payment_status' => 'Completed',
            'paid'           => 1.99,
            'transaction_id' => 1,
            'email'          => 'admin@admin.com',
        );

        $this->call('POST', '/admin/orders/store', $input);

        $this->assertRedirectedTo('/admin/orders/create');
    }

    public function testStoreCreateFailedNoSuchUser()
    {
        $input = array(
            'product_id' => array(1),
            'payment_status' => 'Completed',
            'paid'           => 1.99,
            'transaction_id' => 1,
            'email'          => 'nosuchuser@admin.com',
        );

        $this->call('POST', '/admin/orders/store', $input);

        $this->assertRedirectedTo('/admin/orders/create');
    }
}


text:
//
//  Event1000TextField.m
//  DemoiOS
//
//  https://github.com/MKGitHub/XBNCEventful
//  http://www.xybernic.com
//  http://www.khanofsweden.com
//
//  Copyright 2014 Mohsan Khan
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "Event1000TextField.h"

#import "XBNCEventful.h"

@implementation Event1000TextField

    #pragma mark - Life Cycle

    - (void)commonInit
    {
        [XBNCEventfulStatic receiveEvent:1000
                                receiver:self
                                selector:@selector(receiveValueChangedEvent:)];
    }

    - (id)initWithFrame:(CGRect)frameRect
    {
        if ((self = [super initWithFrame:frameRect]))
        {
            [self commonInit];
        }

        return self;
    }

    - (id)initWithCoder:(NSCoder *)coder
    {
        if ((self = [super initWithCoder:coder]))
        {
            [self commonInit];
        }

        return self;
    }

    - (void)dealloc
    {
        [XBNCEventfulStatic stopReceivingEventsForObject:self];
    }

    #pragma mark - Event

    - (void)receiveValueChangedEvent:(XBNCEvent *)event
    {
        NSNumber *uiSliderValue = event.data[@"NewUISliderValue"];

        self.text = XBNC_$(@"%lu", (unsigned long)uiSliderValue.unsignedIntegerValue);
    }

    #pragma mark - Drawing

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect {
        // Drawing code
    }
    */

@end


text:
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="sudoku.css">
  <meta charset="utf-8">
  <title>Sudoku</title>

          {{cell.value}}


text:
namespace autofill_assistant {

class ServiceRequestSender {
 public:
  using ResponseCallback =
      base::OnceCallback<void(int http_status, const std::string& response)>;

  ServiceRequestSender();
  virtual ~ServiceRequestSender();

  // Sends |request_body| to |url|. Returns the http status code and the
  // response itself.
  virtual void SendRequest(const GURL& url,
                           const std::string& request_body,
                           ResponseCallback callback) = 0;
};

}  // namespace autofill_assistant

#endif  // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_SERVICE_SERVICE_REQUEST_SENDER_H_


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace StudentSystem.Models
{
    public class Student
    {
        private ICollection<Course> courses;

        private ICollection<Homework> homeworks;

        public Student()
        {
            this.courses = new HashSet<Course>();
            this.homeworks = new HashSet<Homework>();
            this.Information = new StudentAdditionalInfo();
        }

        public int Id { get; set; }

        [Required]
        [MinLength(2)]
        [MaxLength(50)]
        public string Name { get; set; }

        [Range(0, 999999)]
        public int Number { get; set; }

        public StudentAdditionalInfo Information { get; set; }

        public virtual ICollection<Course> Courses
        {
            get { return this.courses; }
            set { this.courses = value; }
        }

        public virtual ICollection<Homework> Homeworks
        {
            get { return this.homeworks; }
            set { this.homeworks = value; }
        }
    }
}


text:
package org.locationtech.geowave.format.stanag4676.image;

import java.awt.image.BufferedImage;

public class ImageChipInfo {
  private BufferedImage image;
  private byte[] imageBytes;
  private final int frameNumber;
  private final int pixelRow;
  private final int pixelColumn;

  public ImageChipInfo(
      final BufferedImage image,
      final int frameNumber,
      final int pixelRow,
      final int pixelColumn) {
    this.image = image;
    this.frameNumber = frameNumber;
    this.pixelRow = pixelRow;
    this.pixelColumn = pixelColumn;
  }

  public BufferedImage getImage() {
    return image;
  }

  public void setImage(final BufferedImage image) {
    this.image = image;
  }

  public int getFrameNumber() {
    return frameNumber;
  }

  public int getPixelRow() {
    return pixelRow;
  }

  public int getPixelColumn() {
    return pixelColumn;
  }

  public byte[] getImageBytes() {
    return imageBytes;
  }

  public void setImageBytes(final byte[] imageBytes) {
    this.imageBytes = imageBytes;
  }
}