text:
som=`fru-print.py -b som -f product | awk -F- '{ print $2}' | tr '[:upper:]' '[:lower:]'`
cc=`fru-print.py -b cc -f product | awk -F- '{ print $2}' | tr '[:upper:]' '[:lower:]'`

#TODO Possibly check BOARD/BOARD_VARIANT values before changing arch file
#(but will only affect if the values match up to a repo arch value)
BOARD=${som}
BOARD_VARIANT=${som}_${cc}

#check if dnf configs already updated based off BOARD_VARIANT value
if ! grep "${BOARD_VARIANT}" /etc/dnf/vars/arch > /dev/null
then
    if grep "${BOARD}" /etc/dnf/vars/arch > /dev/null
    then
	#Add board_variant right after first level hiearchy which is MACHINE (Board is assumed to be present as SOM bsps are now built with BOARD defined)
        sed -i "s/:/:${BOARD_VARIANT}:/" /etc/dnf/vars/arch
        #Add board_variant arch to arch_compat (order doesnt matter here)
        sed -i "s/^arch_compat.*/& ${BOARD_VARIANT}/"  /etc/rpmrc

	PACKAGE_FEED_URIS="@@PACKAGE_FEED_URIS@@"
        for URI in ${PACKAGE_FEED_URIS}
        do
                FILE_NAME=$(echo ${URI} | awk -F"petalinux.xilinx.com/" '{print $2}' | sed 's./.-.g')
                echo -e "[remote-repo-${BOARD_VARIANT}]\nname=remote-repo-${BOARD_VARIANT}\nbaseurl=${URI}/${BOARD_VARIANT}\ngpgcheck=0\n" | tee -a /etc/yum.repos.d/*${FILE_NAME}.repo >/dev/null 2>&1
        done
    else
	echo "Not adding board variant to config as board is not present"
    fi
fi


text:
/*!
 * \file
 * \brief EcdsaSignBuffer implementation.
 */

#include <ippcp.h>
#include "ippmath/bignum.h"
#include "ippmath/ecdsa.h"
#include "ippmath/ecgroup.h"
#include "ippmath/memory.h"
#include "bignum-internal.h"

/// The number of attempts to generate ephemeral key pair
#define EPHKEYGEN_WATCHDOG (10)

EpidStatus EcdsaSignBuffer(ConstOctStr buf, size_t buf_len,
                           EcdsaPrivateKey const* privkey, BitSupplier rnd_func,
                           void* rnd_param, EcdsaSignature* sig) {
  EpidStatus result = kEpidMathErr;

  IppsECCPState* ec_ctx = NULL;
  BigNum* bn_ec_order = NULL;

  BigNum* bn_hash = NULL;

  BigNum* bn_reg_private = NULL;
  BigNum* bn_eph_private = NULL;
  IppsECCPPointState* ecp_eph_public = NULL;

  BigNum* bn_sig_x = NULL;
  BigNum* bn_sig_y = NULL;

  if (0 != buf_len && !buf) {
    return kEpidBadArgErr;
  }
  if (buf_len > INT_MAX) {
    return kEpidBadArgErr;
  }
  if (!privkey) {
    return kEpidBadArgErr;
  }
  if (!rnd_func) {
    return kEpidBadArgErr;
  }
  if (!sig) {
    return kEpidBadArgErr;
  }

  do {
    EpidStatus epid_status = kEpidNoErr;
    IppStatus sts = ippStsNoErr;
    int ctxsize = 0;
    // order of EC secp256r1
    const uint8_t secp256r1_r[32] = {
        0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF,
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBC, 0xE6, 0xFA, 0xAD, 0xA7, 0x17,
        0x9E, 0x84, 0xF3, 0xB9, 0xCA, 0xC2, 0xFC, 0x63, 0x25, 0x51};
    Ipp8u hash[IPP_SHA256_DIGEST_BITSIZE / 8] = {0};
    unsigned int gen_loop_count = EPHKEYGEN_WATCHDOG;
    Ipp32u cmp0 = IS_ZERO;
    Ipp32u cmp_order = IS_ZERO;

    // Define standard elliptic curve secp256r1
    sts = ippsECCPGetSizeStd256r1(&ctxsize);
    if (ippStsNoErr != sts) break;
    ec_ctx = (IppsECCPState*)SAFE_ALLOC(ctxsize);
    if (!ec_ctx) {
      result = kEpidMemAllocErr;
      break;
    }
    sts = ippsECCPInitStd256r1(ec_ctx);
    if (ippStsNoErr != sts) break;
    sts = ippsECCPSetStd256r1(ec_ctx);
    if (ippStsNoErr != sts) break;

    // Create big number for order of elliptic curve secp256r1
    epid_status = NewBigNum(sizeof(secp256r1_r), &bn_ec_order);
    if (kEpidMemAllocErr == epid_status) {
      result = kEpidMemAllocErr;
      break;
    }
    if (kEpidNoErr != epid_status) break;
    epid_status = ReadBigNum(secp256r1_r, sizeof(secp256r1_r), bn_ec_order);
    if (kEpidNoErr != epid_status) break;

    // Calculate hash for input message
    sts = ippsSHA256MessageDigest(buf, (int)buf_len, hash);
    if (ippStsNoErr != sts) break;

    // Create big number for hash
    epid_status = NewBigNum(sizeof(hash), &bn_hash);
    if (kEpidMemAllocErr == epid_status) {
      result = kEpidMemAllocErr;
      break;
    }
    if (kEpidNoErr != epid_status) break;
    epid_status = ReadBigNum(hash, sizeof(hash), bn_hash);
    if (kEpidNoErr != epid_status) break;
    sts = ippsMod_BN(bn_hash->ipp_bn, bn_ec_order->ipp_bn, bn_hash->ipp_bn);
    if (ippStsNoErr != sts) break;

    // Create big number for regular private key
    epid_status = NewBigNum(sizeof(*privkey), &bn_reg_private);
    if (kEpidMemAllocErr == epid_status) {
      result = kEpidMemAllocErr;
      break;
    }
    if (kEpidNoErr != epid_status) break;
    epid_status = ReadBigNum(privkey, sizeof(*privkey), bn_reg_private);
    if (kEpidNoErr != epid_status) break;

    // Validate private key is in range [1, bn_ec_order-1]
    sts = ippsCmpZero_BN(bn_reg_private->ipp_bn, &cmp0);
    if (ippStsNoErr != sts) break;
    sts = ippsCmp_BN(bn_reg_private->ipp_bn, bn_ec_order->ipp_bn, &cmp_order);
    if (ippStsNoErr != sts) break;
    if (IS_ZERO == cmp0 || LESS_THAN_ZERO != cmp_order) {
      result = kEpidBadArgErr;
      break;
    }

    // Create big number for ephemeral private key
    epid_status = NewBigNum(sizeof(secp256r1_r), &bn_eph_private);
    if (kEpidMemAllocErr == epid_status) {
      result = kEpidMemAllocErr;
      break;
    }
    if (kEpidNoErr != epid_status) break;

    // Create EC point for ephemeral public key
    sts = ippsECCPPointGetSize(256, &ctxsize);
    if (ippStsNoErr != sts) break;
    ecp_eph_public = (IppsECCPPointState*)SAFE_ALLOC(ctxsize);
    if (!ecp_eph_public) {
      result = kEpidMemAllocErr;
      break;
    }
    sts = ippsECCPPointInit(256, ecp_eph_public);
    if (ippStsNoErr != sts) break;

    // Create big numbers for signature
    epid_status = NewBigNum(sizeof(secp256r1_r), &bn_sig_x);
    if (kEpidMemAllocErr == epid_status) {
      result = kEpidMemAllocErr;
      break;
    }
    if (kEpidNoErr != epid_status) break;
    epid_status = NewBigNum(sizeof(secp256r1_r), &bn_sig_y);
    if (kEpidMemAllocErr == epid_status) {
      result = kEpidMemAllocErr;
      break;
    }
    if (kEpidNoErr != epid_status) break;

    do {
      // Generate ephemeral key pair
      sts = ippsECCPGenKeyPair(bn_eph_private->ipp_bn, ecp_eph_public, ec_ctx,
                               (IppBitSupplier)rnd_func, rnd_param);
      if (ippStsNoErr != sts) break;

      // Set ephemeral key pair
      sts = ippsECCPSetKeyPair(bn_eph_private->ipp_bn, ecp_eph_public, ippFalse,
                               ec_ctx);
      if (ippStsNoErr != sts) break;

      // Compute signature
      sts = ippsECCPSignDSA(bn_hash->ipp_bn, bn_reg_private->ipp_bn,
                            bn_sig_x->ipp_bn, bn_sig_y->ipp_bn, ec_ctx);
      if (ippStsEphemeralKeyErr != sts) break;
    } while (--gen_loop_count);
    if (ippStsEphemeralKeyErr == sts) {
      result = kEpidRandMaxIterErr;
      break;
    }
    if (ippStsNoErr != sts) break;

    sts = ippsGetOctString_BN(sig->x.data, sizeof(sig->x), bn_sig_x->ipp_bn);
    if (ippStsNoErr != sts) break;
    sts = ippsGetOctString_BN(sig->y.data, sizeof(sig->y), bn_sig_y->ipp_bn);
    if (ippStsNoErr != sts) break;

    result = kEpidNoErr;
  } while (0);

  DeleteBigNum(&bn_ec_order);
  DeleteBigNum(&bn_hash);
  DeleteBigNum(&bn_reg_private);
  DeleteBigNum(&bn_eph_private);
  DeleteBigNum(&bn_sig_x);
  DeleteBigNum(&bn_sig_y);

  SAFE_FREE(ec_ctx);
  SAFE_FREE(ecp_eph_public);

  return result;
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: New skills, new site
date: 2011-08-14 21:28:56
categories:
- update
---

After working at [Snow Valley](http://www.snowvalley.com/) for just over a month now, having learned vast amounts in such a short time, I thought it was about time I put my new skills to use on my own website.

MStrutt.co.uk is now fully HTML5 compliant taking advantage of all the lovely new features of CSS3 and all the -webkit extras. Soon I'll be adding in [HTML5 Microdata](http://schema.org/) and fully SEOptimise the site.

I see this happening many more times in the future as I continue to learn on the cutting edge of the web. Already this is filtering down into the other websites in my portfolio with a redesign of [ei8htyei8ht.com](http://ei8htyei8ht.com/) in progress, and [MSCycleBlog](http://cycleblog.mstrutt.co.uk/) & [HelpBuntu](http://helpbuntu.mstrutt.co.uk/) in the pipeline.


text:
#include "esnpapi.h"

#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

std::string getInterfaceName(NPP npp, NPObject* object)
{
    std::string className;
    NPVariant result;
    bool asConstructor = true;  // true if object can be a constructor

    VOID_TO_NPVARIANT(result);
    NPN_Invoke(npp, object, NPN_GetStringIdentifier("toString"), 0, 0, &result);
    for (;;)
    {
        if (NPVARIANT_IS_STRING(result))
        {
            className = std::string(NPVARIANT_TO_STRING(result).utf8characters,
                                    NPVARIANT_TO_STRING(result).utf8length);
        }
        NPN_ReleaseVariantValue(&result);
        if (className.compare(0, 9, "function ") == 0)
        {
            // In Chrome, a [Constructor] object is represented as a 'Function'.
            className = className.substr(9);
            size_t pos = className.find('(');
            if (pos != std::string::npos)
            {
                className = className.substr(0, pos);
                break;
            }
            return "Function";
        }
        if (className.compare(0, 8, "[object ", 8) == 0 && className[className.length() - 1] == ']')
        {
            className = className.substr(8, className.length() - 9);
            break;
        }
        // This object is likely to have a stringifier. Check the constructor name directly.
        NPVariant constructor;
        VOID_TO_NPVARIANT(constructor);
        if (asConstructor && NPN_GetProperty(npp, object, NPN_GetStringIdentifier("constructor"), &constructor))
        {
            if (NPVARIANT_IS_OBJECT(constructor) &&
                NPN_Invoke(npp, NPVARIANT_TO_OBJECT(constructor), NPN_GetStringIdentifier("toString"), 0, 0, &result))
            {
                NPN_ReleaseVariantValue(&constructor);
                asConstructor = false;
                continue;
            }
            NPN_ReleaseVariantValue(&constructor);
        }
        return "Object";
    }
    // In Firefox, the constructor and an instance object cannot be distinguished by toString().
    // Check if object has a 'prototype' to see if it is a constructor.
    if (asConstructor && NPN_HasProperty(npp, object, NPN_GetStringIdentifier("prototype")))
    {
        className += "_Constructor";
    }
    return className;
}

Any convertToAny(NPP npp, const NPVariant* variant)
{
    switch (variant->type)
    {
    case NPVariantType_Void:
    case NPVariantType_Null:
        return Any();
        break;
    case NPVariantType_Bool:
        return NPVARIANT_TO_BOOLEAN(*variant);
        break;
    case NPVariantType_Int32:
        return NPVARIANT_TO_INT32(*variant);
        break;
    case NPVariantType_Double:
        return NPVARIANT_TO_DOUBLE(*variant);
        break;
    case NPVariantType_String:
        return std::string(NPVARIANT_TO_STRING(*variant).utf8characters, NPVARIANT_TO_STRING(*variant).utf8length);
        break;
    case NPVariantType_Object:
    {
        NPObject* object = NPVARIANT_TO_OBJECT(*variant);
        if (!object)
        {
            break;
        }
        if (StubObject::isStub(object))
        {
            StubObject* stub = static_cast<StubObject*>(object);
            return stub->getObject();
        }
        PluginInstance* instance = static_cast<PluginInstance*>(npp->pdata);
        if (instance)
        {
            ProxyControl* proxyControl = instance->getProxyControl();
            if (proxyControl)
            {
                return proxyControl->createProxy(object);
            }
        }
        break;
    }
    default:
        break;
    }
    return Any();
}

void convertToVariant(NPP npp, const std::string& value, NPVariant* variant, bool result)
{
    if (value.length() == 0)
    {
        STRINGN_TO_NPVARIANT(0, 0, *variant);
        return;
    }
    if (!result)
    {
        STRINGN_TO_NPVARIANT(value.c_str(), static_cast<uint32_t>(value.length()), *variant);
        return;
    }
    void* buffer = NPN_MemAlloc(value.length());
    if (!buffer)
    {
        STRINGN_TO_NPVARIANT(0, 0, *variant);
        return;
    }
    memmove(buffer, value.c_str(), value.length());
    STRINGN_TO_NPVARIANT(static_cast<NPUTF8*>(buffer), static_cast<uint32_t>(value.length()), *variant);
}

void convertToVariant(NPP npp, Object* value, NPVariant* variant, bool result)
{
    if (!value)
    {
        NULL_TO_NPVARIANT(*variant);
        return;
    }
    if (ProxyObject* proxy = dynamic_cast<ProxyObject*>(value))
    {
        if (result)
        {
            NPN_RetainObject(proxy->getNPObject());
        }
        OBJECT_TO_NPVARIANT(proxy->getNPObject(), *variant);
        return;
    }
    if (PluginInstance* instance = static_cast<PluginInstance*>(npp->pdata))
    {
        StubControl* stubControl = instance->getStubControl();
        if (stubControl)
        {
            NPObject* object = stubControl->createStub(value);
            if (object)
            {
                if (result)
                {
                    NPN_RetainObject(object);
                }
                OBJECT_TO_NPVARIANT(object, *variant);
                return;
            }
        }
    }
    NULL_TO_NPVARIANT(*variant);
}

namespace
{

NPObject* createArray(NPP npp)
{
    NPObject* array = 0;
    NPObject* window;
    NPN_GetValue(npp, NPNVWindowNPObject, &window);
    NPString script =
    {
        "new Array();",
        12
    };
    NPVariant result;
    if (NPN_Evaluate(npp, window, &script, &result))
    {
        if (NPVARIANT_IS_OBJECT(result))
        {
            array = NPVARIANT_TO_OBJECT(result);
        }
        else
        {
            NPN_ReleaseVariantValue(&result);
        }
    }
    NPN_ReleaseObject(window);
    return array;
}

template <typename T>
void copySequence(NPP npp, NPObject* array, const Sequence<T> sequence, bool result)
{
    for (unsigned i = 0; i < sequence.getLength(); ++i)
    {
        NPIdentifier id = NPN_GetIntIdentifier(i);
        NPVariant element;
        convertToVariant(npp, sequence[i], &element, result);
        NPN_SetProperty(npp, array, id, &element);
    }
}

}

void convertToVariant(NPP npp, const Any& any, NPVariant* variant, bool result)
{
    switch (any.getType())
    {
    case Any::Empty:
        NULL_TO_NPVARIANT(*variant);
        break;
    case Any::Bool:
        BOOLEAN_TO_NPVARIANT(any.toBoolean(), *variant);
        break;
    case Any::Int32:
    case Any::Uint32:
        INT32_TO_NPVARIANT(static_cast<int32_t>(any), *variant);
        break;
    case Any::Int64:
    case Any::Uint64:
    case Any::Float32:
    case Any::Float64:
        DOUBLE_TO_NPVARIANT(static_cast<double>(any), *variant);
        break;
    case Any::Dynamic:
        if (any.isString())
        {
            std::string value = any.toString();
            if (value.length() == 0)
            {
                STRINGN_TO_NPVARIANT(0, 0, *variant);
            }
            else if (!result)
            {
                STRINGN_TO_NPVARIANT(value.c_str(), static_cast<uint32_t>(value.length()), *variant);
            }
            else {
                void* buffer = NPN_MemAlloc(value.length());
                if (!buffer)
                {
                    STRINGN_TO_NPVARIANT(0, 0, *variant);
                }
                else
                {
                    memmove(buffer, value.c_str(), value.length());
                    STRINGN_TO_NPVARIANT(static_cast<NPUTF8*>(buffer), static_cast<uint32_t>(value.length()), *variant);
                }
            }
        }
        else
        {
            assert(any.isObject());
            convertToVariant(npp, any.toObject(), variant, result);
        }
        break;
    default:
        VOID_TO_NPVARIANT(*variant);
        break;
    }
}


text:
package gov.va.jmeadows;

import gov.va.cpe.idn.PatientIds;
import gov.va.cpe.vpr.sync.vista.VistaDataChunk;
import gov.va.hmp.HmpProperties;
import gov.va.med.jmeadows.webservice.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static gov.va.jmeadows.JMeadowsClientUtils.SOURCE_PROTOCOL_DODADAPTER;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.TestCase.fail;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class JMeadowsVitalServiceTest {
    private String DOD_STATUS_REPORT_FLAG = "DODADAPTER_SOURCE_STATUS_REPORT";
    private JMeadowsData mockJMeadowsClient;
    private JMeadowsVitalService jMeadowsVitalService;
    private Environment mockEnvironment;

    private String vistaId = "9E7A";
    private String icn = "123456789";
    private String dfn = "4321";
    private String pid = vistaId +";"+ dfn;
    private String uid = "urn:va:patient:"+vistaId+":"+ dfn +":"+ icn;
    private String edipi = "0000000001";

    private String url = "test.url";
    private long timeoutMS = 45000;
    private String userName = "test.username";
    private String userIen = "test.ien";
    private String userSiteCode = "test.sitecode";
    private String userSiteName = "test.sitename";

    private User user;
    private Patient patient;

    @Before
    public void setup() {
        mockEnvironment = mock(StandardEnvironment.class);
        when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_URL)).thenReturn(url);
        when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_TIMEOUT_MS)).thenReturn("" + timeoutMS);
        when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_NAME)).thenReturn(userName);
        when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_IEN)).thenReturn(userIen);
        when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_CODE)).thenReturn(userSiteCode);
        when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_NAME)).thenReturn(userSiteName);

        this.mockJMeadowsClient = mock(JMeadowsData.class);
        this.jMeadowsVitalService = new JMeadowsVitalService(new JMeadowsConfiguration(mockEnvironment));
        this.jMeadowsVitalService.setJMeadowsClient(mockJMeadowsClient);

        user = new User();
        user.setUserIen("test.ien");
        Site hostSite = new Site();
        hostSite.setSiteCode("test.site.code");
        hostSite.setAgency("VA");
        hostSite.setMoniker("test.moniker");
        hostSite.setName("test.site.name");
        user.setHostSite(hostSite);

        patient = new Patient();
        patient.setEDIPI("test.edipi");
    }

    @Test
    public void testFetchPatientVitals() {
        try {
            when(this.mockJMeadowsClient.getPatientVitals(any(JMeadowsQuery.class))).thenReturn(createTestData());
            JMeadowsQuery query = new JMeadowsQueryBuilder()
                    .user(user)
                    .patient(patient)
                    .build();
            PatientIds patientIds = new PatientIds.Builder()
                    .pid(pid)
                    .icn(icn)
                    .uid(uid)
                    .edipi(edipi)
                    .build();
            List<VistaDataChunk> vistaDataChunkList = jMeadowsVitalService.fetchDodPatientVitals(query, patientIds);
            assertNotNull(vistaDataChunkList);

            //dod status report should have been removed
            assertThat(vistaDataChunkList.size(), is(2));

            List<Vitals> testDataList = createTestData();
            for(int i = 0; i < vistaDataChunkList.size(); i++) {
                VistaDataChunk vistaDataChunk = vistaDataChunkList.get(i);
                assertThat(JMeadowsVitalService.DOMAIN_VITAL, is(vistaDataChunk.getDomain()));
                assertThat(2, is(vistaDataChunk.getItemCount()));
                assertThat(i+1, is(vistaDataChunk.getItemIndex()));
                assertThat(vistaId, is(vistaDataChunk.getParams().get("vistaId")));
                assertThat(dfn, is(vistaDataChunk.getParams().get("patientDfn")));
                assertThat(vistaId, is(vistaDataChunk.getSystemId()));
                assertThat(dfn, is(vistaDataChunk.getLocalPatientId()));
                assertThat(icn, is(vistaDataChunk.getPatientIcn()));
                assertThat("DOD;" + edipi, is(vistaDataChunk.getPatientId()));
                assertThat("vrpcb://9E7A/HMP SYNCHRONIZATION CONTEXT/HMPDJFS API", is(vistaDataChunk.getRpcUri()));
                assertThat(VistaDataChunk.NEW_OR_UPDATE, is(vistaDataChunk.getType()));
                Map<String,Object> jsonMap = vistaDataChunk.getJsonMap();
                Vitals testVital = testDataList.get(i);
                assertThat("Vital Sign", is(jsonMap.get("kind")));
                assertThat("DOD", is(jsonMap.get("facilityCode")));
                assertThat("DOD", is(jsonMap.get("facilityName")));
                assertThat("urn:va:vital:DOD:"+edipi+":"+testVital.getCdrEventId(), is(jsonMap.get("uid")));
                assertThat(testVital.getVitalType(), is(jsonMap.get("typeName")));
                assertThat(testVital.getRate(), is(jsonMap.get("result")));
                assertThat(testVital.getUnits(), is(jsonMap.get("units")));

                List<Map<String, Object>> codes = (List<Map<String, Object>>)jsonMap.get("codes");

                assertThat(JLVTerminologySystem.LOINC.getUrn(), is(codes.get(0).get("system")));
            }
        } catch (JMeadowsException_Exception e) {
            fail(e.getMessage());
        }
    }

    @Test
    public void testNullAndEmptyVitalList() {
        try {
            //return null list
            when(this.mockJMeadowsClient.getPatientVitals(any(JMeadowsQuery.class))).thenReturn(null);

            JMeadowsQuery query = new JMeadowsQueryBuilder()
                    .user(user)
                    .patient(patient)
                    .build();
            PatientIds patientIds = new PatientIds.Builder()
                    .pid(pid)
                    .icn(icn)
                    .uid(uid)
                    .edipi(edipi)
                    .build();

            List<VistaDataChunk> vistaDataChunkList = jMeadowsVitalService.fetchDodPatientVitals(query, patientIds);
            assertNotNull(vistaDataChunkList);
            assertThat(vistaDataChunkList.size(), is(0));

            //return empty list
            when(this.mockJMeadowsClient.getPatientVitals(any(JMeadowsQuery.class))).thenReturn(new ArrayList<Vitals>());

            assertNotNull(vistaDataChunkList);
            assertThat(vistaDataChunkList.size(), is(0));
        } catch (JMeadowsException_Exception e) {
            fail(e.getMessage());
        }
    }

    private List<Vitals> createTestData() throws JMeadowsException_Exception {
        XMLGregorianCalendar cal = null;
        try {
            cal = DatatypeFactory.newInstance().newXMLGregorianCalendar();
        }catch (DatatypeConfigurationException dce) {
            throw new JMeadowsException_Exception("data type factory error", null);
        }

        //create two test vitals

        Site dodSite = new Site();
        dodSite.setMoniker("DOD");
        dodSite.setSiteCode("DOD");
        dodSite.setName("DOD");

        Vitals vital1 = new Vitals();
        vital1.setVitalType("PULSE");
        vital1.setRate("96");
        vital1.setUnits("/min");
        vital1.setDateTimeTaken(cal);
        Code code1 = new Code();
        code1.setCode("1000");
        code1.setDisplay("test.code.display.1");
        code1.setSystem("LOINC");
        vital1.getCodes().add(code1);
        vital1.setSourceProtocol(SOURCE_PROTOCOL_DODADAPTER);
        vital1.setSite(dodSite);
        vital1.setCdrEventId("123456789");

        Vitals vital2 = new Vitals();
        vital2.setVitalType("WEIGHT");
        vital2.setRate("210");
        vital2.setUnits("lb");
        vital2.setDateTimeTaken(cal);
        Code code2 = new Code();
        code2.setCode("1001");
        code2.setDisplay("test.code.display.2");
        code2.setSystem("VITALS");
        vital2.getCodes().add(code2);
        vital2.setSourceProtocol(SOURCE_PROTOCOL_DODADAPTER);
        vital2.setSite(dodSite);
        vital2.setCdrEventId("987654321");

        //generate dod status report beans
        Vitals dodStatusReport1 = new Vitals();
        dodStatusReport1.setVitalType("status.report.text");
        Site dodStatusSite = new Site();
        dodStatusSite.setMoniker(DOD_STATUS_REPORT_FLAG);
        dodStatusSite.setName(DOD_STATUS_REPORT_FLAG);
        dodStatusSite.setSiteCode(DOD_STATUS_REPORT_FLAG);
        dodStatusReport1.setSite(dodStatusSite);

        //generate connection unavailable bean
        Vitals connectionUnavailable = new Vitals();
        connectionUnavailable.setRate("Connection unavailable.");
        Site caSite = new Site();
        caSite.setMoniker("DOD");
        caSite.setName("DOD");
        caSite.setAgency("DOD");
        caSite.setSiteCode("DOD");
        connectionUnavailable.setSite(caSite);

        return Arrays.asList(vital1, vital2, dodStatusReport1, connectionUnavailable);
    }
}


text:
'use strict';

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const inputValidation = require('../../src/middleware');
const range = require('ajv-keywords/keywords/range');

const definition = {
    type: 'object',
    macro: function (schema) {
        if (schema.length === 0) return true;
        if (schema.length === 1) return { not: { required: schema } };
        const schemas = schema.map(function (prop) {
            return { required: [prop] };
        });
        return { not: { anyOf: schemas } };
    },
    metaSchema: {
        type: 'array',
        items: {
            type: 'string'
        }
    }
};

const app = new Koa();
const router = new Router();

app.use(async function(ctx, next) {
    try {
        await next();
    } catch (err) {
        if (err instanceof inputValidation.InputValidationError) {
            ctx.status = 400;
            ctx.body = { more_info: JSON.stringify(err.errors) };
        }
    }
});
app.use(bodyParser());
app.use(router.routes());

const inputValidationOptions = {
    keywords: [range, { name: 'prohibited', definition }],
    beautifyErrors: true,
    firstError: true,
    expectFormFieldsInBody: true,
    framework: 'koa'
};

module.exports = () => {
    inputValidation.init('test/custom-keywords-swagger.yaml', inputValidationOptions);

    router.post('/keywords', inputValidation.validate, function (ctx, next) {
        ctx.status = 200;
        ctx.body = { result: 'OK' };
    });
    return app;
};


text:
const
  Registry = require("hitmands-registry"),
  {
    ENV_DEVELOPMENT,
    Logger,
    serverRequire
  } = Registry.get("configs"),

  Scaffolder = serverRequire("Mail/MailServices/MailScaffolder")
;

function CreateTemplateCtrl(req, res) {
  const
    template = req.params.template.slug,
    collection = req.params.collection.slug,
    group = req.params.group.slug,

    templateId = req.params.template.id || template,
    collectionId = req.params.collection.id || collection,
    groupId = req.params.group.id || group,

    TPL_ID = req.params.MAILTEMPLATE_ID
  ;

  return Promise
    .resolve(Scaffolder.scaffold(
      templateId, collectionId, groupId
    ))
    .then(() => {
      if(ENV_DEVELOPMENT) {
        Logger.log(`Created: ${TPL_ID}`);
      }

      res.statusMessage = "Template Created";
      return res.status(201).json({group, collection, template});
    })
    .catch(() => {

      res.statusMessage = "Unable to create Template";
      return res.status(500).end();
    })
}

module.exports = CreateTemplateCtrl;


text:
var Class = require('../../utils/Class');

/**
 * @classdesc
 * Contains information about a specific Gamepad Axis.
 * Axis objects are created automatically by the Gamepad as they are needed.
 *
 * @class Axis
 * @memberof Phaser.Input.Gamepad
 * @constructor
 * @since 3.0.0
 *
 * @param {Phaser.Input.Gamepad.Gamepad} pad - A reference to the Gamepad that this Axis belongs to.
 * @param {number} index - The index of this Axis.
 */
var Axis = new Class({

    initialize:

    function Axis (pad, index)
    {
        /**
         * A reference to the Gamepad that this Axis belongs to.
         *
         * @name Phaser.Input.Gamepad.Axis#pad
         * @type {Phaser.Input.Gamepad.Gamepad}
         * @since 3.0.0
         */
        this.pad = pad;

        /**
         * An event emitter to use to emit the axis events.
         *
         * @name Phaser.Input.Gamepad.Axis#events
         * @type {Phaser.Events.EventEmitter}
         * @since 3.0.0
         */
        this.events = pad.events;

        /**
         * The index of this Axis.
         *
         * @name Phaser.Input.Gamepad.Axis#index
         * @type {number}
         * @since 3.0.0
         */
        this.index = index;

        /**
         * The raw axis value, between -1 and 1 with 0 being dead center.
         * Use the method `getValue` to get a normalized value with the threshold applied.
         *
         * @name Phaser.Input.Gamepad.Axis#value
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.value = 0;

        /**
         * Movement tolerance threshold below which axis values are ignored in `getValue`.
         *
         * @name Phaser.Input.Gamepad.Axis#threshold
         * @type {number}
         * @default 0.1
         * @since 3.0.0
         */
        this.threshold = 0.1;
    },

    /**
     * Internal update handler for this Axis.
     * Called automatically by the Gamepad as part of its update.
     *
     * @method Phaser.Input.Gamepad.Axis#update
     * @private
     * @since 3.0.0
     *
     * @param {number} value - The value of the axis movement.
     */
    update: function (value)
    {
        this.value = value;
    },

    /**
     * Applies the `threshold` value to the axis and returns it.
     *
     * @method Phaser.Input.Gamepad.Axis#getValue
     * @since 3.0.0
     *
     * @return {number} The axis value, adjusted for the movement threshold.
     */
    getValue: function ()
    {
        return (Math.abs(this.value) < this.threshold) ? 0 : this.value;
    },

    /**
     * Destroys this Axis instance and releases external references it holds.
     *
     * @method Phaser.Input.Gamepad.Axis#destroy
     * @since 3.10.0
     */
    destroy: function ()
    {
        this.pad = null;
        this.events = null;
    }

});

module.exports = Axis;


text:
/**
 * Yard page with dark background
 */
.yard {
    width: 100%;
    /*background: #313543;*/
    background: var(--yardBg);
    color: var(--yardGrayText);
}


text:
'use strict';

//Setting up route
angular.module('useradministration').config(['$stateProvider',
	function($stateProvider) {
		// Useradministration state routing
		$stateProvider.
		state('useradministration', {
			url: '/useradministration',
			templateUrl: 'modules/useradministration/views/useradministration.client.view.html'
		});
	}
]);


text:
namespace sh
{
class StructureHLSL;

class UniformHLSL
{
  public:
    UniformHLSL(StructureHLSL *structureHLSL, ShShaderOutput outputType, const std::vector<Uniform> &uniforms);

    void reserveUniformRegisters(unsigned int registerCount);
    void reserveInterfaceBlockRegisters(unsigned int registerCount);
    TString uniformsHeader(ShShaderOutput outputType, const ReferencedSymbols &referencedUniforms);
    TString interfaceBlocksHeader(const ReferencedSymbols &referencedInterfaceBlocks);

    // Used for direct index references
    static TString interfaceBlockInstanceString(const TInterfaceBlock& interfaceBlock, unsigned int arrayIndex);

    const std::map<std::string, unsigned int> &getInterfaceBlockRegisterMap() const
    {
        return mInterfaceBlockRegisterMap;
    }
    const std::map<std::string, unsigned int> &getUniformRegisterMap() const
    {
        return mUniformRegisterMap;
    }

  private:
    TString interfaceBlockString(const TInterfaceBlock &interfaceBlock, unsigned int registerIndex, unsigned int arrayIndex);
    TString interfaceBlockMembersString(const TInterfaceBlock &interfaceBlock, TLayoutBlockStorage blockStorage);
    TString interfaceBlockStructString(const TInterfaceBlock &interfaceBlock);
    const Uniform *findUniformByName(const TString &name) const;

    // Returns the uniform's register index
    unsigned int declareUniformAndAssignRegister(const TType &type, const TString &name);

    unsigned int mUniformRegister;
    unsigned int mInterfaceBlockRegister;
    unsigned int mSamplerRegister;
    StructureHLSL *mStructureHLSL;
    ShShaderOutput mOutputType;

    const std::vector<Uniform> &mUniforms;
    std::map<std::string, unsigned int> mInterfaceBlockRegisterMap;
    std::map<std::string, unsigned int> mUniformRegisterMap;
};

}

#endif // COMPILER_TRANSLATOR_UNIFORMHLSL_H_


text:
from functools import lru_cache

from rest_framework import serializers

from waldur_core.structure import models as structure_models

class OrderItemSerializer(serializers.Serializer):
    attributes = serializers.ReadOnlyField()
    limits = serializers.ReadOnlyField()
    project_uuid = serializers.SerializerMethodField()
    project_name = serializers.SerializerMethodField()
    customer_uuid = serializers.SerializerMethodField()
    customer_name = serializers.SerializerMethodField()
    offering_uuid = serializers.ReadOnlyField(source='offering.uuid')
    offering_name = serializers.ReadOnlyField(source='offering.name')
    plan_uuid = serializers.ReadOnlyField(source='plan.uuid')
    plan_name = serializers.ReadOnlyField(source='plan.name')
    resource_uuid = serializers.ReadOnlyField(source='resource.uuid')
    resource_name = serializers.ReadOnlyField(source='resource.name')

    @lru_cache(maxsize=1)
    def _get_project(self, order_item):
        return structure_models.Project.all_objects.get(id=order_item.order.project_id)

    def get_customer_uuid(self, order_item):
        project = self._get_project(order_item)
        return project.customer.uuid

    def get_customer_name(self, order_item):
        project = self._get_project(order_item)
        return project.customer.name

    def get_project_uuid(self, order_item):
        project = self._get_project(order_item)
        return project.uuid

    def get_project_name(self, order_item):
        project = self._get_project(order_item)
        return project.name

class ResourceSerializer(serializers.Serializer):
    attributes = serializers.ReadOnlyField()
    limits = serializers.ReadOnlyField()
    project_uuid = serializers.ReadOnlyField(source='project.uuid')
    project_name = serializers.ReadOnlyField(source='project.name')
    customer_uuid = serializers.ReadOnlyField(source='project.customer.uuid')
    customer_name = serializers.ReadOnlyField(source='project.customer.name')
    offering_uuid = serializers.ReadOnlyField(source='offering.uuid')
    offering_name = serializers.ReadOnlyField(source='offering.name')
    plan_uuid = serializers.ReadOnlyField(source='plan.uuid')
    plan_name = serializers.ReadOnlyField(source='plan.name')
    resource_uuid = serializers.ReadOnlyField(source='uuid')
    resource_name = serializers.ReadOnlyField(source='name')


text:
package com.xiaogua.better.guava;

import org.junit.Test;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;

public class TestGuavaMap {
	@Test
	public void testArrayListMultimap() {
		ArrayListMultimap<String, String> m = ArrayListMultimap.create();
		m.put("test", "1");
		m.put("test", "1");
		m.put("test", "2");
		m.put("test2", "3");
		System.out.println(m.get("test"));
		System.out.println(m.get("test2"));
	}

	@Test
	public void testHashMultimap() {
		HashMultimap<String, String> m = HashMultimap.create();
		m.put("test", "1");
		m.put("test", "1");
		m.put("test", "2");
		m.put("test2", "3");
		System.out.println(m.get("test"));// 1,2
		System.out.println(m.get("test2"));
	}

	@Test
	public void testBiMap() {
		BiMap<String, String> m = HashBiMap.create();
		m.put("test", "1");
		m.forcePut("test2", "1");
		m.put(null, null);
		System.out.println(m.get("test"));// null
		System.out.println(m.get("test2"));
		System.out.println(m.inverse().get("1"));
		System.out.println(m.containsKey(null));
	}

}


text:
package com.dwalldorf.timetrack.backend.event;

import com.dwalldorf.timetrack.model.UserModel;

public class UserAuthenticationEvent extends ActionEvent {

    private static final String MESSAGE_NONE = "NONE";

    private final String message;

    private UserAuthenticationEvent(final Action action, final UserModel user, final Result result) {
        this(action, user, result, null);
    }

    private UserAuthenticationEvent(final Action action, final UserModel user, final Result result, final String message) {
        super(action, user, result);
        this.message = message;
    }

    public static UserAuthenticationEvent loginSuccessEvent(final UserModel user) {
        return new UserAuthenticationEvent(Action.LOGIN, user, Result.SUCCESS);
    }

    public static UserAuthenticationEvent loginFailedEvent(final String loginName, final String message) {
        return new UserAuthenticationEvent(Action.LOGIN, userFromUsername(loginName), Result.FAILURE, message);
    }

    public static UserAuthenticationEvent logoutEvent(final UserModel user) {
        return new UserAuthenticationEvent(Action.LOGOUT, user, Result.SUCCESS);
    }

    public static UserAuthenticationEvent registrationSuccessEvent(final UserModel user) {
        return new UserAuthenticationEvent(Action.REGISTER, user, Result.SUCCESS);
    }

    public static UserAuthenticationEvent registrationFailedEvent(final String username, final String message) {
        return new UserAuthenticationEvent(Action.REGISTER, userFromUsername(username), Result.FAILURE, message);
    }

    private static UserModel userFromUsername(final String username) {
        return new UserModel()
                .setUsername(username);
    }

    public String getMessage() {
        if (message == null) {
            return MESSAGE_NONE;
        }

        return message;
    }
}


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using ArchiSteamFarm;
using ConfigGenerator.Localization;

namespace ConfigGenerator {
	internal static class Program {
		private const string ASFExecutableFile = SharedInfo.ASF + ".exe";

		private static void Init() {
			AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
			TaskScheduler.UnobservedTaskException += UnobservedTaskExceptionHandler;

			string homeDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
			if (!string.IsNullOrEmpty(homeDirectory)) {
				Directory.SetCurrentDirectory(homeDirectory);

				// Allow loading configs from source tree if it's a debug build
				if (Debugging.IsDebugBuild) {
					// Common structure is bin/(x64/)Debug/ArchiSteamFarm.exe, so we allow up to 4 directories up
					for (byte i = 0; i < 4; i++) {
						Directory.SetCurrentDirectory("..");
						if (!Directory.Exists(SharedInfo.ASFDirectory)) {
							continue;
						}

						Directory.SetCurrentDirectory(SharedInfo.ASFDirectory);
						break;
					}

					// If config directory doesn't exist after our adjustment, abort all of that
					if (!Directory.Exists(SharedInfo.ConfigDirectory)) {
						Directory.SetCurrentDirectory(homeDirectory);
					}
				}
			}

			if (!Directory.Exists(SharedInfo.ConfigDirectory)) {
				Logging.LogGenericErrorWithoutStacktrace(CGStrings.ErrorConfigDirectoryNotFound);
				Environment.Exit(1);
			}

			if (!File.Exists(ASFExecutableFile)) {
				return;
			}

			FileVersionInfo asfVersionInfo = FileVersionInfo.GetVersionInfo(ASFExecutableFile);
			Version asfVersion = new Version(asfVersionInfo.ProductVersion);

			Version cgVersion = Assembly.GetEntryAssembly().GetName().Version;

			if (asfVersion == cgVersion) {
				return;
			}

			Logging.LogGenericErrorWithoutStacktrace(string.Format(CGStrings.ErrorVersionMismatch, asfVersion, cgVersion));
			Process.Start("https://github.com/" + SharedInfo.GithubRepo + "/releases/tag/" + asfVersion);
			Environment.Exit(1);
		}

		/// <summary>
		///     The main entry point for the application.
		/// </summary>
		[STAThread]
		private static void Main() {
			Init();
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}

		private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) {
			if (args?.ExceptionObject == null) {
				Logging.LogNullError(nameof(args) + " || " + nameof(args.ExceptionObject));
				return;
			}

			Logging.LogGenericException((Exception) args.ExceptionObject);
		}

		private static void UnobservedTaskExceptionHandler(object sender, UnobservedTaskExceptionEventArgs args) {
			if (args?.Exception == null) {
				Logging.LogNullError(nameof(args) + " || " + nameof(args.Exception));
				return;
			}

			Logging.LogGenericException(args.Exception);
		}
	}
}


text:
[![Build Status](https://secure.travis-ci.org/codegenome/MailSleuth.png)](http://travis-ci.org/codegenome/MailSleuth)

This gem provides a model and an observer to log e-mail delivery.

## Installation

Simply add MailSleuth to your Gemfile and bundle it up:

```ruby
gem 'mail_sleuth'
```

Then install the migrations and run them:

```
$ rake mail_sleuth:install:migrations
$ rake db:migrate
```

## Usage

The model is called MessageLog and contains a bunch of attribute named
after Mail::Message accessors. Here's the full list of attributes:

 * `message_id`
 * `bounced?`
 * `final_recipient`
 * `action`
 * `error_status`
 * `diagnostic_code`
 * `retryable?`
 * `from`
 * `to`
 * `delivery_method`
 * `delivery_handler`
 * `errors`
 * `subject`
 * `content_type`
 * `charset`
 * `perform_deliveries`

Some attributes are serialized like: `from`, `to`, `delivery_method`,
`delivery_handler` and `errors`.

## Licence

This project rocks and uses MIT-LICENSE.


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2017 Citrus-CAF Project
  ~ 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.
  ~
  -->

<resources>
    <!-- Set all elevations to 0 -->
    <dimen name="abc_action_bar_elevation_material">0.0dip</dimen>
    <dimen name="action_bar_elevation">0.0dip</dimen>
    <dimen name="tab_elevation">0.0dip</dimen>
    <dimen name="toolbar_elevation">0.0dip</dimen>
</resources>


text:
/*
  Native File Dialog

  http://www.frogtoss.com/labs
*/

#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "nfd.h"
#include "nfd_common.h"

#define SIMPLE_EXEC_IMPLEMENTATION
#include "simple_exec.h"

const char NO_ZENITY_MSG[] = "zenity not installed";

static void AddTypeToFilterName( const char *typebuf, char *filterName, size_t bufsize )
{
    size_t len = strlen(filterName);
    if( len > 0 )
        strncat( filterName, " *.", bufsize - len - 1 );
    else
        strncat( filterName, "--file-filter=*.", bufsize - len - 1 );

    len = strlen(filterName);
    strncat( filterName, typebuf, bufsize - len - 1 );
}

static void AddFiltersToCommandArgs(char** commandArgs, int commandArgsLen, const char *filterList )
{
    char typebuf[NFD_MAX_STRLEN] = {0};
    const char *p_filterList = filterList;
    char *p_typebuf = typebuf;
    char filterName[NFD_MAX_STRLEN] = {0};
    int i;

    if ( !filterList || strlen(filterList) == 0 )
        return;

    while ( 1 )
    {

        if ( NFDi_IsFilterSegmentChar(*p_filterList) )
        {
            char typebufWildcard[NFD_MAX_STRLEN];
            /* add another type to the filter */
            assert( strlen(typebuf) > 0 );
            assert( strlen(typebuf) < NFD_MAX_STRLEN-1 );

            snprintf( typebufWildcard, NFD_MAX_STRLEN, "*.%s", typebuf );

            AddTypeToFilterName( typebuf, filterName, NFD_MAX_STRLEN );

            p_typebuf = typebuf;
            memset( typebuf, 0, sizeof(char) * NFD_MAX_STRLEN );
        }

        if ( *p_filterList == ';' || *p_filterList == '\0' )
        {
            /* end of filter -- add it to the dialog */

            for(i = 0; commandArgs[i] != NULL && i < commandArgsLen; i++);

            commandArgs[i] = strdup(filterName);

            filterName[0] = '\0';

            if ( *p_filterList == '\0' )
                break;
        }

        if ( !NFDi_IsFilterSegmentChar( *p_filterList ) )
        {
            *p_typebuf = *p_filterList;
            p_typebuf++;
        }

        p_filterList++;
    }

    /* always append a wildcard option to the end*/

    for(i = 0; commandArgs[i] != NULL && i < commandArgsLen; i++);

    commandArgs[i] = strdup("--file-filter=*.*");
}

static nfdresult_t ZenityCommon(char** command, int commandLen, const char* defaultPath, const char* filterList, char** stdOut)
{
    if(defaultPath != NULL)
    {
        char* prefix = "--filename=";
        int len = strlen(prefix) + strlen(defaultPath) + 1;

        char* tmp = (char*) calloc(len, 1);
        strcat(tmp, prefix);
        strcat(tmp, defaultPath);

        int i;
        for(i = 0; command[i] != NULL && i < commandLen; i++);

        command[i] = tmp;
    }

    AddFiltersToCommandArgs(command, commandLen, filterList);

    int byteCount = 0;
    int exitCode = 0;
    int processInvokeError = runCommandArray(stdOut, &byteCount, &exitCode, 0, command);

    for(int i = 0; command[i] != NULL && i < commandLen; i++)
        free(command[i]);

    nfdresult_t result = NFD_OKAY;

    if(processInvokeError == COMMAND_NOT_FOUND)
    {
        NFDi_SetError(NO_ZENITY_MSG);
        result = NFD_ERROR;
    }
    else
    {
        if(exitCode == 1)
            result = NFD_CANCEL;
    }

    return result;
}

static nfdresult_t AllocPathSet(char* zenityList, nfdpathset_t *pathSet )
{
    assert(zenityList);
    assert(pathSet);

    size_t len = strlen(zenityList) + 1;
    pathSet->buf = NFDi_Malloc(len);

    int numEntries = 1;

    for(size_t i = 0; i < len; i++)
    {
        char ch = zenityList[i];

        if(ch == '|')
        {
            numEntries++;
            ch = '\0';
        }

        pathSet->buf[i] = ch;
    }

    pathSet->count = numEntries;
    assert( pathSet->count > 0 );

    pathSet->indices = NFDi_Malloc( sizeof(size_t)*pathSet->count );

    int entry = 0;
    pathSet->indices[0] = 0;
    for(size_t i = 0; i < len; i++)
    {
        char ch = zenityList[i];

        if(ch == '|')
        {
            entry++;
            pathSet->indices[entry] = i + 1;
        }
    }

    return NFD_OKAY;
}

/* public */

nfdresult_t NFD_OpenDialog( const char *filterList,
                            const nfdchar_t *defaultPath,
                            nfdchar_t **outPath )
{
    int commandLen = 100;
    char* command[commandLen];
    memset(command, 0, commandLen * sizeof(char*));

    command[0] = strdup("zenity");
    command[1] = strdup("--file-selection");
    command[2] = strdup("--title=Open File");

    char* stdOut = NULL;
    nfdresult_t result = ZenityCommon(command, commandLen, defaultPath, filterList, &stdOut);

    if(stdOut != NULL)
    {
        size_t len = strlen(stdOut);
        *outPath = NFDi_Malloc(len);
        memcpy(*outPath, stdOut, len);
        (*outPath)[len-1] = '\0'; // trim out the final \n with a null terminator
        free(stdOut);
    }
    else
    {
        *outPath = NULL;
    }

    return result;
}

nfdresult_t NFD_OpenDialogMultiple( const nfdchar_t *filterList,
                                    const nfdchar_t *defaultPath,
                                    nfdpathset_t *outPaths )
{
    int commandLen = 100;
    char* command[commandLen];
    memset(command, 0, commandLen * sizeof(char*));

    command[0] = strdup("zenity");
    command[1] = strdup("--file-selection");
    command[2] = strdup("--title=Open Files");
    command[3] = strdup("--multiple");

    char* stdOut = NULL;
    nfdresult_t result = ZenityCommon(command, commandLen, defaultPath, filterList, &stdOut);

    if(stdOut != NULL)
    {
        size_t len = strlen(stdOut);
        stdOut[len-1] = '\0'; // remove trailing newline

        if ( AllocPathSet( stdOut, outPaths ) == NFD_ERROR )
            result = NFD_ERROR;

        free(stdOut);
    }
    else
    {
        result = NFD_ERROR;
    }

    return result;
}

nfdresult_t NFD_SaveDialog( const nfdchar_t *filterList,
                            const nfdchar_t *defaultPath,
                            nfdchar_t **outPath )
{
    int commandLen = 100;
    char* command[commandLen];
    memset(command, 0, commandLen * sizeof(char*));

    command[0] = strdup("zenity");
    command[1] = strdup("--file-selection");
    command[2] = strdup("--title=Save File");
    command[3] = strdup("--save");

    char* stdOut = NULL;
    nfdresult_t result = ZenityCommon(command, commandLen, defaultPath, filterList, &stdOut);

    if(stdOut != NULL)
    {
        size_t len = strlen(stdOut);
        *outPath = NFDi_Malloc(len);
        memcpy(*outPath, stdOut, len);
        (*outPath)[len-1] = '\0'; // trim out the final \n with a null terminator
        free(stdOut);
    }
    else
    {
        *outPath = NULL;
    }

    return result;
}

nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath,
    nfdchar_t **outPath)
{
    int commandLen = 100;
    char* command[commandLen];
    memset(command, 0, commandLen * sizeof(char*));

    command[0] = strdup("zenity");
    command[1] = strdup("--file-selection");
    command[2] = strdup("--directory");
    command[3] = strdup("--title=Select folder");

    char* stdOut = NULL;
    nfdresult_t result = ZenityCommon(command, commandLen, defaultPath, "", &stdOut);

    if(stdOut != NULL)
    {
        size_t len = strlen(stdOut);
        *outPath = NFDi_Malloc(len);
        memcpy(*outPath, stdOut, len);
        (*outPath)[len-1] = '\0'; // trim out the final \n with a null terminator
        free(stdOut);
    }
    else
    {
        *outPath = NULL;
    }

    return result;
}


text:
import System.Environment
import Network.Pcap
import PreprocessPcap

main = do
  [fName] <- getArgs
  h <- openOffline fName
  let loop h = do
        r <- getNext h
        case r of
          Nothing -> return ()
          Just (_, r') -> do
            putStrLn . showLine $ r'
            loop h
  loop h


text:
struct DataPacket
{
    const static int valuesLength = 10;
    const static int truthsLength = 3;

    int valuesUsed, truthsUsed;

    float values[valuesLength];
    bool truths[truthsLength];

    DataPacket()
    {
        for(int i = 0; i < valuesLength; i++)
        {
            values[i] = 0;

            if(i < truthsLength)
            {
                truths[i] = false;
            }
        }
    }
};

#endif

#ifndef Mediated_Perception_cartesianPacket_h
#define Mediated_Perception_cartesianPacket_h

struct CartesianPacket : DataPacket
{

};

#endif

#ifndef Mediated_Perception_nullPacket_h
#define Mediated_Perception_nullPacket_h

struct NullPacket : DataPacket
{

};

#endif

#ifndef Mediated_Perception_oscilatePacket_h
#define Mediated_Perception_oscilatePacket_h

struct OscilatePacket : DataPacket
{
    OscilatePacket()
    {
        valuesUsed = 3;
        truthsUsed = 0;
    }
};

#endif

#ifndef Mediated_Perception_valuePacket_h
#define Mediated_Perception_valuePacket_h

struct ValuePacket : DataPacket
{

};

#endif

#endif


text:
namespace Societies.Core.Infrastructure.Enumerations.Human
{
    public enum EyesColorType
    {
        NotSet = 0,
        Brown,
        Black,
        Gray,
        Blue,
        Green,
        Mixed
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cache
{
    // Cache Directories
    private $cms_cache = 'assets/cms/cache/';

    function __construct()
    {
        $this->CI = get_instance();
        $this->CI->load->helper('file');
    }

    // ------------------------------------------------------------------------

    /*
     * Model
     *
     * Executes and caches returned data from a model method
     *
     * @param string
     * @param string
     * @param array
     * @return mixed
     */
    function model($model, $method, $arguments = array(), $dir='')
    {
        $this->CI->load->add_package_path(APPPATH.'modules/content/');
        $this->CI->load->model($model);

        if ( ! is_array($arguments))
        {
            $arguments = (array) $arguments;
        }

        $cache_id = sha1($method.serialize($arguments));

        // Remove _model from model name to create the cache directory
        if (empty($dir))
        {
            $dir = str_replace('_model', '', strtolower($model)) . '/';
        }

        // Read cached file if it exists
        $data = $this->get($cache_id, $dir);

        if ($data !== FALSE)
        {
            // Data was returned from cache file
            return $data;
        }
        else
        {
            // Instantiate a new instance of the model
            $Class = new $model();
            $Object = $Class->$method($arguments);

            if (is_callable(array($Object, 'exists')) && $Object->exists() || (is_array($Object) && count($Object) > 0))
            {
                $this->save($cache_id, $dir, $Object);
            }

            return $Object;
        }
    }

    // ------------------------------------------------------------------------

    /*
     * Get
     *
     * Unserializes data from cache file
     *
     * @param string
     * @return bool
     */
    function get($id, $dir)
    {
        $cache_dir = $this->cms_cache . trim($dir, '/') . '/';

        // Read cached file if it exists
        if (file_exists(CMS_ROOT . $cache_dir . $id . '.cache'))
        {
            $content = read_file(CMS_ROOT . $cache_dir . $id . '.cache');

            return @unserialize($content);
        }

        return FALSE;
    }

    // ------------------------------------------------------------------------

    /*
     * Save
     *
     * Serializes and writes data to cache file
     *
     * @param string
     * @param string
     * @param string
     * @return bool
     */
    function save($id, $dir, $data)
    {
        $cache_dir = $this->cms_cache . trim($dir, '/') . '/';

        // Check if the cache directory exists
        // If not create it
        if ( ! file_exists(CMS_ROOT . $cache_dir))
        {
            @mkdir(CMS_ROOT . $cache_dir);
        }

        // Write data to cache file
        if ( ! write_file(CMS_ROOT . $cache_dir . $id . '.cache', @serialize($data)))
        {
            $this->CI->session->set_flashdata('message', '
Error compiling: ' . $cache_dir . ' is not writable.
');
            return FALSE;
        }

        return TRUE;
    }

    // ------------------------------------------------------------------------

    /*
     * Delete All
     *
     * This function will  delete caches files in a specified directory
     *
     * @param string
     * @return void
     */
    function delete_all($dir = '')
    {
        $this->CI->load->helper('file');

        if ( file_exists(CMS_ROOT . $this->cms_cache . $dir) )
        {
            foreach (glob(CMS_ROOT . $this->cms_cache . $dir . '/*') as $file)
            {
                @unlink($file);
            }
        }
    }
}


text:
using System.Web;
using System.Web.Routing;

namespace ScSyncr.Agent
{
    public class ScSyncrHttpModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            if (!RouteTable.Routes.Contains(ScSyncrRoute.Singleton))
                RouteTable.Routes.Add(ScSyncrRoute.Singleton);
            //context.BeginRequest += BeginRequest;
        }

        public void Dispose()
        {
        }
    }
}


text:
#ifndef __GLESMULTIRENDERTARGET_H__
#define __GLESMULTIRENDERTARGET_H__

#include "OgreGLESFrameBufferObject.h"

namespace Ogre {

    class GLESFBOManager;

	/** MultiRenderTarget for GL ES. Requires the FBO extension.
	*/
	class _OgreGLESExport GLESFBOMultiRenderTarget : public MultiRenderTarget
	{
	public:
		GLESFBOMultiRenderTarget(GLESFBOManager *manager, const String &name);
		~GLESFBOMultiRenderTarget();

		virtual void getCustomAttribute( const String& name, void *pData );

		bool requiresTextureFlipping() const { return true; }
	private:
		virtual void bindSurfaceImpl(size_t attachment, RenderTexture *target);
		virtual void unbindSurfaceImpl(size_t attachment);
		GLESFrameBufferObject fbo;
	};

}

#endif // __GLESMULTIRENDERTARGET_H__


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
		"http://www.w3.org/TR/html4/strict.dtd">

	<title>DojoX Portlet In a GridContainer: Using specific columns test</title>

	<link rel="stylesheet" id="themeStyles" href="../../../dijit/themes/soria/soria.css">

Test inserting Portlets in specific GridContainer columns

		This page tests the inserting of Portlets into specific columns of the GridContainer.
		To do this, each Portlet must be assigned a "column" attribute, and the "isAutoOrganized"
		attribute of the GridContainer must be set to false.

			This Portlet is placed in Column 1

			This Portlet is placed in Column 1

			This Portlet is placed in Column 1

			This Portlet is placed in Column 2

			This Portlet is placed in Column 3

			This Portlet is placed in Column 3


text:
package kr.co.leehana.example.bytearrayinputstream;

import java.io.ByteArrayInputStream;
import java.util.Random;

public class ByteArrayInputStreamSimpleExample1 {

	public static void main(String[] args) {
		byte[] buffer = new byte[10];
		Random rnd = new Random();

		for (int i = 0; i < buffer.length; i++) {
			buffer[i] = (byte) rnd.nextInt();
		}

		ByteArrayInputStream b = new ByteArrayInputStream(buffer);

		System.out.println("All the elements in the buffer:");

		int num;
		while ((num = b.read()) != -1) {
			System.out.print(num + " ");
		}
	}
}


text:
html {
	height: 100%;
	letter-spacing: 0.2px;
	font-size: 10px;
}

body {
	font-family: "Raleway", sans-serif;
	color: #eee;
	height: 100%;
	overflow: hidden;
	background: #222;
}

#swiftui-kara-wrapper {
	margin-top: 4rem;
	height: calc(100% - 12rem);
}

swiftui-kara {
	height: 40rem;
	width: 100%;

	font-family: "Raleway", sans-serif;
	font-size: 5rem;
	font-weight: bold;
	line-height: 3rem;
}

swiftui-karatext {
	color: #FC5956; /* Clipping text color */
	background-color: #444; /* Ground text color */
}

#player-wrapper {
	position: absolute;
	height: 12rem; bottom: 0;
	width: 100%;
	overflow-x: auto;
	font-size: 1.6rem;
}

#player-wrapper-inner {
	position: absolute;
	top: 0; bottom: 0;
	width: 120rem;
}

#control-btn, #song-informations, #time-informations, #volume-informations {
	margin-left: 2rem;
}

#control-btn {
	background: #2d2d2d;
	color: #FC5956;
	min-width: 0;
	width: 6rem;
	height: 6rem;
	padding: 0;
	border-radius: 50%;
	transition: background 0.25s ease;
}

#control-btn:hover {
	background: #fff;
}

#song-informations img {
	width: 8rem;
	height: 8rem;
}

#song-informations #names {
	height: 8rem;
	margin-left: 2rem;
}

#song, #artist {
	font-weight: bold;
}

#artist, #album {
	font-size: 1.2rem;
}

#time-slider {
	margin-right: 1rem;
}

#time-slider::shadow #sliderBar::shadow #progressContainer {
	background: #2d2d2d;
}

#time-slider #sliderBar #progressContainer { /* For Firefox */
	background: #2d2d2d;
}

#time-slider::shadow #sliderBar::shadow #activeProgress {
	background: #FC5956;
}

#time-slider #sliderBar #activeProgress { /* For Firefox */
	background: #FC5956;
}

#time-slider::shadow #sliderKnobInner {
	background: #FC5956;
	border: none;
}

#time-slider #sliderKnobInner { /* For Firefox */
	background: #FC5956;
	border: none;
}

#volume-slider::shadow #sliderBar::shadow #progressContainer {
	background: #2d2d2d;
}

#volume-slider #sliderBar #progressContainer { /* For Firefox */
	background: #2d2d2d;
}

#volume-slider::shadow #sliderBar::shadow #activeProgress {
	background: #FC5956;
}

#volume-slider #sliderBar #activeProgress { /* For Firefox */
	background: #FC5956;
}

#volume-slider::shadow #sliderKnobInner {
	background: #FC5956;
	border: none;
}

#volume-slider #sliderKnobInner { /* For Firefox */
	background: #FC5956;
	border: none;
}

#volume-slider::shadow #sliderKnobInner::before {
	background: #FC5956;
	border: none;
}

#volume-slider #sliderKnobInner::before { /* For Firefox */
	background: #FC5956;
	border: none;
}

#credit-wrapper {
	position: absolute;
	height: 4rem; top: 0;
	width: 100%;
	font-size: 1.2rem;
	border-bottom: 1px solid #111;
}

#credit-wrapper a {
	text-decoration: none;
	color: #FC5956;
	transition: color 0.25s ease;
}

#credit-wrapper a:hover {
	color: #eee;
}

#credit-wrapper a core-icon {
	margin-right: 0.5rem;
}

@media (max-device-width: 800px) {
	html {
		font-size: 8px;
	}

	swiftui-kara {
		font-size: 4rem;
		line-height: 2.5rem;
	}

	#swiftui-kara-wrapper {
		height: calc(100% - 20rem);
	}

	#player-wrapper {
		height: 25rem;
	}

	#player-wrapper-inner {
		width: 100%;
		flex-direction: column;
		justify-content: space-around;
	}

	#song-informations, #time-informations, #volume-informations {
		align-self: flex-start;
	}
}

@media (max-device-width: 480px) {
	html {
		font-size: 6px;
	}

	swiftui-kara {
		font-size: 3rem;
		line-height: 2rem;
	}
}


text:
package edu.upb.winfo.downloadcom;

import java.io.OutputStreamWriter;
import java.util.concurrent.atomic.AtomicBoolean;

import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import jd.http.RandomUserAgent;
import org.apache.log4j.*;
import org.apache.log4j.varia.LevelRangeFilter;

/**
 * Created by geskill on 30.12.2015.
 * <p>
 * crawler4j has some issues, that hinder the crawler to be more efficient
 * https://github.com/yasserg/crawler4j/issues/16
 *
 * @author geskill
 */
public class App {

	public static DatabaseInterface DATABASE = null;

	public static void main(String[] args) throws Exception {

		/*
		 * Instantiate the application logging system.
         */
		Logger logger = Logger.getRootLogger();

		/*
		 * Define log filter, to no log everything.
         */
		LevelRangeFilter filter = new LevelRangeFilter();
		filter.setAcceptOnMatch(true);
		filter.setLevelMin(Level.INFO);
		filter.setLevelMax(Level.FATAL);

		/*
		 * Write log to console.
         */
		ConsoleAppender consoleAppender = new ConsoleAppender();
		consoleAppender.setName("ConsoleAppender");
		consoleAppender.setWriter(new OutputStreamWriter(System.out));
		consoleAppender.setLayout(new PatternLayout("%d{ISO8601}|%-6r [%t] %-5p %30.30c %x - %m%n"));
		consoleAppender.addFilter(filter);
		logger.addAppender(consoleAppender);

		/*
		 * Write log to file.
         */
		FileAppender fileAppender = new FileAppender();
		fileAppender.setName("FileAppender");
		fileAppender.setFile("data/log/log.txt", true, false, 8 * 1024); // setFile(fileName) has bug
		fileAppender.setLayout(new PatternLayout("%d{ISO8601}|%-6r [%t] %-5p %30.30c %x - %m%n"));
		fileAppender.addFilter(filter);
		logger.addAppender(fileAppender);

		/*
         * Create now the database access.
         */
		AtomicBoolean success = new AtomicBoolean(false);
		DATABASE = new LocalDatabase("data/config/database.xml", success);
		if (!success.get()) {
			return;
		}

		/*
         * Create the seeds reader.
         */
		SeedReader seedReader = new SeedReader("data/config/seeds.txt");

		/*
         * Instantiate the crawler configuration
         */
		String crawlStorageFolder = "data/crawl/root/";
		int numberOfCrawlers = 1; // TODO: rework on https://github.com/yasserg/crawler4j/issues/108

		CrawlConfig crawlConfig = new CrawlConfig();
		crawlConfig.setCrawlStorageFolder(crawlStorageFolder);
		crawlConfig.setResumableCrawling(true);
		crawlConfig.setUserAgentString(RandomUserAgent.generate());
		crawlConfig.setPolitenessDelay(10000);

        /*
         * Instantiate the controller for this crawl.
         */
		PageFetcher pageFetcher = new PageFetcher(crawlConfig);
		RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
		robotstxtConfig.setEnabled(false);
		RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
		CrawlController controller = new CrawlController(crawlConfig, pageFetcher, robotstxtServer);

        /*
         * For each crawl, you need to add some seed urls. These are the first
         * URLs that are fetched and then the crawler starts following links
         * which are found in these pages
         */
		for (String s : seedReader.getSeeds()) {
			controller.addSeed(s);
		}

        /*
         * Start the crawl. This is a blocking operation, meaning that your code
         * will reach the line after this only when crawling is finished.
         */
		controller.start(DownloadComCrawler.class, numberOfCrawlers);
	}
}


text:
require "spec_helper"

describe Alephant::Publisher::Request::Processor do
  let (:base_path) { File.join(File.dirname(__FILE__), 'fixtures', 'components') }
  subject { described_class.new(base_path) }

  describe ".new" do
    specify { expect(subject).to be_a described_class }
  end

  describe "#consume" do
    let (:data) do
      {
        :content => "Foo Bar"
      }
    end

    context "using valid data" do
      let (:component) { "foo" }

      specify { expect(subject.consume(data, component)).to eq "#{data.values.first}\n" }
    end

  end
end


text:
package ecs

import (
	"encoding/csv"
	"strings"
)

func parseCommandOverride(command string) ([]string, error) {
	reader := csv.NewReader(strings.NewReader(command))
	reader.Comma = ' '
	commands, err := reader.Read()
	if err != nil {
		return nil, err
	}
	return commands, nil
}


text:
function plotData(X, y)
%PLOTDATA Plots the data points X and y into a new figure
%   PLOTDATA(x,y) plots the data points with + for the positive examples
%   and o for the negative examples. X is assumed to be a Mx2 matrix.

% Create New Figure
figure; hold on;

pos = find(y == 1); neg = find(y == 0);
plot(X(pos, 1), X(pos,2), '+'); hold on
plot(X(neg, 1), X(neg, 2), 'o');

hold off;

end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Eriostemon obovalis A.Cunn.

### Remarks
null


text:
from panflute import *
import bs4
import sys

def anchor_headings(elem, doc):
    if type(elem) != Header:
        return
    identifier = elem.identifier
    for child in elem.content:
        if type(child) == RawInline and child.format == 'html':
            b = bs4.BeautifulSoup(child.text, 'html.parser')
            if not b.a or 'name' not in b.a.attrs:
                continue
            identifier = b.a['name']
    return Header(*elem.content, level=elem.level, identifier=identifier,
                  classes=elem.classes, attributes=elem.attributes)

if __name__ == '__main__':
    toJSONFilter(anchor_headings)


text:
///////////////////////////////////////////////////////////////////////////////////////////////
//
//    This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
//    Copyright (c) 2005-2008, Jim Heising
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without modification,
//    are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * 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.
//
//    * Neither the name of Jim Heising nor the names of its contributors may be
//      used to endorse or promote products derived from this software without specific prior
//      written permission.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
//
///////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Threading;
using WOSI.CallButler.Data;
using CallButler.Manager.Forms;

namespace CallButler.Manager.ViewControls
{
    public partial class ProvidersView : CallButler.Manager.ViewControls.ViewControlBase
    {
        private System.Timers.Timer timer;

        public ProvidersView()
        {
            InitializeComponent();
            providerGrid.ReadOnly = false;
            SetColumnPriviledges();

            this.HelpRTFText = Properties.Resources.ProviderHelp;
        }

        private void SetColumnPriviledges()
        {
            foreach (DataGridViewColumn col in providerGrid.Columns)
            {
                if (col.HeaderText.Equals("Default") || col.HeaderText.Equals("Enabled"))
                {
                    col.ReadOnly = false;
                }
                else
                {
                    col.ReadOnly = true;
                }
            }
        }

        private System.Timers.Timer Timer
        {
            get
            {
                if (timer == null)
                {
                    timer = new System.Timers.Timer();
                    timer.Interval = 5000;
                    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
                }
                return timer;
            }
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                timer.Stop();
                lock (callButlerDataset)
                {
                    callButlerDataset.Providers.Merge(ManagementInterfaceClient.ManagementInterface.GetProviders(ManagementInterfaceClient.AuthInfo));
                }
            }
            catch { }
            finally
            {
                timer.Start();
            }
        }

        private void btnAddNewProvider_Click(object sender, EventArgs e)
        {
            AddNewProvider();
        }

        internal static DialogResult Add3rdPartyProvider()
        {
            return DialogResult.OK;
        }

        internal DialogResult AddNewProvider()
        {
            return AddNewProvider(ProviderType.None, true);
        }

        internal DialogResult AddNewProvider(ProviderType type, bool showInitialDialog)
        {
            DialogResult res = DialogResult.Cancel;
            CallButler.Manager.Plugin.CallButlerManagementProviderPlugin providerPlugin = null;

            /*if (showInitialDialog)
            {
                InitialProviderDialog dlg = new InitialProviderDialog();
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    type = dlg.ProviderType;
                }
            }*/

                /*switch (type)
                {
                    case ProviderType.CallButler:
                        // Get our default CallButler provider plugin
                        providerPlugin = (CallButler.Manager.Plugin.CallButlerManagementProviderPlugin)PluginManager.GetPluginFromID(new Guid(Properties.Settings.Default.PreferredVoIPProviderPluginID));
                        break;*/

                    //case ProviderType.Other:
                        providerPlugin = (CallButler.Manager.Plugin.CallButlerManagementProviderPlugin)PluginManager.GetPluginFromID(new Guid(Properties.Settings.Default.DefaultVoIPProviderPluginID));
                        //break;
                //}

                if (providerPlugin != null)
                {
                    CallButler.Manager.Plugin.ProviderData providerData = providerPlugin.AddNewProvider();

                    if (providerData != null)
                    {
                        CallButlerDataset.ProvidersRow provider = CreateProviderRow(providerData, providerPlugin.ServicePluginID.ToString());
                        callButlerDataset.Providers.AddProvidersRow(provider);
                        SaveProviderRow(provider);
                        res = DialogResult.OK;
                    }
                }
                return res;
         }

        private int DefaultCount
        {
            get
            {
                DataRow[] rows = callButlerDataset.Providers.Select("IsDefault = true");
                return rows.Length;
            }
        }

        private void providerGrid_DeleteDataRow(object sender, CallButler.Manager.Controls.DataRowEventArgs e)
        {

            if (MessageBox.Show(this, CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.ProvidersView_ConfirmDelete), CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.Common_ConfirmDelete), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                DeleteProvider((CallButlerDataset.ProvidersRow)e.DataRow);
            }
        }

        private void DeleteProvider(CallButlerDataset.ProvidersRow provider)
        {
            Guid providerID = provider.ProviderID;
            callButlerDataset.Providers.RemoveProvidersRow(provider);
            ManagementInterfaceClient.ManagementInterface.DeleteProvider(ManagementInterfaceClient.AuthInfo, providerID);
        }

        protected override void OnLoadData()
        {
            lock (callButlerDataset)
            {
                callButlerDataset.Providers.Merge(ManagementInterfaceClient.ManagementInterface.GetProviders(ManagementInterfaceClient.AuthInfo));
                callButlerDataset.AcceptChanges();
            }

            providerGrid.CellValueChanged += new DataGridViewCellEventHandler(providerGrid_CellValueChanged);
            providerGrid.CurrentCellDirtyStateChanged += new EventHandler(providerGrid_CurrentCellDirtyStateChanged);

            Thread regTimerThread = new Thread(new ThreadStart(StartRegStatusTimer));
            regTimerThread.Start();
        }

        protected override void OnSaveData()
        {
            Timer.Stop();
            Timer.Dispose();
        }

        private void StartRegStatusTimer()
        {
            Timer.Stop();
            Timer.Start();
        }

        private void providerGrid_EditDataRow(object sender, CallButler.Manager.Controls.DataRowEventArgs e)
        {
            EditProvider((CallButlerDataset.ProvidersRow)e.DataRow);
        }

        private void EditProvider(CallButlerDataset.ProvidersRow provider)
        {
            // Get the provider editor plugin
            CallButler.Manager.Plugin.CallButlerManagementProviderPlugin providerPlugin = (CallButler.Manager.Plugin.CallButlerManagementProviderPlugin)PluginManager.GetPluginFromID(new Guid(Properties.Settings.Default.DefaultVoIPProviderPluginID));

            /*try
            {
                // Check to see if this provider uses a different plugin
                if(provider.PluginID != null && provider.PluginID.Length > 0)
                    providerPlugin = (CallButler.Manager.Plugin.CallButlerManagementProviderPlugin)PluginManager.GetPluginFromID(new Guid(provider.PluginID));
            }
            catch
            {
            }*/

            if (providerPlugin != null)
            {
                // Copy our provider row into our provider data
                CallButler.Manager.Plugin.ProviderData providerData = new CallButler.Manager.Plugin.ProviderData();

                if (provider.AuthPassword != null && provider.AuthPassword.Length > 0)
                    providerData.AuthPassword = WOSI.Utilities.CryptoUtils.Decrypt(provider.AuthPassword, WOSI.CallButler.Data.Constants.EncryptionPassword);

                providerData.AuthUsername = provider.AuthUsername;
                providerData.DisplayName = provider.DisplayName;
                providerData.Domain = provider.Domain;
                providerData.EnableRegistration = provider.EnableRegistration;
                providerData.Expires = provider.Expires;
                providerData.ExtraData = provider.ExtraData;
                providerData.IsEnabled = provider.IsEnabled;
                providerData.Name = provider.Name;
                providerData.SIPProxy = provider.SIPProxy;
                providerData.SIPRegistrar = provider.SIPRegistrar;
                providerData.Username = provider.Username;

                // Edit the data
                providerData = providerPlugin.EditProvider(providerData);

                if (providerData != null)
                {
                    // Copy the data back into our provider row
                    if (providerData.AuthPassword != null && providerData.AuthPassword.Length > 0)
                        provider.AuthPassword = WOSI.Utilities.CryptoUtils.Encrypt(providerData.AuthPassword, WOSI.CallButler.Data.Constants.EncryptionPassword);

                    provider.AuthUsername = providerData.AuthUsername;
                    provider.DisplayName = providerData.DisplayName;
                    provider.Domain = providerData.Domain;
                    provider.EnableRegistration = providerData.EnableRegistration;
                    provider.Expires = providerData.Expires;
                    provider.ExtraData = providerData.ExtraData;
                    provider.IsEnabled = providerData.IsEnabled;
                    provider.Name = providerData.Name;
                    provider.SIPProxy = providerData.SIPProxy;
                    provider.SIPRegistrar = providerData.SIPRegistrar;
                    provider.Username = providerData.Username;

                    SaveProviderRow(provider);
                    LoadData();
                }
            }
        }

        void providerGrid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (providerGrid.IsCurrentCellDirty)
            {
                providerGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
       }

        private void providerGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                DataRowView rv = (DataRowView)providerGrid.Rows[e.RowIndex].DataBoundItem;
                DataRow row = rv.Row;

                bool IsChecked = (bool) providerGrid[e.ColumnIndex, e.RowIndex].Value;

                if (IsChecked)
                {
                    if (providerGrid.Columns[e.ColumnIndex].HeaderText.Equals("Default"))
                    {
                        foreach (DataGridViewRow dr in providerGrid.Rows)
                        {
                            if (dr.Index != e.RowIndex)
                            {
                                dr.Cells["IsDefault"].Value = false;
                            }
                        }
                    }

                }

                rv.EndEdit();

                if (!IsChecked)
                {
                    if (providerGrid.CurrentRow.Index == e.RowIndex && DefaultCount == 0)
                    {
                        providerGrid[e.ColumnIndex, e.RowIndex].Value = true;
                    }
                }

                SaveProviderRow((CallButlerDataset.ProvidersRow) row);
                providerGrid.InvalidateRow(e.RowIndex);
            }
        }

        private CallButlerDataset.ProvidersRow CreateProviderRow(CallButler.Manager.Plugin.ProviderData providerData, string pluginID)
        {
            CallButlerDataset.ProvidersRow provider = callButlerDataset.Providers.NewProvidersRow();

            if (DefaultCount == 0)
            {
                provider.IsDefault = true;
            }

            provider.CustomerID = Properties.Settings.Default.CustomerID;
            provider.ProviderID = Guid.NewGuid();
            provider.PluginID = pluginID;

            if (providerData.AuthPassword != null && providerData.AuthPassword.Length > 0)
                provider.AuthPassword = WOSI.Utilities.CryptoUtils.Encrypt(providerData.AuthPassword, WOSI.CallButler.Data.Constants.EncryptionPassword);

            provider.AuthUsername = providerData.AuthUsername;
            provider.DisplayName = providerData.DisplayName;
            provider.Domain = providerData.Domain;
            provider.EnableRegistration = providerData.EnableRegistration;
            provider.Expires = providerData.Expires;
            provider.IsEnabled = providerData.IsEnabled;
            provider.ExtraData = providerData.ExtraData;
            provider.Name = providerData.Name;
            provider.SIPProxy = providerData.SIPProxy;
            provider.SIPRegistrar = providerData.SIPRegistrar;
            provider.Username = providerData.Username;

            return provider;
        }

        private void SaveProviderRow( CallButlerDataset.ProvidersRow row )
        {
             CallButlerDataset.ProvidersDataTable providerDataTable = Utils.TableUtils<CallButlerDataset.ProvidersDataTable>.CreateTableFromRow(row);
             ManagementInterfaceClient.ManagementInterface.PersistProviders(ManagementInterfaceClient.AuthInfo, providerDataTable);
        }

        private void providerGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == usernameDataGridViewTextBoxColumn.Index && e.Value != System.DBNull.Value)
            {
                e.Value = WOSI.Utilities.StringUtils.FormatPhoneNumber((string)e.Value);
            }
        }

    }
}


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\Response\GetRoomsResponseMessageType.
 */

namespace jamesiarmes\PhpEws\Response;

/**
 * Represents the response to a GetRooms operation request.
 *
 * @package php-ews\Response
 */
class GetRoomsResponseMessageType extends ResponseMessageType
{
    /**
     * Provides a list of email addresses and display names that represent
     * meeting rooms.
     *
     * @since Exchange 2010
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfRoomsType
     */
    public $Rooms;
}


text:
A slight misnomer, this is actually a project for dtls-datapump-subject, but naming
hasn't quite stabalized yet


text:
{% extends "mapentity/mapentity_form.html" %}

{% load static feedback_tags %}

{% block extrabody %}
    {% suricate_workflow_enabled as suricate_workflow_enabled %}
    {{ block.super }}

    {% if suricate_workflow_enabled %}
        <script type="text/javascript" src="{% static "feedback/workflow.js" %}"></script>
        <script type="application/json" id="predefined_emails">
            {% predefined_emails as predefined_emails %}
            {{ predefined_emails|safe }}
        </script>
        <script type="application/json" id="resolved_intervention_info">
            {% resolved_intervention_info report as resolved_intervention_info %}
            {{ resolved_intervention_info|safe }}
        </script>
    {% endif %}
{% endblock extrabody %}


text:
namespace llvm {
class Module;
class StructType;
class Type;

/// This class provides the core functionality of linking in LLVM. It keeps a
/// pointer to the merged module so far. It doesn't take ownership of the
/// module since it is assumed that the user of this class will want to do
/// something with it after the linking.
class Linker {
public:
  struct StructTypeKeyInfo {
    struct KeyTy {
      ArrayRef<Type *> ETypes;
      bool IsPacked;
      KeyTy(ArrayRef<Type *> E, bool P);
      KeyTy(const StructType *ST);
      bool operator==(const KeyTy &that) const;
      bool operator!=(const KeyTy &that) const;
    };
    static StructType *getEmptyKey();
    static StructType *getTombstoneKey();
    static unsigned getHashValue(const KeyTy &Key);
    static unsigned getHashValue(const StructType *ST);
    static bool isEqual(const KeyTy &LHS, const StructType *RHS);
    static bool isEqual(const StructType *LHS, const StructType *RHS);
  };

  typedef DenseSet<StructType *, StructTypeKeyInfo> NonOpaqueStructTypeSet;
  typedef DenseSet<StructType *> OpaqueStructTypeSet;

  struct IdentifiedStructTypeSet {
    // The set of opaque types is the composite module.
    OpaqueStructTypeSet OpaqueStructTypes;

    // The set of identified but non opaque structures in the composite module.
    NonOpaqueStructTypeSet NonOpaqueStructTypes;

    void addNonOpaque(StructType *Ty);
    void switchToNonOpaque(StructType *Ty);
    void addOpaque(StructType *Ty);
    StructType *findNonOpaque(ArrayRef<Type *> ETypes, bool IsPacked);
    bool hasType(StructType *Ty);
  };

  Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler);
  Linker(Module *M);
  ~Linker();

  Module *getModule() const { return Composite; }
  void deleteModule();

  /// \brief Link \p Src into the composite. The source is destroyed.
  /// Returns true on error.
  bool linkInModule(Module *Src);

  /// \brief Set the composite to the passed-in module.
  void setModule(Module *Dst);

  static bool LinkModules(Module *Dest, Module *Src,
                          DiagnosticHandlerFunction DiagnosticHandler);

  static bool LinkModules(Module *Dest, Module *Src);

private:
  void init(Module *M, DiagnosticHandlerFunction DiagnosticHandler);
  Module *Composite;

  IdentifiedStructTypeSet IdentifiedStructTypes;

  DiagnosticHandlerFunction DiagnosticHandler;
};

} // End llvm namespace

#endif


text:
@interface LoggedViewController ()

@end

@implementation LoggedViewController

@end


text:
from requestbuilder import Arg

from euca2ools.commands.ec2 import EC2Request

class AttachVpnGateway(EC2Request):
    DESCRIPTION = 'Attach a virtual private gateway to a VPC'
    ARGS = [Arg('-c', '--vpc', dest='VpcId', metavar='VPC',
                required=True,
                help='VPC to attach the virtual private gateway to (required)'),
            Arg('VpnGatewayId', metavar='VGATEWAY',
                help='virtual private gateway to attach (required)')]

    def print_result(self, result):
        attachment = result.get('attachment') or {}
        print self.tabify(('VGWATTACHMENT', attachment.get('vpcId'),
                           attachment.get('state')))


text:
  Berville-sur-Mer est
       un village
       situé dans le département de l'Eure en Haute-Normandie. Elle comptait 498 habitants en 2008.

À coté de Berville-sur-Mer sont localisées les villes de
Fatouville-Grestain localisée à 3 km, 669 habitants,
Marais-Vernier située à 6 km, 492 habitants,
Foulbec à 5 km, 489 habitants,
Conteville à 2 km, 821 habitants,
Manneville-la-Raoult située à 6 km, 491 habitants,
Saint-Samson-de-la-Roque localisée à 5 km, 328 habitants,
 entre autres. De plus, Berville-sur-Mer est située à seulement 19 km de Le Havre.

Le nombre d'habitations, à Berville-sur-Mer, était réparti en 2011 en 26 appartements et 297 maisons soit
 un marché plutôt équilibré.

La commune compte quelques  aménagements, elle dispose, entre autres, de une boucle de randonnée.

Si vous envisagez de venir habiter à Berville-sur-Mer, vous pourrez aisément trouver une maison à vendre.


text:
<?php

namespace Koseu\Controllers;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use \Tsugi\Grades\GradeUtil;

class Assignments {

    const ROUTE = '/assignments';

    public static function routes(Application $app, $prefix=self::ROUTE) {
        $app->get($prefix, 'Koseu\\Controllers\\Assignments::get');
        $app->get($prefix.'/', 'Koseu\\Controllers\\Assignments::get');
    }

    public function get(Request $request, Application $app)
    {
        global $CFG;
        $tsugi = $app['tsugi'];

        if ( ! isset($CFG->lessons) ) {
            die_with_error_log('Cannot find lessons.json ($CFG->lessons)');
        }

        // Load the Lesson
        $l = new \Tsugi\UI\Lessons($CFG->lessons);

        // Load all the Grades so far
        $allgrades = array();
        if ( isset($_SESSION['id']) && isset($_SESSION['context_id'])) {
            $rows = GradeUtil::loadGradesForCourse($_SESSION['id'], $_SESSION['context_id']);
            foreach($rows as $row) {
                $allgrades[$row['resource_link_id']] = $row['grade'];
            }
        }

        return $app['twig']->render('@Koseu/Badges.twig',
            array('data' => $l->renderAssignments($allgrades, true))
        );

    }
}