text:
<?php

namespace dface\sql\placeholders;

class NumberPlaceHolderNode extends PlaceHolderNode
{

	public function acceptVisitor(NodeVisitor $visitor, $args)
	{
		return $visitor->visitNumberPlaceHolder($this, $args);
	}

}


text:
/*Your styles*/

/*
Those classes will be edited at runtime with values specified
by the settings of the CC application
*/
.hostFontColor{}
.hostFontFamily{}
.hostFontSize{}

/*font family, color and size*/
.hostFont{}
/*background color*/
.hostBgd{}
/*lighter background color*/
.hostBgdLight{}
/*darker background color*/
.hostBgdDark{}
/*background color and font*/
.hostElt{}

.hostButton{
    border:1px solid;
    border-radius:2px;
    height:20px;
    vertical-align:bottom;
    font-family:inherit;
    color:inherit;
    font-size:inherit;
}

redpajama_set_name: RedPajamaGithub


text:
@interface OCDSpecPostCondition : OCDSpecCondition {
}
@end

OCDSpecPostCondition *afterEach(VOIDBLOCK postcondition);


text:
namespace gpdxl
{
	using namespace gpos;

	XERCES_CPP_NAMESPACE_USE

	//---------------------------------------------------------------------------
	//	@class:
	//		CParseHandlerNLJoin
	//
	//	@doc:
	//		Parse handler for nested loop join operators
	//
	//---------------------------------------------------------------------------
	class CParseHandlerNLJoin : public CParseHandlerPhysicalOp
	{
		private:

			// the nested loop join operator
			CDXLPhysicalNLJoin *m_pdxlop;

			// private copy ctor
			CParseHandlerNLJoin(const CParseHandlerNLJoin &);

			// process the start of an element
			void StartElement
				(
					const XMLCh* const xmlszUri, 		// URI of element's namespace
 					const XMLCh* const xmlszLocalname,	// local part of element's name
					const XMLCh* const xmlszQname,		// element's qname
					const Attributes& attr				// element's attributes
				);

			// process the end of an element
			void EndElement
				(
					const XMLCh* const xmlszUri, 		// URI of element's namespace
					const XMLCh* const xmlszLocalname,	// local part of element's name
					const XMLCh* const xmlszQname		// element's qname
				);

		public:
			// ctor/dtor
			CParseHandlerNLJoin
				(
				IMemoryPool *pmp,
				CParseHandlerManager *pphm,
				CParseHandlerBase *pphRoot
				);

	};
}

#endif // !GPDXL_CParseHandlerNLJoin_H

// EOF


text:
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object type="Spring.Objects.Factory.Attributes.AutowiredAttributeObjectPostProcessor, Spring.Core" />

  <object id="HelloFoo"
          type="Spring.Objects.Factory.Attributes.ByType.HelloFoo, Spring.Core.Tests" />

  <object id="AutowireTestFieldNormal"
          type="Spring.Objects.Factory.Attributes.ByType.AutowireTestFieldNormal, Spring.Core.Tests"
          lazy-init="true" />

  <object id="AutowireTestPropertyNormal"
          type="Spring.Objects.Factory.Attributes.ByType.AutowireTestPropertyNormal, Spring.Core.Tests"
          lazy-init="true" />

  <object id="AutowireTestMethodNormal"
          type="Spring.Objects.Factory.Attributes.ByType.AutowireTestMethodNormal, Spring.Core.Tests"
          lazy-init="true" />

  <object id="AutowireTestConstructorNormal"
          type="Spring.Objects.Factory.Attributes.ByType.AutowireTestConstructorNormal, Spring.Core.Tests"
          lazy-init="true" />

</objects>


text:
Please adhere to the coding guidelines used throughout the
project (indentation, accurate comments, etc.) and any other requirements.

1. Fork the LitApi repository
2. Create a new branch for each feature or improvement
3. Send a pull request from each feature branch to the **master** branch

It is very important to separate new features or improvements into separate feature branches, and to send a
pull request for each branch. This allows us to review and pull in new features or improvements individually.


text:
import json
import operator
from functools import reduce

from django.db import connection
from django.db.models import Q
from django.http import JsonResponse
from django.urls import reverse
from django.views import View
from django.views.generic import TemplateView, DetailView, ListView
from uk_geo_utils.helpers import Postcode

from addressbase.models import Address
from councils.models import Council
from data_finder.helpers import RoutingHelper
from pollingstations.models import PollingStation

class IndexView(ListView):
    queryset = Council.objects.select_related("dataquality")
    template_name = "dashboard/council_list.html"

class CouncilDetailView(DetailView):
    queryset = Council.objects.all()
    template_name = "dashboard/council_detail.html"

    def get_context_data(self, object, **kwargs):
        context = super().get_context_data(object=object, **kwargs)

        with connection.cursor() as cursor:
            cursor.execute(
                """
                SELECT postcode, st_maxdistance(multipoint, multipoint)::int AS maxdistance
                FROM (
                    SELECT aa.postcode, st_transform(st_collect(aa.location), 27700) AS multipoint
                    FROM addressbase_address aa JOIN addressbase_uprntocouncil uc
                    ON aa.uprn = uc.uprn
                    WHERE uc.lad = %s AND uc.polling_station_id != ''
                    GROUP BY aa.postcode
                ) AS subquery
                WHERE multipoint IS NOT NULL
                ORDER BY maxdistance DESC
                LIMIT 20;
            """,
                (object.geography.gss,),
            )
            context["postcodes_by_diameter"] = cursor.fetchall()

        with connection.cursor() as cursor:
            cursor.execute(
                """
                SELECT aa.postcode, max(st_distance(
                        st_transform(ps.location, 27700),
                        st_transform(COALESCE(aa.location), 27700)
                    )::int) AS distance
                FROM
                    addressbase_address aa
                    JOIN addressbase_uprntocouncil uc
                        ON aa.uprn = uc.uprn
                    JOIN pollingstations_pollingstation ps
                        ON uc.polling_station_id = ps.internal_council_id
                    JOIN councils_councilgeography cg
                        ON ps.council_id = cg.council_id
                WHERE
                    cg.council_id = %s
                    AND ps.location IS NOT NULL
                GROUP BY aa.postcode
                ORDER BY distance DESC
                LIMIT 50;
                """,
                (object.council_id,),
            )

            context["distances_to_stations"] = cursor.fetchall()

        context["pollingstation_list"] = PollingStation.objects.filter(
            council=object
        ).order_by("internal_council_id")

        return context

class PostCodeView(TemplateView):
    template_name = "dashboard/postcode.html"

    def get_context_data(self, postcode, **kwargs):
        postcode = Postcode(postcode)
        addresses = Address.objects.filter(postcode=postcode.with_space)
        unassigned_addresses = [a for a in addresses if not a.polling_station_id]
        addresses = [a for a in addresses if a.polling_station_id]
        return {
            "postcode": postcode,
            "addresses": addresses,
            "unassigned_addresses": unassigned_addresses,
            "routing_helper": RoutingHelper(postcode),
        }

class PostCodeGeoJSONView(View):
    station_colors = ["purple", "red", "blue", "yellow", "green", "pink", "orange"]

    def get(self, request, postcode):
        postcode = Postcode(postcode)
        addresses = Address.objects.filter(postcode=postcode.with_space)
        station_ids = sorted(
            set((a.council_id, a.polling_station_id) for a in addresses)
        )
        if station_ids:
            stations = PollingStation.objects.filter(
                reduce(
                    operator.or_,
                    (
                        Q(
                            council_id=council_id,
                            internal_council_id=internal_council_id,
                        )
                        for council_id, internal_council_id in station_ids
                    ),
                )
            )
        else:
            stations = PollingStation.objects.none()
        station_colors = dict(zip(station_ids, self.station_colors))

        return JsonResponse(
            {
                "type": "FeatureCollection",
                "features": [
                    {
                        "type": "Feature",
                        "geometry": json.loads(station.location.geojson)
                        if station.location
                        else None,
                        "properties": {
                            "type": "pollingstation",
                            "council_id": station.council_id,
                            "internal_council_id": station.internal_council_id,
                            "address": station.address,
                            "color": station_colors[
                                (station.council_id, station.internal_council_id)
                            ],
                            "url": reverse(
                                "dashboard:pollingstation_detail",
                                args=(station.council_id, station.internal_council_id),
                            ),
                        },
                    }
                    for station in stations
                ]
                + [
                    {
                        "type": "Feature",
                        "geometry": json.loads(address.location.geojson)
                        if address.location
                        else None,
                        "properties": {
                            "type": "residentialaddress",
                            "address": address.address,
                            "color": station_colors[
                                (
                                    address.council_id,
                                    address.polling_station_id,
                                )
                            ]
                            if address.polling_station_id
                            else "white",
                            "uprn": address.uprn,
                            "polling_station_id": address.polling_station_id,
                            "url": reverse("address_view", args=(address.uprn,)),
                        },
                    }
                    for address in addresses
                ],
            },
            content_type="application/geo+json",
        )

class PollingStationDetailView(DetailView):
    template_name = "dashboard/pollingstation_detail.html"
    queryset = PollingStation.objects.all()

    def get_object(self, queryset=None):
        return self.queryset.get(
            council_id=self.kwargs["council_pk"], internal_council_id=self.kwargs["id"]
        )


text:
title: Add Elements to the End of an Array Using concat Instead of push
---

## Add Elements to the End of an Array Using concat Instead of push
Where the `push` method adds new element to the end of the orginal array, the `concat` method creates a new array containing the elements from the original array and the new element. The original array remains the same when using `concat`.

#### Relevant Links:
- [Array.prototype.concat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)

## Solution
```javascript
function nonMutatingPush(original, newItem) {

  // Add your code below this line

  return original.concat(newItem);

  // Add your code above this line
}

var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);

```


text:
package com.gyf.ec.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gohuinuo.common.base.BaseController;
import com.gyf.ec.model.EcSuppliers;
import com.gyf.ec.model.EcSuppliersCommodity;
import com.gyf.ec.service.EcCatalogueService;
import com.gyf.ec.service.EcSuppliersCommodityService;
import com.gyf.ec.service.EcSuppliersService;

/**
 * 供应商商品
 * @author Administrator
 *
 */
@Controller
@RequestMapping("ecSuppliersCommodity")
public class EcSuppliersCommodityController extends BaseController {

	@Resource
	private EcSuppliersCommodityService ecSuppliersCommodityService;

	@Resource
	private EcSuppliersService ecSuppliersService;

	@Resource
	private EcCatalogueService ecCatalogueService;

	/**
	 * 跳转到模块页面
	* @param model
	* @return 模块html
	 */
	@RequestMapping
	public String toEcSuppliersCommodity(Model model){
		model.addAttribute("ecCataloue", JSON.toJSONString(ecCatalogueService.findAllEcCatalogue()));
		return "ec/suppliers/suppliersCommodity";
	}

	/**
	 * 供应商分页显示
	* @param params
	* @return
	 */
	@RequestMapping(value="ecSuppliersList",method=RequestMethod.POST)
	public String ecSuppliersList(@RequestParam Map<String, Object> params,Model model){
		PageInfo<EcSuppliers> page = ecSuppliersService.findPageInfo(params);

		model.addAttribute("ecSuppliersPage", page);
		return "ec/suppliers/suppliersCommodity-list";
	}

	/**
	 * 供应商商品分页显示
	 *
	 */
	@RequestMapping(value="ecCommodityList",method=RequestMethod.POST)
	public String ecCommodityList(@RequestParam Map<String, Object> params,Model model,HttpServletRequest request,
			HttpServletResponse response){
		PageHelper.startPage(params);
		HttpSession session = request.getSession();
		Map<Long, EcSuppliersCommodity> scMap = new HashMap<Long, EcSuppliersCommodity>();
		if(session.getAttribute("scMap") != null) {
			scMap = (Map<Long, EcSuppliersCommodity>) session.getAttribute("scMap");
		}
		List<EcSuppliersCommodity> ecSkuList = ecSuppliersCommodityService.findPageInfoSku(params);
		model.addAttribute("commodityPage", new PageInfo<EcSuppliersCommodity>(ecSkuList))
		.addAttribute("scMap", scMap);
		return "ec/suppliers/commodity-list";
	}

	/**
	 * 弹窗显示
	* @param params {"mode":"1.add 2.edit 3.detail}
	* @return
	 */
	@RequestMapping(value="{mode}/showlayer",method=RequestMethod.POST)
	public String layer(Long id,@PathVariable String mode, Model model, HttpServletRequest request,
			HttpServletResponse response){
		String url = "";
		if (StringUtils.equalsIgnoreCase(mode, "edit")) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);
			EcSuppliersCommodity ecSuppliersCommodity = ecSuppliersCommodityService.findscDetail(map);
			model.addAttribute("ecSuppliersCommodity", ecSuppliersCommodity);
			url = "ec/suppliers/commodity-save";
		} else if(StringUtils.equalsIgnoreCase(mode, "editBatch")) {
			HttpSession session = request.getSession();
			Map<Long, EcSuppliersCommodity> scMap = new HashMap<Long, EcSuppliersCommodity>();
			if(session.getAttribute("scMap") != null) {
				scMap = (Map<Long,  EcSuppliersCommodity>) session.getAttribute("scMap");
			}
			model.addAttribute("scMap", scMap);
			url = "ec/suppliers/commodity-saveBatch";
		}
		return url;
	}

	@RequestMapping(value="save",method=RequestMethod.POST)
	public @ResponseBody Integer save(@ModelAttribute EcSuppliersCommodity ecSuppliersCommodity){
		int num = 0;
		num = ecSuppliersCommodityService.updatePurchasePrice(ecSuppliersCommodity);
		return num;
	}

	@RequestMapping(value="saveBatch",method=RequestMethod.POST)
	public @ResponseBody Integer saveBatch(@ModelAttribute EcSuppliersCommodity ecSuppliersCommodity, HttpServletRequest request, HttpServletResponse response){
		HttpSession session = request.getSession();
		Map<Long, EcSuppliersCommodity> scMap = new HashMap<Long, EcSuppliersCommodity>();
		if(session.getAttribute("scMap") != null) {
			scMap = (Map<Long,  EcSuppliersCommodity>) session.getAttribute("scMap");
		}
		int num = 0;
		for(EcSuppliersCommodity esc : scMap.values()) {
			esc.setPurchasePrice(ecSuppliersCommodity.getPurchasePrice());
			num = ecSuppliersCommodityService.updatePurchasePrice(esc);
		}
		if(num != 0) {
			scMap.clear();
		}
		return num;
	}

	// ajax存储被选择的用户(单个)
	@RequestMapping(value = "ajaxChooseUser", method = RequestMethod.POST)
	public @ResponseBody JSONObject ajaxChooseUser(@RequestParam Map<String, Object> params, HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();

		Map<Long, EcSuppliersCommodity> scMap = new HashMap<Long, EcSuppliersCommodity>();
		if(session.getAttribute("scMap") != null) {
			scMap = (Map<Long,  EcSuppliersCommodity>) session.getAttribute("scMap");
		}
		if("false".equals(params.get("flag")) && scMap.containsKey(Long.parseLong(params.get("id") + ""))) {
			scMap.remove(Long.parseLong(params.get("id") + ""));
		} else if("true".equals(params.get("flag"))) {
			EcSuppliersCommodity esc = ecSuppliersCommodityService.findscDetail(params);
			scMap.put(esc.getId(), esc);
		}
		session.setAttribute("scMap", scMap);
		JSONObject obj = new JSONObject();
		return obj;
	}

	// ajax存储被选择的用户(所有)
	@RequestMapping(value = "ajaxChooseAllUser", method = RequestMethod.POST)
	public @ResponseBody JSONObject ajaxChooseAllUser(@RequestParam Map<String, Object> params, HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();

		Map<Long, EcSuppliersCommodity> scMap = new HashMap<Long, EcSuppliersCommodity>();
		String[] ids = (params.get("id") + "").split(",");
		if(session.getAttribute("scMap") != null) {
			scMap = (Map<Long, EcSuppliersCommodity>) session.getAttribute("scMap");
		}
		for(int i = 0; i < ids.length; i++) {
			if("false".equals(params.get("flag")) && scMap.containsKey(Long.parseLong(ids[i]))) {
				scMap.remove(Long.parseLong(ids[i]));
			} else if("true".equals(params.get("flag")))  {
				params.put("id", ids[i]);
				EcSuppliersCommodity esc = ecSuppliersCommodityService.findscDetail(params);
				scMap.put(esc.getId(), esc);
			}
		}
		session.setAttribute("scMap", scMap);
		JSONObject obj = new JSONObject();
		return obj;
	}

}


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

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

  constructor() { }

  ngOnInit() {
  }

}


text:
<?php
// Heading
$_['heading_title']        = 'Extension Installer';

// Text
$_['text_upload']          = 'Upload your extensions';
$_['text_success']         = 'Success: The extension has been installed!';
$_['text_unzip']           = 'Extracting files!';
$_['text_ftp']             = 'Copying files!';
$_['text_sql']             = 'Running SQL!';
$_['text_xml']             = 'Applying modifications!';
$_['text_php']             = 'Running PHP!';
$_['text_remove']          = 'Removing temporary files!';
$_['text_clear']           = 'Success: You have cleared all temporary files!';

// Entry
$_['entry_upload']         = 'Upload File';
$_['entry_overwrite']      = 'Files that will be overwritten';
$_['entry_progress']       = 'Progress';

// Help
$_['help_upload']          = 'Requires a modification file with extension ".ocmod.zip" or ".ocmod.xml".';

// Error
$_['error_permission']     = 'Warning: You do not have permission to modify extensions!';
$_['error_temporary']      = 'Warning: There are some temporary files that require deleting. Click the clear button to remove them!';
$_['error_upload']         = 'File could not be uploaded!';
$_['error_filetype']       = 'Invalid file type!';
$_['error_file']           = 'File could not be found!';
$_['error_unzip']          = 'Zip file could not be opened!';
$_['error_code']           = 'Modification requires a unique ID code!';
$_['error_exists']         = 'Modification %s is using the same ID code as the one you are trying to upload!';
$_['error_directory']      = 'Directory containing files to be uploaded could not be found!';
$_['error_ftp_status']     = 'FTP needs to be enabled in the settings';
$_['error_ftp_connection'] = 'Could not connect as %s:%s';
$_['error_ftp_login']      = 'Could not login as %s';
$_['error_ftp_root']       = 'Could not set root directory as %s';
$_['error_ftp_directory']  = 'Could not change to directory %s';
$_['error_ftp_file']       = 'Could not upload file %s';


text:
#include "tensorflow/lite/kernels/internal/reference/comparisons.h"

#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"
#include "tensorflow/lite/micro/micro_log.h"

namespace tflite {
namespace ops {
namespace micro {
namespace comparisons {
namespace {

struct OpData {
  ComparisonParams params;
};

constexpr int kInputTensor1 = 0;
constexpr int kInputTensor2 = 1;
constexpr int kOutputTensor = 0;

TfLiteStatus EqualEval(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  const OpData* data = static_cast<const OpData*>(node->user_data);

  const TfLiteEvalTensor* input1 =
      tflite::micro::GetEvalInput(context, node, kInputTensor1);
  const TfLiteEvalTensor* input2 =
      tflite::micro::GetEvalInput(context, node, kInputTensor2);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kOutputTensor);

  RuntimeShape input1_shape = tflite::micro::GetTensorShape(input1);
  RuntimeShape input2_shape = tflite::micro::GetTensorShape(input2);
  RuntimeShape output_shape = tflite::micro::GetTensorShape(output);
  bool* output_data = tflite::micro::GetTensorData<bool>(output);

  bool requires_broadcast = !tflite::micro::HaveSameShapes(input1, input2);
  switch (input1->type) {
    case kTfLiteBool:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<bool>(input1), input2_shape,
                tflite::micro::GetTensorData<bool>(input2), output_shape,
                output_data)
          : reference_ops::EqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<bool>(input1), input2_shape,
                tflite::micro::GetTensorData<bool>(input2), output_shape,
                output_data);
      break;
    case kTfLiteFloat32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data)
          : reference_ops::EqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data)
          : reference_ops::EqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt64:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data)
          : reference_ops::EqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt8:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowEqualWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data)
          : reference_ops::EqualWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data);
      break;
    default:
      MicroPrintf("Type %s (%d) not supported.",
                  TfLiteTypeGetName(input1->type), input1->type);
      return kTfLiteError;
  }
  return kTfLiteOk;
}

// TODO(renjieliu): Refactor the logic to avoid duplications.
TfLiteStatus NotEqualEval(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  const OpData* data = static_cast<const OpData*>(node->user_data);

  const TfLiteEvalTensor* input1 =
      tflite::micro::GetEvalInput(context, node, kInputTensor1);
  const TfLiteEvalTensor* input2 =
      tflite::micro::GetEvalInput(context, node, kInputTensor2);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kOutputTensor);

  RuntimeShape input1_shape = tflite::micro::GetTensorShape(input1);
  RuntimeShape input2_shape = tflite::micro::GetTensorShape(input2);
  RuntimeShape output_shape = tflite::micro::GetTensorShape(output);
  bool* output_data = tflite::micro::GetTensorData<bool>(output);

  bool requires_broadcast = !tflite::micro::HaveSameShapes(input1, input2);
  switch (input1->type) {
    case kTfLiteBool:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowNotEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<bool>(input1), input2_shape,
                tflite::micro::GetTensorData<bool>(input2), output_shape,
                output_data)
          : reference_ops::NotEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<bool>(input1), input2_shape,
                tflite::micro::GetTensorData<bool>(input2), output_shape,
                output_data);
      break;
    case kTfLiteFloat32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowNotEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data)
          : reference_ops::NotEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowNotEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data)
          : reference_ops::NotEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt64:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowNotEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data)
          : reference_ops::NotEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt8:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowNotEqualWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data)
          : reference_ops::NotEqualWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data);
      break;
    default:
      MicroPrintf("Type %s (%d) not supported.",
                  TfLiteTypeGetName(input1->type), input1->type);
      return kTfLiteError;
  }
  return kTfLiteOk;
}

TfLiteStatus GreaterEval(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  const OpData* data = static_cast<const OpData*>(node->user_data);

  const TfLiteEvalTensor* input1 =
      tflite::micro::GetEvalInput(context, node, kInputTensor1);
  const TfLiteEvalTensor* input2 =
      tflite::micro::GetEvalInput(context, node, kInputTensor2);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kOutputTensor);

  RuntimeShape input1_shape = tflite::micro::GetTensorShape(input1);
  RuntimeShape input2_shape = tflite::micro::GetTensorShape(input2);
  RuntimeShape output_shape = tflite::micro::GetTensorShape(output);
  bool* output_data = tflite::micro::GetTensorData<bool>(output);

  bool requires_broadcast = !tflite::micro::HaveSameShapes(input1, input2);
  switch (input1->type) {
    case kTfLiteFloat32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowGreaterNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data)
          : reference_ops::GreaterNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowGreaterNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data)
          : reference_ops::GreaterNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt64:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowGreaterNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data)
          : reference_ops::GreaterNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt8:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowGreaterWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data)
          : reference_ops::GreaterWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data);
      break;
    default:
      MicroPrintf("Type %s (%d) not supported.",
                  TfLiteTypeGetName(input1->type), input1->type);
      return kTfLiteError;
  }
  return kTfLiteOk;
}

TfLiteStatus GreaterEqualEval(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  const OpData* data = static_cast<const OpData*>(node->user_data);

  const TfLiteEvalTensor* input1 =
      tflite::micro::GetEvalInput(context, node, kInputTensor1);
  const TfLiteEvalTensor* input2 =
      tflite::micro::GetEvalInput(context, node, kInputTensor2);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kOutputTensor);

  RuntimeShape input1_shape = tflite::micro::GetTensorShape(input1);
  RuntimeShape input2_shape = tflite::micro::GetTensorShape(input2);
  RuntimeShape output_shape = tflite::micro::GetTensorShape(output);
  bool* output_data = tflite::micro::GetTensorData<bool>(output);

  bool requires_broadcast = !tflite::micro::HaveSameShapes(input1, input2);
  switch (input1->type) {
    case kTfLiteFloat32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowGreaterEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data)
          : reference_ops::GreaterEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowGreaterEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data)
          : reference_ops::GreaterEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt64:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowGreaterEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data)
          : reference_ops::GreaterEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt8:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowGreaterEqualWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data)
          : reference_ops::GreaterEqualWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data);
      break;
    default:
      MicroPrintf("Type %s (%d) not supported.",
                  TfLiteTypeGetName(input1->type), input1->type);
      return kTfLiteError;
  }
  return kTfLiteOk;
}

TfLiteStatus LessEval(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  const OpData* data = static_cast<const OpData*>(node->user_data);

  const TfLiteEvalTensor* input1 =
      tflite::micro::GetEvalInput(context, node, kInputTensor1);
  const TfLiteEvalTensor* input2 =
      tflite::micro::GetEvalInput(context, node, kInputTensor2);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kOutputTensor);

  RuntimeShape input1_shape = tflite::micro::GetTensorShape(input1);
  RuntimeShape input2_shape = tflite::micro::GetTensorShape(input2);
  RuntimeShape output_shape = tflite::micro::GetTensorShape(output);
  bool* output_data = tflite::micro::GetTensorData<bool>(output);

  bool requires_broadcast = !tflite::micro::HaveSameShapes(input1, input2);
  switch (input1->type) {
    case kTfLiteFloat32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowLessNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data)
          : reference_ops::LessNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowLessNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data)
          : reference_ops::LessNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt64:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowLessNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data)
          : reference_ops::LessNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt8:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowLessWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data)
          : reference_ops::LessWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data);
      break;
    default:
      MicroPrintf("Type %s (%d) not supported.",
                  TfLiteTypeGetName(input1->type), input1->type);
      return kTfLiteError;
  }
  return kTfLiteOk;
}

TfLiteStatus LessEqualEval(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  const OpData* data = static_cast<const OpData*>(node->user_data);

  const TfLiteEvalTensor* input1 =
      tflite::micro::GetEvalInput(context, node, kInputTensor1);
  const TfLiteEvalTensor* input2 =
      tflite::micro::GetEvalInput(context, node, kInputTensor2);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kOutputTensor);

  RuntimeShape input1_shape = tflite::micro::GetTensorShape(input1);
  RuntimeShape input2_shape = tflite::micro::GetTensorShape(input2);
  RuntimeShape output_shape = tflite::micro::GetTensorShape(output);
  bool* output_data = tflite::micro::GetTensorData<bool>(output);

  bool requires_broadcast = !tflite::micro::HaveSameShapes(input1, input2);
  switch (input1->type) {
    case kTfLiteFloat32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowLessEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data)
          : reference_ops::LessEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<float>(input1), input2_shape,
                tflite::micro::GetTensorData<float>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt32:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowLessEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data)
          : reference_ops::LessEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int32_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int32_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt64:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowLessEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data)
          : reference_ops::LessEqualNoScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int64_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int64_t>(input2), output_shape,
                output_data);
      break;
    case kTfLiteInt8:
      requires_broadcast
          ? reference_ops::Broadcast4DSlowLessEqualWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data)
          : reference_ops::LessEqualWithScaling(
                data->params, input1_shape,
                tflite::micro::GetTensorData<int8_t>(input1), input2_shape,
                tflite::micro::GetTensorData<int8_t>(input2), output_shape,
                output_data);
      break;
    default:
      MicroPrintf("Type %s (%d) not supported.",
                  TfLiteTypeGetName(input1->type), input1->type);
      return kTfLiteError;
  }
  return kTfLiteOk;
}

}  // namespace

void* Init(TfLiteContext* context, const char* buffer, size_t length) {
  TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  return context->AllocatePersistentBuffer(context, sizeof(OpData));
}

TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  OpData* data = static_cast<OpData*>(node->user_data);

  MicroContext* micro_context = GetMicroContext(context);

  TfLiteTensor* input1 =
      micro_context->AllocateTempInputTensor(node, kInputTensor1);
  TF_LITE_ENSURE(context, input1 != nullptr);
  TfLiteTensor* input2 =
      micro_context->AllocateTempInputTensor(node, kInputTensor2);
  TF_LITE_ENSURE(context, input2 != nullptr);

  if (input1->type == kTfLiteInt8) {
    auto input1_offset = -input1->params.zero_point;
    auto input2_offset = -input2->params.zero_point;
    const int kLeftShift = 8;

    int32_t input1_multiplier;
    int input1_shift;
    QuantizeMultiplierSmallerThanOneExp(
        static_cast<double>(input1->params.scale), &input1_multiplier,
        &input1_shift);
    int32_t input2_multiplier;
    int input2_shift;
    QuantizeMultiplierSmallerThanOneExp(
        static_cast<double>(input2->params.scale), &input2_multiplier,
        &input2_shift);

    data->params.left_shift = kLeftShift;
    data->params.input1_offset = input1_offset;
    data->params.input1_multiplier = input1_multiplier;
    data->params.input1_shift = input1_shift;
    data->params.input2_offset = input2_offset;
    data->params.input2_multiplier = input2_multiplier;
    data->params.input2_shift = input2_shift;
  }

  micro_context->DeallocateTempTfLiteTensor(input1);
  micro_context->DeallocateTempTfLiteTensor(input2);

  return kTfLiteOk;
}

}  // namespace comparisons

TfLiteRegistration Register_EQUAL() {
  return tflite::micro::RegisterOp(comparisons::Init, comparisons::Prepare,
                                   comparisons::EqualEval);
}

TfLiteRegistration Register_NOT_EQUAL() {
  return tflite::micro::RegisterOp(comparisons::Init, comparisons::Prepare,
                                   comparisons::NotEqualEval);
}

TfLiteRegistration Register_GREATER() {
  return tflite::micro::RegisterOp(comparisons::Init, comparisons::Prepare,
                                   comparisons::GreaterEval);
}

TfLiteRegistration Register_GREATER_EQUAL() {
  return tflite::micro::RegisterOp(comparisons::Init, comparisons::Prepare,
                                   comparisons::GreaterEqualEval);
}

TfLiteRegistration Register_LESS() {
  return tflite::micro::RegisterOp(comparisons::Init, comparisons::Prepare,
                                   comparisons::LessEval);
}

TfLiteRegistration Register_LESS_EQUAL() {
  return tflite::micro::RegisterOp(comparisons::Init, comparisons::Prepare,
                                   comparisons::LessEqualEval);
}

}  // namespace micro
}  // namespace ops
}  // namespace tflite


text:
import os
import sys
import tft_tuning
import tft_utils
import tft_expr
import tft_sol_exprs
import tft_error_form

import tft_parser

# ========
# sub-routines
# ========
def FinalizeAlloc (fname_atext, alloc, eforms = []) :
    fatext = open(fname_atext, "w")
    fatext.write(str(alloc))
    fatext.close()

    print ("==== FINAL TUNING RESULT ====")
    if (alloc is None):
        print (str(alloc))
    else:
        tft_tuning.PrintAlloc(alloc, eforms)
    print ("=============================")

# ========
# main
# ========
assert(len(sys.argv) >= 3)

# alloc text file
FNAME_ATEXT = "__tft_alloc_text"

# get config file
CONFIG_FILE_NAME = os.path.abspath(sys.argv[1])
tft_tuning.LoadConfig(CONFIG_FILE_NAME)

# get input file name
INPUT_FILE_NAME = sys.argv[2]
eforms, alloc = tft_tuning.TFTRun(INPUT_FILE_NAME)

# -- the first tuning --

FinalizeAlloc(FNAME_ATEXT, alloc, eforms)

# -- additional tuning with more error thresholds --
if (alloc is None):
    print ("WARNING: no additional tuning when the \"base\" allocation is None...")
    exit(1)

assert(tft_sol_exprs.EFORMS is not None)
assert(len(tft_sol_exprs.EFORMS) > 0)
assert(all([isinstance(ef, tft_error_form.ErrorForm) for ef in tft_sol_exprs.EFORMS]))
assert(len(tft_tuning.OPTIMIZERS) > 0)

for ai in range(3, len(sys.argv)):
    af = None
    try:
        af = float(sys.argv[ai])
    except:
        print ("ERROR: invalid additional error threshold: " + str(sys.argv[ai]))

    new_eup = tft_expr.ConstantExpr(af)

    for ef in tft_sol_exprs.EFORMS :
        ef.upper_bound = new_eup

    # solve the error form
    eforms, alloc = tft_sol_exprs.SolveErrorForms(tft_sol_exprs.EFORMS, tft_tuning.OPTIMIZERS)

    print ("==== Additional Allocation with Error Threshold: " + str(new_eup) + " ====")
    FinalizeAlloc(FNAME_ATEXT+"-"+sys.argv[ai], alloc, eforms)


text:
package keeper_test

import (
	"testing"

	sdk "github.com/cosmos/cosmos-sdk/types"
	"github.com/stretchr/testify/require"
	keepertest "github.com/zigbee-alliance/distributed-compliance-ledger/testutil/keeper"
	"github.com/zigbee-alliance/distributed-compliance-ledger/testutil/nullify"
	"github.com/zigbee-alliance/distributed-compliance-ledger/x/pki/keeper"
	"github.com/zigbee-alliance/distributed-compliance-ledger/x/pki/types"
)

func createTestRevokedRootCertificates(keeper *keeper.Keeper, ctx sdk.Context) types.RevokedRootCertificates {
	item := types.RevokedRootCertificates{}
	keeper.SetRevokedRootCertificates(ctx, item)

	return item
}

func TestRevokedRootCertificatesGet(t *testing.T) {
	keeper, ctx := keepertest.PkiKeeper(t, nil)
	item := createTestRevokedRootCertificates(keeper, ctx)
	rst, found := keeper.GetRevokedRootCertificates(ctx)
	require.True(t, found)
	require.Equal(t,
		nullify.Fill(&item),
		nullify.Fill(&rst),
	)
}

func TestRevokedRootCertificatesRemove(t *testing.T) {
	keeper, ctx := keepertest.PkiKeeper(t, nil)
	createTestRevokedRootCertificates(keeper, ctx)
	keeper.RemoveRevokedRootCertificates(ctx)
	_, found := keeper.GetRevokedRootCertificates(ctx)
	require.False(t, found)
}


text:
// Author:  morlovich@google.com (Maksim Orlovich)

#include "pagespeed/kernel/base/mock_message_handler.h"

#include <map>
#include <utility>

#include "pagespeed/kernel/base/abstract_mutex.h"
#include "pagespeed/kernel/base/google_message_handler.h"
#include "pagespeed/kernel/base/message_handler.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/base/writer.h"

namespace net_instaweb {

MockMessageHandler::MockMessageHandler(AbstractMutex* mutex)
    : mutex_(mutex) {
}

MockMessageHandler::~MockMessageHandler() {
}

void MockMessageHandler::MessageSImpl(MessageType type,
                                      const GoogleString& message) {
  ScopedMutex hold_mutex(mutex_.get());
  if (ShouldPrintMessage(message)) {
    internal_handler_.MessageSImpl(type, message);
    GoogleString type_str = MessageTypeToString(type);
    StrAppend(&buffer_, type_str.substr(0, 1), "[Wed Jan 01 00:00:00 2014] [",
              type_str, "] [00000] ", message, "\n");
  } else {
    ++skipped_message_counts_[type];
  }
  ++message_counts_[type];
}

void MockMessageHandler::FileMessageSImpl(MessageType type,
                                          const char* filename, int line,
                                          const GoogleString& message) {
  ScopedMutex hold_mutex(mutex_.get());
  if (ShouldPrintMessage(message)) {
    internal_handler_.FileMessageSImpl(type, filename, line, message);
  } else {
    ++skipped_message_counts_[type];
  }
  ++message_counts_[type];
}

int MockMessageHandler::MessagesOfType(MessageType type) const {
  ScopedMutex hold_mutex(mutex_.get());
  return MessagesOfTypeImpl(message_counts_, type);
}

int MockMessageHandler::SkippedMessagesOfType(MessageType type) const {
  ScopedMutex hold_mutex(mutex_.get());
  return MessagesOfTypeImpl(skipped_message_counts_, type);
}

int MockMessageHandler::MessagesOfTypeImpl(const MessageCountMap& counts,
                                           MessageType type) const {
  MessageCountMap::const_iterator i = counts.find(type);
  if (i != counts.end()) {
    return i->second;
  } else {
    return 0;
  }
}

int MockMessageHandler::TotalMessages() const {
  ScopedMutex hold_mutex(mutex_.get());
  return TotalMessagesImpl(message_counts_);
}

int MockMessageHandler::TotalSkippedMessages() const {
  ScopedMutex hold_mutex(mutex_.get());
  return TotalMessagesImpl(skipped_message_counts_);
}

int MockMessageHandler::TotalMessagesImpl(const MessageCountMap& counts) const {
  int total = 0;
  for (MessageCountMap::const_iterator i = counts.begin();
       i != counts.end(); ++i) {
    total += i->second;
  }
  return total;
}

int MockMessageHandler::SeriousMessages() const {
  ScopedMutex hold_mutex(mutex_.get());
  int num = TotalMessagesImpl(message_counts_) -
       MessagesOfTypeImpl(message_counts_, kInfo);
  return num;
}

void MockMessageHandler::set_mutex(AbstractMutex* mutex) {
  mutex_->DCheckUnlocked();
  mutex_.reset(mutex);
}

void MockMessageHandler::AddPatternToSkipPrinting(
    const char* pattern) {
  patterns_to_skip_.Allow(GoogleString(pattern));
}

bool MockMessageHandler::ShouldPrintMessage(
    const StringPiece& msg) {
  return !patterns_to_skip_.Match(msg, false);
}

bool MockMessageHandler::Dump(Writer* writer) {
  if (buffer_ == "") {
    return false;
  }
  return (writer->Write(buffer_, &internal_handler_));
}

}  // namespace net_instaweb


text:
<?php

namespace Clanmunity\Framework\Core;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Router;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\EventListener\RouterListener;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;

use Clanmunity\Framework\Cache\Cache;
use Clanmunity\Framework\Container\Container;

class Core extends Container implements HttpKernelInterface
{
    /** @var  \Symfony\Component\HttpKernel\HttpKernel */
    protected $kernel;

    /** @var  \Symfony\Component\Routing\RouteCollection */
    protected $routes;

    protected $loader;

    /** @var  \Symfony\Component\HttpKernel\HttpCache\HttpCache */
    protected $useHttpCache;

    /**
     * @param bool $useHttpCache
     */
    public function __construct($useHttpCache = false)
    {
        $this->useHttpCache = $useHttpCache;
    }

    /**
     * @inheritdoc
     */
    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        $this->routes = $this->getRouteCollection();

        // create a context using the current request
        $context = new RequestContext();
        $context->fromRequest($request);

        // matches URL based on a set of routes
        $matcher = new UrlMatcher($this->routes, $context);

        $dispatcher = new EventDispatcher();
        $dispatcher->addSubscriber(new RouterListener($matcher));

        // determine the controller to execute
        $resolver = new ControllerResolver();

        $kernel = new HttpKernel($dispatcher, $resolver);

        if ($this->useHttpCache) {
            $cache = new Cache();
            $kernel = new HttpCache($kernel, new Store($cache->getCacheDir()));
        }

        $response = $kernel->handle($request);

        return $response;
    }

    /**
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function run(Request $request = null)
    {
        if (null === $request) {
            $request = Request::createFromGlobals();
        }

        $response = $this->handle($request);
        $response->send();

        return $response;
    }

    protected function getRouteCollection()
    {
        $routes = new RouteCollection();

        // for each route found in our route_env.yml
        // add it to the route collection
        /*$configDirectories = config.dir;
        $locator = new FileLocator($configDirectories);

        // Loads routes files
        $loader =  new YamlFileLoader($locator);
        return $loader;
        };*/

        $routes->add('hello', new Route('/', array('_controller' =>
           function (Request $request) {
               return new Response(sprintf("Hello %s", $request->get('name')));
           }
        )));

        return $routes;
    }

    public function setUseHttpCache($useHttpCache = false)
    {
        $this->useHttpCache = $useHttpCache;
    }
}


text:
class Enquiry < ActiveRecord::Base
  attr_accessor :phone_country_code

  VALID_EMAIL = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :email, presence: {message: "can not be blank."}, format: {with: VALID_EMAIL}
  validates :name, :telephone, :message, presence: {message: "can not be blank."}

  after_create :send_enquiry_email

  def send_enquiry_email
    EnquiryMailer.enquiry_email(self).deliver
  end

end


text:
package org.headlessintrace.client.connection;

import java.util.List;

import org.headlessintrace.client.connection.command.IAgentCommand;
import org.headlessintrace.client.filter.ITraceFilterExt;
import org.headlessintrace.client.request.BadCompletedRequestListener;

public interface IConnectionList {

	/**
	 * TODO:  Add code to see if we're already connected to this host.
	 * @param host
	 * @param port
	 * @return
	 */
	IConnection locateConnection(HostPort hostPort);

	/**
	 *
	 * @param conn2
	 * @param connectionCallback
	 */
	int disconnect(IConnection conn2,
			IConnectionStateCallback connectionCallback);

	IConnection connect(IConnectionStateCallback connectionCallback,
			HostPort hostPort, IAgentCommand[] startupCommands)
			throws ConnectionException, ConnectionTimeout, BadCompletedRequestListener;

	int size();
	List<IConnection> getConnections();

	IConnection connect(IConnectionStateCallback connectionCallback,
			HostPort hostPort, IAgentCommand[] startupCommands,
			ITraceFilterExt filter) throws ConnectionException,
			ConnectionTimeout, BadCompletedRequestListener;

	void add(HostPort hostPort, IConnection c);

}


text:
import {assert, expect} from 'chai';
import * as moment from 'moment';
import {PaymentAPI} from '../src/PaymentAPI';
import {PaymentHighwayUtility} from '../src/PaymentHighwayUtility';
import {Card} from '../src/model/request/Card';
import {TransactionResponse} from '../src/model/response/TransactionResponse';
import {TransactionRequest} from '../src/model/request/TransactionRequest';
import {CommitTransactionRequest} from '../src/model/request/CommitTransactionRequest';
import {RevertTransactionRequest} from '../src/model/request/RevertTransactionRequest';
import {TransactionStatusResponse} from '../src/model/response/TransactionStatusResponse';
import {Response} from '../src/model/response/Response';
import {OrderSearchResponse} from '../src/model/response/OrderSearchResponse';
import {MasterpassTransactionRequest} from '../src/model/request/MasterpassTransactionRequest';
import {PaymentData} from '../src/model/request/applepay/PaymentData';
import {ApplePayTransaction, ApplePayTransactionRequest} from '../src/model/request/ApplePayTransactionRequest';
import {MobilePayInitRequest} from '../src/model/request/MobilePayInitRequest';
import {Splitting} from '../src/model/Splitting';
import {ChargeMitRequest} from '../src/model/request/ChargeMitRequest';
import {ChargeCitRequest} from '../src/model/request/ChargeCitRequest';
import {ChallengeWindowSize, StrongCustomerAuthentication} from '../src/model/request/sca/StrongCustomerAuthentication';
import {ReturnUrls} from '../src/model/request/sca/ReturnUrls';
import {CustomerDetails} from '../src/model/request/sca/CustomerDetails';
import {PhoneNumber} from '../src/model/request/sca/PhoneNumber';
import {
    AccountAgeIndicator,
    AccountInformationChangeIndicator,
    AccountPasswordChangeIndicator,
    CustomerAccount,
    ShippingAddressFirstUsedIndicator,
    SuspiciousActivityIndicator
} from '../src/model/request/sca/CustomerAccount';
import {
    DeliveryTimeFrame,
    PreOrderPurchaseIndicator,
    Purchase,
    ReorderItemsIndicator,
    ShippingIndicator,
    ShippingNameIndicator
} from '../src/model/request/sca/Purchase';
import {Address} from '../src/model/request/sca/Address';
import {Request} from '../src/model/request/PhRequest';
import {CustomerAuthenticationInfo, Method} from '../src/model/request/sca/CustomerAuthenticationInfo';

let api: PaymentAPI;
let validCard: any;
let testCard: Card;
let scaSoftDeclineCard: Card;

beforeEach(() => {
    api = new PaymentAPI('https://v1-hub-staging.sph-test-solinor.com/', 'testKey', 'testSecret', 'test', 'test_merchantId');
    testCard = new Card('4153013999700024', '2023', '11', '024');
    validCard = {
        card: testCard,
        amount: 99,
        currency: 'EUR',
        blocking: true,
        orderId: PaymentHighwayUtility.createRequestId()
    };
    scaSoftDeclineCard = new Card('4153013999701162', '2023', '11', '162');
});

function createDebitTransaction(orderId?: string, commit?: boolean, splitting?: Splitting, referenceNumber?: string): PromiseLike<TransactionResponse> {
    let initResponse: TransactionResponse;

    return api.initTransaction().then((response) => {
        initResponse = response;
        let transactionRequest = new TransactionRequest(testCard, 9999, 'EUR', orderId, undefined, commit, splitting, referenceNumber);

        return api.debitTransaction(initResponse.id, transactionRequest);
    }).then((debitResponse) => {
        checkResult(debitResponse);
        return initResponse;
    });
}

function checkResult(response: Response): void {
    assert(response.result.code === 100, 'Request should succeed with code 100, complete response was: ' + JSON.stringify(response));
    assert(response.result.message === 'OK', 'Request should succeed with message "OK", complete response was: ' + JSON.stringify(response));
}

function printResult(response: Response): string {
    return ', complete result was: \n' + JSON.stringify(response);
}

function getFullStrongCustomerAuthenticationData(): StrongCustomerAuthentication {

    const returnUrls = ReturnUrls.Builder(
        'https://example.com/success',
        'https://example.com/cancel',
        'https://example.com/failure'
    ).setWebhookSuccessUrl('https://example.com/webhook/success')
        .setWebhookCancelUrl('https://example.com/webhook/cancel')
        .setWebhookFailureUrl('https://example.com/webhook/failure')
        .setWebhookDelay(0)
        .build();

    const customerDetails = CustomerDetails.Builder()
        .setShippingAddressMatchesBillingAddress(true)
        .setName('Eric Example')
        .setEmail('eric.example@example.com')
        .setHomePhone(new PhoneNumber('358', '123456789'))
        .setMobilePhone(new PhoneNumber('358', '441234566'))
        .setWorkPhone(new PhoneNumber('358', '441234566'))
        .build();

    const customerAccount = CustomerAccount.Builder()
        .setAccountAgeIndicator(AccountAgeIndicator.MoreThan60Days)
        .setAccountDate('2018-07-05')
        .setChangeIndicator(AccountInformationChangeIndicator.MoreThan60Days)
        .setChangeDate('2018-09-11')
        .setPasswordChangeIndicator(AccountPasswordChangeIndicator.NoChange)
        .setPasswordChangeDate('2018-07-05')
        .setNumberOfRecentPurchases(7)
        .setNumberOfAddCardAttemptsDay(1)
        .setNumberOfTransactionActivityDay(3)
        .setNumberOfTransactionActivityYear(8)
        .setShippingAddressIndicator(ShippingAddressFirstUsedIndicator.Between30And60Days)
        .setShippingAddressUsageDate('2019-07-01')
        .setSuspiciousActivity(SuspiciousActivityIndicator.NoSuspiciousActivity)
        .build();

    const purchase = Purchase.Builder()
        .setShippingIndicator(ShippingIndicator.ShipToCardholdersAddress)
        .setDeliveryTimeFrame(DeliveryTimeFrame.SameDayShipping)
        .setDeliveryEmail('eric.example@example.com')
        .setReorderItemsIndicator(ReorderItemsIndicator.FirstTimeOrdered)
        .setPreOrderPurchaseIndicator(PreOrderPurchaseIndicator.MerchandiseAvailable)
        .setPreOrderDate('2019-08-20')
        .setShippingNameIndicator(ShippingNameIndicator.AccountNameMatchesShippingName)
        .setGiftCardAmount(200)
        .setGiftCardCount(7)
        .build();

    const billingAddress = Address.Builder()
        .setCity('Helsinki')
        .setCountry('246')
        .setAddressLine1('Arkadiankatu 1')
        .setAddressLine2('')
        .setAddressLine3('')
        .setPostCode('00101')
        .setState('18')
        .build();

    const shippingAddress = Address.Builder()
        .setCity('Helsinki')
        .setCountry('246')
        .setAddressLine1('Arkadiankatu 1')
        .setAddressLine2('')
        .setAddressLine3('')
        .setPostCode('00101')
        .setState('18')
        .build();

    const customerAuthenticationInfo = CustomerAuthenticationInfo.Builder()
        .setMethod(Method.OwnCredentials)
        .build();

    return StrongCustomerAuthentication.Builder(returnUrls)
        .setCustomerDetails(customerDetails)
        .setCustomerAccount(customerAccount)
        .setPurchase(purchase)
        .setBillingAddress(billingAddress)
        .setShippingAddress(shippingAddress)
        .setCustomerAuthenticationInfo(customerAuthenticationInfo)
        .setDesiredChallengeWindowSize(ChallengeWindowSize.Window600x400)
        .setExitIframeOnResult(false)
        .setExitIframeOnThreeDSecure(false)
        .build();
}

describe('PaymentAPI', () => {
    it('Should have instance of PaymentHighwayAPI', () => {
        assert.instanceOf(api, PaymentAPI, 'Was not instance of PaymentAPI');
    });

    it('Test init transaction', () => {
        return api.initTransaction().then((body) => {
            checkResult(body);
            assert.isNotNull(body.id, 'Transaction init should return id');
        });
    });

    it('Test debit transaction', () => {
        return createDebitTransaction().then((body) => {
            assert.isNotNull(body.id, 'Transaction id not received');
        });
    });

    it('Test charge merchant initiated transaction', async () => {
        const initResponse = await api.initTransaction();

        const chargeMitRequest = ChargeMitRequest.Builder(9999, 'EUR', 'order1')
            .setCard(testCard)
            .build();
        const chargeResponse = await api.chargeMerchantInitiatedTransaction(initResponse.id, chargeMitRequest);

        checkResult(chargeResponse);
    });

    it('Test charge merchant initiated transaction should throw an exception if card or token is not defined', async () => {
        expect(() => ChargeMitRequest.Builder(9999, 'EUR', 'order1').build())
            .to.throw('Either card or token must be defined');
    });

    it('Test charge customer initiated transaction', async () => {
        const initResponse = await api.initTransaction();

        const strongCustomerAuthentication = StrongCustomerAuthentication.Builder(
            ReturnUrls.Builder(
                'https://example.com/success',
                'https://example.com/cancel',
                'https://example.com/failure'
            ).build()
        ).build();

        const chargeCitRequest = ChargeCitRequest.Builder(9999, 'EUR', 'testorder1', strongCustomerAuthentication)
            .setCard(testCard)
            .build();
        const chargeResponse = await api.chargeCustomerInitiatedTransaction(initResponse.id, chargeCitRequest);

        checkResult(chargeResponse);
    });

    it('Test charge customer initiated transaction should throw an exception if card or token is not defined', async () => {
        const strongCustomerAuthentication = StrongCustomerAuthentication.Builder(
            ReturnUrls.Builder(
                'https://example.com/success',
                'https://example.com/cancel',
                'https://example.com/failure'
            ).build()
        ).build();

        expect(() => ChargeCitRequest.Builder(9999, 'EUR', 'order1', strongCustomerAuthentication).build())
            .to.throw('Either card or token must be defined');
    });

    it('Test charge customer initiated transaction with full SCA data', async () => {
        const initResponse = await api.initTransaction();

        const strongCustomerAuthentication = getFullStrongCustomerAuthenticationData();

        const chargeCitRequest = ChargeCitRequest.Builder( 9999, 'EUR', 'testorder1', strongCustomerAuthentication)
            .setCard(testCard)
            .build();
        const chargeResponse = await api.chargeCustomerInitiatedTransaction(initResponse.id, chargeCitRequest);

        checkResult(chargeResponse);
    });

    it('Test soft-decline of customer initiated transaction', async () => {
        const initResponse = await api.initTransaction();

        const strongCustomerAuthentication = StrongCustomerAuthentication.Builder(
            ReturnUrls.Builder(
                'https://example.com/success',
                'https://example.com/cancel',
                'https://example.com/failure'
            ).build()
        ).build();

        const chargeCitRequest = ChargeCitRequest.Builder(100, 'EUR', 'order1', strongCustomerAuthentication)
            .setCard(scaSoftDeclineCard)
            .build();
        const chargeResponse = await api.chargeCustomerInitiatedTransaction(initResponse.id, chargeCitRequest);

        assert(chargeResponse.result.code === 400, 'Request should have been soft declined with code 400, complete response was: ' + JSON.stringify(chargeResponse));
        assert.isNotNull(chargeResponse.three_d_secure_url, '3D Secure url not received');
    });

    it('Test commit transaction', () => {
        const commitRequest = new CommitTransactionRequest(9999, 'EUR');
        let transactionId: string;
        return createDebitTransaction('12345ABC', false)
            .then((initResponse) => {
                transactionId = initResponse.id;
                return api.commitTransaction(transactionId, commitRequest);
            })
            .then((commitResponse) => {
                checkResult(commitResponse);
                assert(commitResponse.card.type === 'Visa', 'Card type should be "Visa"' + printResult(commitResponse));
                assert(commitResponse.card.cvc_required === 'not_tested', 'Test card should return cvc_required = not_tested' + printResult(commitResponse));
                assert(commitResponse.recurring === false, 'Transaction should have recurring as false.' + printResult(commitResponse));

                assert(true === /^[0-9a-f]{64}$/.test(commitResponse.card.card_fingerprint), 'Card fingerprint didn\'t contain 64 hex chars');
                assert(true === /^[0-9a-f]{64}$/.test(commitResponse.card.pan_fingerprint), 'Pan fingerprint didn\'t contain 64 hex chars');

                return api.transactionResult(transactionId);
            })
            .then((resultResponse) => {
                assert(resultResponse.recurring === false, 'Transaction result should have recurring false.' + printResult(resultResponse));
                checkResult(resultResponse);
            });
    });

    it('Test uncommitted transaction', () => {
        let transactionId: string;
        return createDebitTransaction('12345DEF', false)
            .then((initResponse) => {
                transactionId = initResponse.id;
            });
    });

    it('Test revert transaction', () => {
        return createDebitTransaction()
            .then((initResponse) => {
                return api.revertTransaction(initResponse.id, new RevertTransactionRequest(9999));
            })
            .then((revertResponse) => {
                checkResult(revertResponse);
            });
    });

    it('Test revert whole transaction', () => {
        let transactionId: string;
        return createDebitTransaction()
            .then((initResponse) => {
                transactionId = initResponse.id;
                return api.revertTransaction(transactionId, new RevertTransactionRequest());
            })
            .then((revertResponse) => {
                checkResult(revertResponse);
                return api.transactionStatus(transactionId);
            })
            .then((statusResponse: TransactionStatusResponse) => {
                checkResult(statusResponse);
                assert(statusResponse.transaction.current_amount === 0, 'Transaction current amount should be 0' + printResult(statusResponse));
                assert(statusResponse.transaction.id === transactionId, 'Transaction id should be same with init response and revert response' + printResult(statusResponse));
            });
    });

    it('Test transaction status', () => {
        let transactionId: string;

        const referenceNumber = "1313";

        return createDebitTransaction(null, null, null, referenceNumber)
            .then((initResponse) => {
                transactionId = initResponse.id;
                return api.revertTransaction(transactionId, new RevertTransactionRequest(9950));
            })
            .then(() => {
                return api.transactionStatus(transactionId);
            })
            .then((statusResponse: TransactionStatusResponse) => {
                checkResult(statusResponse);
                assert(statusResponse.transaction.current_amount === 49, 'Current amount should be 49, it was ' + statusResponse.transaction.current_amount + printResult(statusResponse));
                assert(statusResponse.transaction.id === transactionId, 'Transaction id should be same with init response and revert response' + printResult(statusResponse));
                assert(statusResponse.transaction.card.cvc_required === 'not_tested', 'Test card should return cvc_required = not_tested' + printResult(statusResponse));
                assert(statusResponse.transaction.reference_number === referenceNumber, 'Transaction reference number mismatch' + printResult(statusResponse));
            });
    });

    it('Test splitting in transaction status', () => {
      let transactionId: string;

      let subMerchantId = '12345';
      let amountToSubMerchant = 9000;

      let splitting = new Splitting(subMerchantId, amountToSubMerchant);

      return createDebitTransaction(undefined, undefined, splitting)
        .then((initResponse) => {
          transactionId = initResponse.id;
          return api.transactionStatus(transactionId);
        })
        .then((statusResponse: TransactionStatusResponse) => {
          checkResult(statusResponse);
          assert(statusResponse.transaction.splitting.merchant_id === subMerchantId, 'Status response should contain matching splitting merchant ID');
          assert(statusResponse.transaction.splitting.amount === amountToSubMerchant, 'Status response should contain matching splitting amount');
        });
    });

    it('Test order search', () => {
        let transactionId: string;
        const orderId = PaymentHighwayUtility.createRequestId();
        return createDebitTransaction(orderId)
            .then((initResponse) => {
                transactionId = initResponse.id;
                return api.searchOrders(orderId);
            })
            .then((searchResponse: OrderSearchResponse) => {
                checkResult(searchResponse);
                assert(searchResponse.transactions[0].current_amount === 9999, 'Current amount for tested order should be 9999, it was: ' + searchResponse.transactions[0].current_amount + printResult(searchResponse));
                assert(searchResponse.transactions[0].id === transactionId, 'Transaction id should be same with init response and search response' + printResult(searchResponse));
                assert(searchResponse.transactions[0].recurring === false, 'Transaction should have recurring false' + printResult(searchResponse));
            });
    });

    it('Test daily batch report', () => {
        const date = moment().add(1, 'days').format('YYYYMMDD');
        return api.fetchDailyReport(date)
            .then((reportResponse) => {
                checkResult(reportResponse);
            });
    });

    it('Test rejected debit response', () => {
        const testCardTokenizeOkPaymentFails = new Card('4153013999700156', '2023', '11', '156');
        const orderId = PaymentHighwayUtility.createRequestId();
        let transactionResponse: TransactionResponse;
        return api.initTransaction()
            .then((response) => {
                transactionResponse = response;
                const transactionRequest = new TransactionRequest(testCardTokenizeOkPaymentFails, 9999, 'EUR', orderId);
                return api.debitTransaction(transactionResponse.id, transactionRequest);
            })
            .then((debitResponse) => {
                assert(debitResponse.result.code === 200, 'Authorization should fail (code 200), got ' + debitResponse.result.code);
                assert(debitResponse.result.message === 'Authorization failed', 'Authorization should fail');
                return api.transactionResult(transactionResponse.id);
            })
            .then((resultResponse) => {
                assert(resultResponse.result.code === 200, 'Authorization should fail (code 200), got ' + resultResponse.result.code);
                return api.transactionStatus(transactionResponse.id);
            })
            .then((statusResponse) => {
                assert(statusResponse.transaction.committed === false, 'Committed should be false, got' + statusResponse.transaction.committed);
            });
    });

    it('Test Masterpass transaction', () => {
        const preGeneratedMasterpassTransaction = '327c6f29-9b46-40b9-b85b-85e908015d92';

        return api.userProfile(preGeneratedMasterpassTransaction)
            .then((userProfileResponse) => {
                checkResult(userProfileResponse);

                const masterpass = userProfileResponse.masterpass;
                assert(masterpass.amount === 100);
                assert(masterpass.currency === 'EUR');
                assert(masterpass.masterpass_wallet_id === '101');

                const profile = userProfileResponse.profile;
                assert(profile.email_address === 'matti.meikalainen@gmail.com');
                assert.isNotNull(profile.billing_address);
                assert(profile.billing_address.country === 'FI');
                assert.isNotNull(profile.shipping_address);
                assert(profile.shipping_address.country === 'FI');

                const request = new MasterpassTransactionRequest(50, 'EUR');
                return api.debitMasterpassTransaction(preGeneratedMasterpassTransaction, request);
            })
            .then((debitResponse) => {
                checkResult(debitResponse);
            });
    });

    it('Test Apple Pay request builders', () => {
        let amount = 100;
        let currency = 'EUR';

        let paymentToken: PaymentData = JSON.parse('{ "data": "ABCD", "header": { "ephemeralPublicKey": "XYZ", "publicKeyHash": "13579", "transactionId": "24680" }, "signature": "ABCDXYZ0000", "version": "EC_v1" }');
        assert.strictEqual(paymentToken.data, 'ABCD', 'Data was not equal to ABCD');

        let withStaticBuilder = withoutRequestId(ApplePayTransactionRequest.Builder(paymentToken, amount, currency).build());
        let withRequestBuilder = withoutRequestId(new ApplePayTransaction.RequestBuilder(paymentToken, amount, currency).build());

        assert.deepEqual(withStaticBuilder, withRequestBuilder, 'results differ from builder');

        let requestWithCommit = withoutRequestId(ApplePayTransactionRequest.Builder(paymentToken, amount, currency).setCommit(true).build());
        assert.notDeepEqual(withStaticBuilder, requestWithCommit, 'requests should differ if commit is added');

        assert(withStaticBuilder.amount === 100);
    });

    function withoutRequestId<T extends Request>(request: T): any {
        let copy = Object.assign({}, request);
        delete copy.requestId;
        return copy;
    }

    it('Test Apple Pay validators', () => {
        let amount = 100;
        let currency = 'EUR';

        // Syntax is valid, but content will fail
        let paymentToken: PaymentData = JSON.parse('{ "data": "ABCD", "header": { "ephemeralPublicKey": "XYZ=", "publicKeyHash": "13579ABC", "transactionId": "0002040608" }, "signature": "ABCD13579ABC", "version": "EC_v1" }');

        return api.initTransaction()
            .then((response) => {
                const request = ApplePayTransactionRequest.Builder(paymentToken, amount, currency).build();
                return api.debitApplePayTransaction(response.id, request);
            })
            .then((debitResponse) => {
                assert(debitResponse.result.code === 900, 'Authorization should fail (code 900), got ' + debitResponse.result.code);
                assert.equal(debitResponse.result.message, 'ERROR', 'Authorization should fail with ERROR, validation should succeed');
            });
    });

    it( 'Test MobilePay app flow init @external', () => {
        const request = MobilePayInitRequest.Builder(100, 'EUR')
            .setOrder(PaymentHighwayUtility.createRequestId())
            .setReturnUri('myapp://paid')
            .setWebhookSuccessUrl('https://myserver.com/success')
            .setWebhookCancelUrl('https://myserver.com/cancel')
            .setWebhookFailureUrl('https://myserver.com/failure')
            .build();

        return api.initMobilePaySession(request).then((response) => {
           assert.isNotNull(response.uri);
           assert.isNotNull(response.session_token);
           assert.isNotNull(response.valid_until);
           assert.containIgnoreCase(response.uri, response.session_token, 'Returned app URI should contain session token.');
        });
    });

    it('Test MobilePay app flow session status @external', () => {
        const request = MobilePayInitRequest.Builder(100, 'EUR')
            .setOrder(PaymentHighwayUtility.createRequestId())
            .setReturnUri('myapp://paid')
            .setWebhookSuccessUrl('https://myserver.com/success')
            .setWebhookCancelUrl('https://myserver.com/cancel')
            .setWebhookFailureUrl('https://myserver.com/failure')
            .build();

        return api.initMobilePaySession(request).then((initResponse) => {
            return api.mobilePaySessionStatus(initResponse.session_token).then((response) => {
                assert.equal(response.status, 'in_progress');
                assert.equal(response.valid_until, initResponse.valid_until, 'Both init and status check should have same valid until value.');
                assert.isUndefined(response.transaction_id); // transaction id is available only when session is finished
            });
        });
    });
});


text:
package org.capcaval.ccoutils.unittest;

public enum TestStatus {
	ok_test_passed, fail_timeout, fail_assertfalse
}


text:
import re
from io import BytesIO

import trml2pdf
from django.core.mail import EmailMultiAlternatives
from django.template.loader import select_template
from django.urls import reverse
from django.utils.functional import cached_property
from django.utils.text import slugify
from PyPDF2 import PdfFileReader, PdfFileWriter

from ..conf import settings
from .leprikonsite import LeprikonSite
from .printsetup import PrintSetup
from .utils import shorten

whitespace = re.compile(r"\s+")

class PdfExportAndMailMixin(object):
    all_attachments = []
    all_recipients = []
    object_name = "generic"

    def get_absolute_url(self):
        return reverse(f"leprikon:{self.object_name}_pdf", kwargs={"pk": self.pk, "slug": self.slug})

    def get_attachments(self, event):
        return None

    def get_context(self, event):
        return {
            "event": event,
            "pdf_filename": self.get_pdf_filename(event),
            "print_setup": self.get_print_setup(event),
            "object": self,
            "site": LeprikonSite.objects.get_current(),
        }

    def get_mail_subject(self, event):

        return self.mail_subject_patterns[event].format(
            subject_type=self.subject.subject_type.name_akuzativ,
            subject=self.subject.name,
        )

    def get_print_setup(self, event):
        return PrintSetup()

    def get_template_variants(self):
        return ("default",)

    def select_template(self, event, suffix):
        return select_template(
            [
                "leprikon/{}_{}/{}.{}".format(self.object_name, event, variant, suffix)
                for variant in self.get_template_variants()
            ]
        )

    def send_mail(self, event="received"):
        template_subject = self.select_template(event, "subject.txt")
        template_txt = self.select_template(event, "txt")
        template_html = self.select_template(event, "html")
        context = self.get_context(event)
        content_subject = template_subject.render(context)
        content_txt = template_txt.render(context)
        content_html = template_html.render(context)
        subject = whitespace.sub(" ", content_subject).strip()
        EmailMultiAlternatives(
            subject=subject,
            body=content_txt.strip(),
            from_email=settings.SERVER_EMAIL,
            to=self.all_recipients,
            headers={"X-Mailer": "Leprikon (http://leprikon.cz/)"},
            alternatives=[(content_html, "text/html")],
            attachments=self.get_attachments(event),
        ).send()

    @cached_property
    def slug(self):
        return shorten(slugify(self), 100)

    def get_pdf_filename(self, event):
        return self.slug + ".pdf"

    def get_pdf_attachment(self, event):
        return (self.get_pdf_filename(event), self.get_pdf(event), "application/pdf")

    def get_pdf(self, event):
        output = BytesIO()
        self.write_pdf(event, output)
        output.seek(0)
        return output.read()

    def write_pdf(self, event, output):
        # get plain pdf from rml
        template = self.select_template(event, "rml")
        rml_content = template.render(self.get_context(event))
        pdf_content = trml2pdf.parseString(rml_content.encode("utf-8"))
        print_setup = self.get_print_setup(event)

        # merge with background
        if print_setup.background:
            template_pdf = PdfFileReader(print_setup.background.file)
            registration_pdf = PdfFileReader(BytesIO(pdf_content))
            writer = PdfFileWriter()
            # merge pages from both template and registration
            for i in range(registration_pdf.getNumPages()):
                if i < template_pdf.getNumPages():
                    page = template_pdf.getPage(i)
                    page.mergePage(registration_pdf.getPage(i))
                else:
                    page = registration_pdf.getPage(i)
                writer.addPage(page)
            # write result to output
            writer.write(output)
        else:
            # write basic pdf registration to response
            output.write(pdf_content)
        return output


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-styles/typography.html">

<dom-module id="training-book">
<template>
	<style include="shared-styles" is="custom-style">
		:host {
			display: block;
		}

		tab_w_content{
			color: blue;
			background-color: red;
		}

	</style>

	<iron-pages selected="{{selectedPage}}">
	<div>
	<template is="dom-if" if="[[days.length]]" >
		<paper-tabs selected="{{selectedTraining}}" attr-for-selected="training" scrollable>
			<template is="dom-repeat" items="[[days]]" as="d" >

				<paper-tab
					hidden$="{{!d}}"
					training="{{d}}"
					class$="{{_hasContent(d.logs)}}">[[d.dayNumber]]</paper-tab>
			</template>
		</paper-tabs>
		<template is="dom-repeat" items="[[selectedTraining.logs]]" as="t" >
			<training-book-page training="{{t}}"></training-book-page>
		</template>
		<paper-button on-tap="_newTraining">Nouvelle entrée</paper-button>
	</template>
	</div>

</template>

<script>
	(function() {
		'use strict';

		Polymer({
			is: 'training-book',

			properties: {
				selectedPage: {
					type: Number,
					value: 0,
				},
				days: {
					type: Array,
					notify: true
					//observer: '_renderCalendar'
				},
				diff: 0
			},
			_hasContent: function(arr){
				if(arr){
					if(arr.length > 0)
						return 'tab_w_content';
				}
				return '';
			},
			_newTraining: function(e){
				this.fire('add-training', {training: this.selectedTraining});
			}
		});
	})();
</script>
</dom-module>


text:
Processing.jl
=============

A port of the Processing language (https://www.processing.org) to Julia.

It mainly uses ModernGL.jl and GLFW.jl behind the scenes. Please note that this package assumes that you have a graphics card/driver which supports OpenGL 3.2 or greater. If your computer is about 4-5 years old, then that is most likely the case. A convience function will soon be added to easily report what versions of OpenGL your card supports. In the worst case scenario, you can fall back onto a 2D-only Cairo/TK supported backend by importing the Processing2D.jl file, rather than entering "using Processing". See the "basic2D.jl" example in the "test/" directory for demo of how to go about this easily.

At the moment, this package is based on "hand-written" code, in order to see how much speed can be attained in a raw OpenGL setting. That code is slowly being transferred to the GLAbstraction.jl, GLWindow.jl, and GLVisualize.jl packages and those packages will eventually become the main support for Processing.jl. This development will take place in a separate branch. The master branch will remain the recommended version for the time being, since it is tested and mostly stable. Any bug fixes will be ported to both branches.

# Installation

## Mac OS X

This package is developed on a 13" Macbook Pro with an Intel card. So far, my experience is that on OS X 10.10 and 10.11, everything just works. However, the assumption is made that you have a Retina screen if you are using a Mac. This will be amended soon. Anyway, to install, just run the following:

```julia
Pkg.clone("https://github.com/SimonDanisch/FreeTypeAbstraction.jl.git")
Pkg.clone("https://github.com/rennis250/Processing.jl.git")
```

## Linux

Only tested on Ubuntu 14.04 LTS with the opensource ATI drivers. First, make sure that the required packages for GLFW.jl are installed:

```julia
sudo apt-get update
sudo apt-get install cmake xorg-dev libglu1-mesa-dev
```

(Note: I found that cmake was not installed on the machine that I was using. The GLFW C code assumes that you have cmake installed, so we installed via apt-get here.)

Then, install the rest as usual:

```julia
Pkg.clone("https://github.com/SimonDanisch/FreeTypeAbstraction.jl.git")
Pkg.clone("https://github.com/rennis250/Processing.jl.git")
```

## Windows

Only tested on a Windows 7 machine with an ATI card. Install the package as usual:

```julia
Pkg.clone("https://github.com/SimonDanisch/FreeTypeAbstraction.jl.git")
Pkg.clone("https://github.com/rennis250/Processing.jl.git")
```

# Caveats

For some features, such as alpha blending or point smoothing, we ask OpenGL to simply perform this operation. This means that it will depend on the algorithms that your graphics card supplier/driver has implemented. I have already noticed visible differences between rendering on Windows and Mac. These differences should soon be amended with our own shader-based implementations of these functions.

# Credit

Processing is an open graphics programming language developed by Ben Fry & Casey Reas. This port was developed by Robert Ennis with the help of @SimonDanisch and @o-jasper. It is mainly maintained by Robert Ennis.


text:
package org.dcache.nfs.v4.xdr;
import org.dcache.xdr.*;
import java.io.IOException;

public class retention_set4 implements XdrAble {
    public boolean rs_enable;
    public uint64_t [] rs_duration;

    public retention_set4() {
    }

    public retention_set4(XdrDecodingStream xdr)
           throws OncRpcException, IOException {
        xdrDecode(xdr);
    }

    public void xdrEncode(XdrEncodingStream xdr)
           throws OncRpcException, IOException {
        xdr.xdrEncodeBoolean(rs_enable);
        { int $size = rs_duration.length; xdr.xdrEncodeInt($size); for ( int $idx = 0; $idx < $size; ++$idx ) { rs_duration[$idx].xdrEncode(xdr); } }
    }

    public void xdrDecode(XdrDecodingStream xdr)
           throws OncRpcException, IOException {
        rs_enable = xdr.xdrDecodeBoolean();
        { int $size = xdr.xdrDecodeInt(); rs_duration = new uint64_t[$size]; for ( int $idx = 0; $idx < $size; ++$idx ) { rs_duration[$idx] = new uint64_t(xdr); } }
    }

}
// End of retention_set4.java


text:
import Koa from 'koa';
import bodyParser  from 'koa-bodyparser';
import path from "path";
import serialize from 'serialize-javascript';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Provider } from 'mobx-react';
import {match, RouterContext, Router, IndexRoute, Route, createMemoryHistory} from 'react-router';
import {renderToString} from 'react-dom/server';
import renderHtmlPage from './renderHtmlPage';

const Thinky = require('thinky');
const serve = require('koa-static');

import koaRoutes from './routes';
import reactRoutes from '../client/react/routes';
import {usePassport} from './middlewares';
import * as stores from '../client/react/stores';
import log from './utils/log';
import config from '../config';

const app = new Koa();

if (__DEV__) {
    log.info('web packing')
    const webpack = require('webpack');
    const webpackConfig = require('../../tools/webpack');
    const webpackDevMiddleware = require('koa-webpack-dev-middleware');
    const webpackHostMiddleware = require('koa-webpack-hot-middleware');
    const compiler = webpack(webpackConfig);

    app.use(webpackDevMiddleware(compiler, {
        noInfo: true,
        publicPath: webpackConfig.output.publicPath,
        hot: true,
        stats: { colors: true }
    }));

    app.use(webpackHostMiddleware(compiler));
}

app.use(bodyParser());

usePassport(app);

app.use(serve(config.directories.dist));

koaRoutes(app);

app.use((ctx, next) => {
    if (__DEV__) {
        global.webpackIsomorphicTools.refresh();
    }

    const location = ctx.request.url;
    const history = createMemoryHistory(location);
    match({ routes: reactRoutes, location, history }, (error, redirectLocation, renderProps) => {
        if (error) {
            log.error(error);
        } else if (redirectLocation) {
            log.debug('status: 302');
            ctx.response.redirect(302, redirectLocation.pathname + redirectLocation.search);
        } else if (renderProps) {
            log.debug('status: 200');

            const serverRender = renderToString(
                <Provider {...stores}>
                    <div>
                        <RouterContext {...renderProps} />
                    </div>
                </Provider>
            );

            try {
                ctx.response.set('content-type', 'text/html');
                ctx.response.status = 200;
                ctx.response.body = renderHtmlPage(serverRender);
            } catch (error) {
                log.error(error);
            }

        } else {
            next();
        }
    });
});

app.listen(config.server.port, () => {
    console.log(`server is running, port ${config.server.port}`);
});


text:
import tkinter
import tkinter.font

from .pomodoro import Pomodoro

class App:
    def __init__(self, master):
        self.master = master

        font = tkinter.font.Font(
            family="Helvetica", size=50, weight=tkinter.font.BOLD)
        self.pomodoro_count_text = tkinter.StringVar()
        tkinter.Label(master, textvariable=self.pomodoro_count_text,
                      justify=tkinter.constants.CENTER).grid(row=0, columnspan=2)
        self.time_left = tkinter.StringVar()
        tkinter.Label(master, textvariable=self.time_left, font=font, width=5).grid(
            row=1, columnspan=2, sticky=tkinter.constants.W)

        self.start_text = tkinter.StringVar()
        self.start_button = tkinter.Button(
            master, textvariable=self.start_text, command=self.start_clicked)
        self.reset_button = tkinter.Button(
            master, text="Reset", command=self.reset_pomodoro_count)

        self.start_button.grid(row=2, column=0)
        self.reset_button.grid(row=2, column=1)

        self.reset_pomodoro_count()
        self.reset_time_left()
        self.start_text.set("Start")

    def update_pomodoro_count(self):
        self.pomodoro_count_text.set("%d completed" % self._pomodoro_count)
        if self._pomodoro_count == 0:
            self.reset_button.config(state=tkinter.constants.DISABLED)
        else:
            self.reset_button.config(state=tkinter.constants.ACTIVE)

    def increase_pomodoro_count(self):
        self._pomodoro_count += 1
        self.update_pomodoro_count()

    def reset_pomodoro_count(self):
        self._pomodoro_count = 0
        self.update_pomodoro_count()

    def reset_time_left(self):
        self.time_left.set("00:00")
        self.master.wm_title("Pomodoro")

    def start_clicked(self):
        self.start_text.set("Cancel")
        pomodoro = Pomodoro()
        stoppable = pomodoro.start(self.on_pomodoro_step, self.on_pomodoro_end)
        self.start_button.configure(
            command=lambda: self.cancel_clicked(stoppable))

    def on_pomodoro_step(self, min_left, sec_left):
        self.time_left.set("%02d:%02d" % (min_left, sec_left))
        self.master.wm_title(self.time_left.get())

    def on_pomodoro_end(self, completed):
        self.start_text.set("Start")
        self.start_button.configure(command=self.start_clicked)
        self.reset_time_left()
        if completed:
            self.increase_pomodoro_count()

    def cancel_clicked(self, stoppable):
        stoppable.stop()

def main():
    root = tkinter.Tk()
    root.wm_title("Pomodoro")
    app = App(root)
    root.mainloop()

if __name__ == "__main__":
    main()


text:
#pragma once
#include <aws/network-firewall/NetworkFirewall_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace NetworkFirewall
{
namespace Model
{
  enum class ResourceManagedStatus
  {
    NOT_SET,
    MANAGED,
    ACCOUNT
  };

namespace ResourceManagedStatusMapper
{
AWS_NETWORKFIREWALL_API ResourceManagedStatus GetResourceManagedStatusForName(const Aws::String& name);

AWS_NETWORKFIREWALL_API Aws::String GetNameForResourceManagedStatus(ResourceManagedStatus value);
} // namespace ResourceManagedStatusMapper
} // namespace Model
} // namespace NetworkFirewall
} // namespace Aws