text:
package com.amazonaws.services.connectcontactlens.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.connectcontactlens.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CategoryDetailsMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CategoryDetailsMarshaller {

    private static final MarshallingInfo<List> POINTSOFINTEREST_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PointsOfInterest").build();

    private static final CategoryDetailsMarshaller instance = new CategoryDetailsMarshaller();

    public static CategoryDetailsMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CategoryDetails categoryDetails, ProtocolMarshaller protocolMarshaller) {

        if (categoryDetails == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(categoryDetails.getPointsOfInterest(), POINTSOFINTEREST_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package org.wso2.carbon.governance.wsdltool.ui.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.governance.wsdltool.stub.beans.xsd.ServiceInfoBean;
import org.wso2.carbon.governance.wsdltool.ui.clients.WSDLToolServiceClient;
import org.wso2.carbon.registry.common.ui.UIException;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class AddWSDLToolUtil {

    private static final Log log = LogFactory.getLog(AddWSDLToolUtil.class);

    public static void addMEXBean(
            HttpServletRequest request, ServletConfig config, HttpSession session) throws UIException {

        try {
            String parentPath = request.getParameter("parentPath");
            String wsdlURL = request.getParameter("wsdlURL");
            String ownerName = request.getParameter("ownerName");
            String ownerEmail = request.getParameter("ownerEmail");
            String ownerTelephone = request.getParameter("ownerTelephone");
            String ownerAddress = request.getParameter("ownerAddress");
            String description = request.getParameter("description");

            ServiceInfoBean serviceInfoBean = new ServiceInfoBean();
            serviceInfoBean.setWsdlURL(wsdlURL);
            serviceInfoBean.setOwnerName(ownerName);
            serviceInfoBean.setOwnerEmail(ownerEmail);
            serviceInfoBean.setOwnerAddress(ownerAddress);
            serviceInfoBean.setOwnerTelephone(ownerTelephone);
            serviceInfoBean.setDescription(description);

            WSDLToolServiceClient serviceClient = new WSDLToolServiceClient(config, session);
            serviceClient.addMEXService(parentPath + "/dummy.wsdl", serviceInfoBean);

        } catch (Exception e) {
            String msg = "Failed to get service details. " + e.getMessage();
            log.error(msg, e);
            throw new UIException(msg, e);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.example;

import java.io.Serializable;

public class Foo implements Serializable {

    private static final long serialVersionUID = 1L;
    private final String message;
    private final int count;

    public Foo(final String message, final int count) {
        this.message = message;
        this.count = count;
    }

    @Override
    public String toString() {
        return String.format("Foo(%s, %s)", message, count);
    }
}


text:
select
    t.*,
    108 as creator_id, 'Foo' as creator_name
from todo t
where id = :key_value


text:
Home

Body

Baby

Tips

CHANGES IN THE BODY

As the baby grows, you will begin to show and may experience mood swings,
intense food cravings, fatigue, weight gain, morning sickness, tender breasts, and nausea.

During this week, many women have their first ultrasound done to make sure
that everything is alright with mother and baby and to get a first glimpse of their embryo.


text:
DATE=$(date +"%Y-%m-%d-%H-%M")
PG_BASEBACKUP=pg_basebackup
PSQL=psql
BZIP2=bzip2
MKDIR=mkdir

###########################
####### LOAD CONFIG #######
###########################
while [ $# -gt 0 ]; do
  case $1 in
    -c)
      CONFIG_FILE_PATH="$2"
      shift 2
      ;;
    *)
      ${ECHO} "Unknown Option \"$1\"" 1>&2
      exit 2
      ;;
  esac
done

if [ -z $CONFIG_FILE_PATH ] ; then
  SCRIPTPATH=$(cd ${0%/*} && pwd -P)
  CONFIG_FILE_PATH="${SCRIPTPATH}/pg_backup.config"
fi

if [ ! -r ${CONFIG_FILE_PATH} ] ; then
  echo "Could not load config file from ${CONFIG_FILE_PATH}" 1>&2
  exit 1
fi

source "${CONFIG_FILE_PATH}"

DUMPLOG="$BACKUP_DIR/pg_basebackup-${DATE}.log"
DUMPDIR="$BACKUP_DIR/pg_basebackup-${DATE}"

###########################
#### PRE-BACKUP CHECKS ####
###########################

# Make sure we're running as the required backup user
if [ "$BACKUP_USER" != "" -a "$(id -un)" != "$BACKUP_USER" ] ; then
  echo "This script must be run as $BACKUP_USER. Exiting." 1>&2
  exit 1
fi

# Check if we can connect to postgres
$PSQL --tuples-only --quiet -h $HOSTNAME -U $USERNAME -p $PORT -c ''
RETVAL=$?

if [ $RETVAL != 0 ]; then
  echo "PostgreSQL DB not running"
  exit $RETVAL
else
  echo "PostgreSQL DB is running"
fi

# Check that the BACKUP_DIR directory Exists
if [ ! -d $BACKUP_DIR ]; then
  echo "No Dump Directory: ${BACKUP_DIR}"
  exit 1
fi

# Check that the DATADIR directory Exists
if [ ! -d $DATADIR ]; then
  echo "No Data Directory: ${DATADIR}"
  exit 1
fi

###########################
#### START THE BACKUPS ####
###########################

# Start Physical DB backup
echo "Start ${DATE}" > $DUMPLOG

cd $DATADIR
if [ $? != 0 ]; then
  echo "Could not cd to $DATADIR"
  exit $RETVAL
fi

$MKDIR $DUMPDIR
if [ $? != 0 ]; then
  echo "Could not create directory $DATADIR"
  exit $RETVAL
fi

unset RETVAL
$PG_BASEBACKUP -D $DUMPDIR -h $HOSTNAME -p $PORT -U $USERNAME -Fp -X stream
RETVAL=$?

if [ $RETVAL != 0 ]; then
  echo "${DATE}: Backup failed"
  exit $RETVAL
else
  echo "${DATE}: Backup successful"
fi


text:
#include "sol-flow/am2315.h"
#include "sol-flow-internal.h"

#include <sol-util-internal.h>
#include <errno.h>

#include "am2315.h"

#define ZERO_K 273.15

struct am2315_data {
    struct am2315 *device;
    struct sol_flow_node *node;
};

// Humidity Sensor node

static struct sol_drange humidity_out = {
    .min = 0.0,
    .max = 100.0,
    .step = 0.1
};

static void
_send_humidity_error_packet(struct am2315_data *mdata)
{
    const char errmsg[] = "Could not read AM2315 humidity samples";

    SOL_WRN(errmsg);
    sol_flow_send_error_packet(mdata->node, EIO, errmsg);
}

static void
_humidity_reading_callback(float humidity, bool success, void *data)
{
    struct am2315_data *mdata = data;

    if (!success)
        _send_humidity_error_packet(mdata);

    humidity_out.val = humidity;

    sol_flow_send_drange_packet(mdata->node,
        SOL_FLOW_NODE_TYPE_AM2315_HUMIDITY__OUT__OUT, &humidity_out);
}

static int
humidity_am2315_open(struct sol_flow_node *node, void *data, const struct sol_flow_node_options *options)
{
    struct am2315_data *mdata = data;
    const struct sol_flow_node_type_am2315_humidity_options *opts;

    SOL_FLOW_NODE_OPTIONS_SUB_API_CHECK(options, SOL_FLOW_NODE_TYPE_AM2315_HUMIDITY_OPTIONS_API_VERSION,
        -EINVAL);
    opts = (const struct sol_flow_node_type_am2315_humidity_options *)options;

    mdata->device = am2315_open(opts->i2c_bus, opts->i2c_slave);
    if (!mdata->device) {
        return -EINVAL;
    }

    am2315_humidity_callback_set(mdata->device, _humidity_reading_callback,
        mdata);

    mdata->node = node;

    return 0;
}

static void
humidity_am2315_close(struct sol_flow_node *node, void *data)
{
    struct am2315_data *mdata = data;

    if (mdata->device)
        am2315_close(mdata->device);
}

static int
humidity_am2315_tick(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct am2315_data *mdata = data;

    am2315_read_humidity(mdata->device);

    return 0;
}

// Temperature sensor node

static struct sol_drange temperature_out = {
    .min = -40.0 + ZERO_K,
    .max = 140.0 + ZERO_K,
    .step = 0.1
};

static void
_send_temperature_error_packet(struct am2315_data *mdata)
{
    const char errmsg[] = "Could not read AM2315 temperature samples";

    SOL_WRN(errmsg);
    sol_flow_send_error_packet(mdata->node, EIO, errmsg);
}

static void
_temperature_reading_callback(float temperature, bool success, void *data)
{
    struct am2315_data *mdata = data;

    if (!success)
        _send_temperature_error_packet(mdata);

    temperature_out.val = temperature - ZERO_K;

    sol_flow_send_drange_packet(mdata->node,
        SOL_FLOW_NODE_TYPE_AM2315_TEMPERATURE__OUT__KELVIN, &temperature_out);
}

static int
temperature_am2315_open(struct sol_flow_node *node, void *data, const struct sol_flow_node_options *options)
{
    struct am2315_data *mdata = data;
    const struct sol_flow_node_type_am2315_temperature_options *opts;

    SOL_FLOW_NODE_OPTIONS_SUB_API_CHECK(options, SOL_FLOW_NODE_TYPE_AM2315_TEMPERATURE_OPTIONS_API_VERSION,
        -EINVAL);
    opts = (const struct sol_flow_node_type_am2315_temperature_options *)options;

    mdata->device = am2315_open(opts->i2c_bus, opts->i2c_slave);
    if (!mdata->device) {
        return -EINVAL;
    }

    am2315_temperature_callback_set(mdata->device, _temperature_reading_callback,
        mdata);

    mdata->node = node;

    return 0;
}

static void
temperature_am2315_close(struct sol_flow_node *node, void *data)
{
    struct am2315_data *mdata = data;

    if (mdata->device)
        am2315_close(mdata->device);
}

static int
temperature_am2315_tick(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct am2315_data *mdata = data;

    am2315_read_temperature(mdata->device);

    return 0;
}

#include "am2315-gen.c"


text:
module Stupidedi
  using Refinements

  module TransactionSets
    #
    # {Builder} is a simple DSL for construction a transaction set
    #
    module Builder

      autoload :Dsl, "stupidedi/transaction_sets/builder/dsl"

    end

    class << Builder
      # @return [Schema::TransactionSetDef]
      def build(functional_group, id, name, *table_defs)
        Schema::TransactionSetDef.build(functional_group, id, name, *table_defs)
      end

      # @group Element Constraints
      #######################################################################

      # @param [String, ...] values
      def Values(*values)
        [:Values, values]
      end

      # @param [Integer] n
      def MaxLength(n)
        [:MaxLength, n]
      end

      # @param [Integer] n
      def MaxPrecision(n)
        [:MaxPrecision, n]
      end

      # @endgroup
      #######################################################################

      # @group Definition Constructors
      #######################################################################

      # @param [Schema::ElementReq] requirement
      # @param [String] name
      def Element(requirement, name, *constraints)
        [:Element, requirement, name, constraints]
      end

      # @return [SegmentUse]
      def Segment(position, segment_def, name, requirement, repeat_count, *elements)
        unless elements.length == segment_def.element_uses.length
          raise Exceptions::InvalidSchemaError,
            "segment #{segment_def.id} has #{segment_def.element_uses.length}" +
            " elements but #{elements.length} arguments were given"
        end

        element_idx   = "00"
        element_uses  = elements.zip(segment_def.element_uses).map do |e, u|
          e_tag, e_requirement, e_name, e_arguments = e
          element_idx = element_idx.succ
          descriptor  = "#{segment_def.id}#{element_idx}"

          unless e_tag == :Element
            raise Exceptions::InvalidSchemaError,
              "given argument for #{descriptor} must be Element(...)"
          end

          if u.composite?
            e_repeat_count, e_arguments = e_arguments.partition{|x| x.is_a?(Schema::RepeatCount) }

            changes = Hash.new
            changes[:requirement] = e_requirement

            if e_repeat_count.length == 1
              changes[:repeat_count] = e_repeat_count.head
            elsif e_repeat_count.length > 1
              raise Exceptions::InvalidSchemaError,
                "more than one RepeatCount was specified for #{descriptor}"
            end

            unless e_requirement.forbidden?
              unless e_arguments.length == u.definition.component_uses.length
                raise Exceptions::InvalidSchemaError,
                  "composite element #{u.definition.id} at #{descriptor} has
                  #{u.definition.component_uses.length} component elements but
                  #{e_arguments.length} arguments were given".join
              end

              # ComponentElementUses
              component_idx   = "00"
              component_uses  = e_arguments.zip(u.definition.component_uses).map do |e1, c|
                c_tag, c_requirement, c_name, c_arguments = e1
                component_idx = component_idx.succ
                descriptor    = "#{descriptor}-#{component_idx}"

                unless c_tag == :Element
                  raise Exceptions::InvalidSchemaError,
                    "given argument for #{descriptor} must be Element(...)"
                end

                mod_element(c, descriptor, c_requirement, c_name, c_arguments)
              end

              changes[:definition] = u.definition.copy(:name           => e_name,
                                                       :component_uses => component_uses)
            else
              changes[:definition] = u.definition.copy(:name => e_name)
            end

            u.copy(changes)
          else
            mod_element(u, descriptor, e_requirement, e_name, e_arguments)
          end
        end

        segment_def.
          copy(:name => name, :element_uses => element_uses).
          use(position, requirement, repeat_count)
      end

      # @endgroup
      #######################################################################

     private

      # @return [Schema::SimpleElementUse]
      def mod_element(element_use, descriptor, requirement, name, arguments)
        unless requirement.is_a?(Schema::ElementReq)
          raise Exceptions::InvalidSchemaError,
            "first argument to Element must be a Schema::ElementReq but got #{requirement.inspect} for #{descriptor}"
        end

        unless name.is_a?(String)
          raise Exceptions::InvalidSchemaError,
            "second argument to Element must be a String for #{descriptor}"
        end

        changes = Hash.new # changes to SegmentUse
        dhanges = Hash.new # changes to SegmentDef

        changes[:requirement] = requirement
        changes[:definition]  = element_use.definition.copy(:name => name)

        repeat_count = arguments.select{|x| x.is_a?(Schema::RepeatCount) }

        if repeat_count.length == 1
          changes[:repeat_count] = repeat_count.head
        elsif repeat_count.length > 1
          raise Exceptions::InvalidSchemaError,
            "more than one RepeatCount specified for #{descriptor}"
        end

        allowed_values = arguments.select{|x| x.is_a?(Array) and x.head == :Values }

        if allowed_values.length == 1
          begin
            changes[:allowed_values] = element_use.allowed_values.replace(allowed_values.head.last)
          rescue ArgumentError => e
            raise Exceptions::InvalidSchemaError,
              "#{e.message} for #{descriptor}"
          end
        elsif allowed_values.length > 1
          raise Exceptions::InvalidSchemaError,
            "more than one Values specified for #{descriptor}"
        end

        max_length = arguments.select{|x| x.is_a?(Array) and x.head == :MaxLength }

        if max_length.length == 1
          dhanges[:max_length] = max_length.head.last
        elsif max_length.length > 1
          raise Exceptions::InvalidSchemaError,
            "more than one MaxLength specified for #{descriptor}"
        end

        if dhanges.empty?
          element_use.copy(changes)
        else
          element_use.copy(changes.merge(:definition =>
            element_use.definition.copy(dhanges)))
        end
      end
    end
  end
end


text:
layout: post
title: "Broyden's Method Derivation"
excerpt: "Numerical methods"
categories: articles
tags: [numerical methods]
comments: true
share: true
---

# Broyden's Method

## Newton's method
We know that in numerical methods, newton's method is very handy to use, and also fast to converge. Newton's method can be stated
as the following:

$$ x_{n+1} = x_n - f'(x_n)^{-1} * f(x_n) $$

However, the inverse of $$ f(x_n) $$ can be hard to calculate, such operation will take $$O(n^3)$$ time complexity. Therefore,
Broyden's method is introduced, to approxiate the inverse of the Jacobian matrix.

## "Good" Broyden

Let's say we want to approximate the inverse of Jacobian matrix, we can first use rank-1 update to approximate the Jacobian matrix,
after that we can apply Sherman-Morrison to approximate the inverse of Jacobian. Broyden mentioned in his study that smaller rank matrix
should be used to update the Jacobian matrix, but here I am not sure why the smaller rank is needed.

### Rank 1 update
$$J_{k+1} = J_k  + uv^T$$

### Secant condition
Secnat condition actually comes from the finite difference estimation of derivative in 1-dimesnion.
$$J_{k+1}(x_{k+1} - x_k) = f(x_{k+1}) - f(x_k)$$
Let $$ x_{k+1} - x_k = d$$ and $$f(x_{k+1}) - f(x_k) = g$$

Combining the equations above, we should have $$u = \frac{g - J_k d}{v^T d}$$

Therefore, the material we need to start the update is only $$v$$. To find $$v$$, we can solve a optimization problem as follows:
$$argmin ||uv^T||_F = ||\frac{hv^T}{v^Td}||_F$$, where $$h = g - Jd$$

$$||\frac{hv^T}{v^Td}||_F = \sum_i\sum_j(\frac{h_iv_j}{\sum_k v_k d_k})^2$$

After taking derivatives of $$v_j$$, we should have:

$$2 \sum_i \frac{h_iv_j}{\sum_k v_k d_k} \frac{h_i\sum_k v_k d_k - h_i v_j d_j}{(\sum_k v_k d_k)^2} + \sum_i \sum_{l \neq j} 2 \frac{-h_i^2 v_l^2 d_j}{(\sum_k v_k d_k)^2}$$, to make it simpler, we have
$$2 (\frac{\sum h_i^2}{(\sum_k v_k d_k})^2) (v_j - \frac{\sum_k v_k^2 d_j}{\sum_k v_k d_k}) = 0$$

The equations satisfies when $$v = \alpha d$$, we can just let $$\alpha = 1$$, therefore, we can get the updating rules as follows:

$$J_{k+1} = J_k + \frac{\Delta f_{k+1} - J_k \Delta x_{k+1}}{||\Delta x_{k+1}||^2} \Delta x_{k+1} ^ T$$
Apply sherman-morrison on the it, we can get the update rule for inverse matrix of the Jacobian.

## "Bad" Broyden

"Bad" Broyden's idea is similar, given an slightly different secant condition,

$$B_{k+1}g = d$$, where $$B$$ is an approximation to the inverse of Jacobian, then by the same logic as good broyden, write update rule as $$B_{k+1} = B_k + pq^T$$, and solve the optimization problem:

$$|p q^T|_F$$

we would have $$q = \alpha g$$, which results in the final updating rule:
$$B_{k+1} = B_k + \frac{\Delta x_{k+1} - B_k \Delta f(x_{k+1})}{||\Delta f(x_{k+1})||^2} \Delta f(x_{k+1})^T$$


text:
With Simple Google Custom Search, help people search what they need in your website just like in official google site.

## Installation

Add this line to your application's Gemfile:

    gem 'simple_google_custom_search'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install simple_google_custom_search

## Configuration

You need to define a <tt>constant variable</tt> for the API to search the matching words to your domain:

    SGCS_CONFIG = {
        domain: 'YOUR_SITE_URL'
    }

## Usage

To perform a search:

    results = SimpleGoogleCustomSearch.search("simple", offset +optional+)

The +results+ variable is now a SimpleGoogleCustomSearch::ResultSet object:

    results.total            # number of results (integer)
    results.item             # array of result objects (SimpleGoogleCustomSearch::Result)

Iterate through the results:

    results.item.each do |result|
        result.title           # result title
        result.link            # result URL
        result.description     # excerpt, with terms highlighted
    end

## TODO

1. Unit Test
2. Add Pagination

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
class Flag < ActiveRecord::Base
  belongs_to :challenge, inverse_of: :flags

  has_many :solved_challenges

  validates :flag, presence: true
end


text:
package registry

import (
	"math/rand"
	"testing"

	. "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
)

func expectSchedule(scheduler Scheduler, pod Pod, expected string, t *testing.T) {
	actual, err := scheduler.Schedule(pod)
	expectNoError(t, err)
	if actual != expected {
		t.Errorf("Unexpected scheduling value: %d, expected %d", actual, expected)
	}
}

func TestRoundRobinScheduler(t *testing.T) {
	scheduler := MakeRoundRobinScheduler([]string{"m1", "m2", "m3", "m4"})
	expectSchedule(scheduler, Pod{}, "m1", t)
	expectSchedule(scheduler, Pod{}, "m2", t)
	expectSchedule(scheduler, Pod{}, "m3", t)
	expectSchedule(scheduler, Pod{}, "m4", t)
}

func TestRandomScheduler(t *testing.T) {
	random := rand.New(rand.NewSource(0))
	scheduler := MakeRandomScheduler([]string{"m1", "m2", "m3", "m4"}, *random)
	_, err := scheduler.Schedule(Pod{})
	expectNoError(t, err)
}

func TestFirstFitSchedulerNothingScheduled(t *testing.T) {
	mockRegistry := MockPodRegistry{}
	scheduler := MakeFirstFitScheduler([]string{"m1", "m2", "m3"}, &mockRegistry)
	expectSchedule(scheduler, Pod{}, "m1", t)
}

func makePod(host string, hostPorts ...int) Pod {
	networkPorts := []Port{}
	for _, port := range hostPorts {
		networkPorts = append(networkPorts, Port{HostPort: port})
	}
	return Pod{
		CurrentState: PodState{
			Host: host,
		},
		DesiredState: PodState{
			Manifest: ContainerManifest{
				Containers: []Container{
					Container{
						Ports: networkPorts,
					},
				},
			},
		},
	}
}

func TestFirstFitSchedulerFirstScheduled(t *testing.T) {
	mockRegistry := MockPodRegistry{
		pods: []Pod{
			makePod("m1", 8080),
		},
	}
	scheduler := MakeFirstFitScheduler([]string{"m1", "m2", "m3"}, &mockRegistry)
	expectSchedule(scheduler, makePod("", 8080), "m2", t)
}

func TestFirstFitSchedulerFirstScheduledComplicated(t *testing.T) {
	mockRegistry := MockPodRegistry{
		pods: []Pod{
			makePod("m1", 80, 8080),
			makePod("m2", 8081, 8082, 8083),
			makePod("m3", 80, 443, 8085),
		},
	}
	scheduler := MakeFirstFitScheduler([]string{"m1", "m2", "m3"}, &mockRegistry)
	expectSchedule(scheduler, makePod("", 8080, 8081), "m3", t)
}

func TestFirstFitSchedulerFirstScheduledImpossible(t *testing.T) {
	mockRegistry := MockPodRegistry{
		pods: []Pod{
			makePod("m1", 8080),
			makePod("m2", 8081),
			makePod("m3", 8080),
		},
	}
	scheduler := MakeFirstFitScheduler([]string{"m1", "m2", "m3"}, &mockRegistry)
	_, err := scheduler.Schedule(makePod("", 8080, 8081))
	if err == nil {
		t.Error("Unexpected non-error.")
	}
}


text:
/*
* Author   Jonathan Lurie - http://me.jonathanlurie.fr
* License  MIT
* Link      https://github.com/Pixpipe/pixpipejs
* Lab       MCIN - Montreal Neurological Institute
*/

import { Image2D } from '../core/Image2D.js';
import { Filter } from '../core/Filter.js';

/**
* CanvasImageWriter is a filter to output an instance of Image into a
* HTML5 canvas element.
* The metadata "parentDivID" has to be set using `setMetadata("parentDivID", "whatever")`
* The metadata "alpha", if true, enable transparency. Default: false.
* If the input Image2D has values not in [0, 255], you can remap/stretch using
* setMetadata("min", xxx ) default: 0
* setMetadata("max", xxx ) default: 255
* We can also use `setMetadata("reset", false)` so that we can add another canvas
* with a new image at update.
*
* **Usage**
* - [examples/imageToCanvasFilter.html](../examples/imageToCanvasFilter.html)
*
* @example
// create an image
* var myImage = new pixpipe.Image2D({width: 100, height: 250, color: [255, 128, 64, 255]})
*
* // create a filter to write the image into a canvas
* var imageToCanvasFilter = new pixpipe.CanvasImageWriter( "myDiv" );
* imageToCanvasFilter.addInput( myImage );
* imageToCanvasFilter.update();
*/
class CanvasImageWriter extends Filter{

  /**
  * @param {String} parentDivID - dom id of the future canvas' parent.
  * (most likely the ID of a div)
  */
  constructor(){
    // call Filter constructor
    super();

    this.addInputValidator(0, Image2D);

    this.setMetadata("alpha", false);
    this.setMetadata("min", 0);
    this.setMetadata("max", 255);
    this.setMetadata("reset", true);

    // so that we can flush the content
    this._canvas = null;
    this._ctx = null;
  }

  /**
  * Get the canvas used to print the Image2D;
  * @return {Object} canvas
  */
  getCanvas(){
    return this._canvas;
  }

  /**
  * @private
  * Initialize a new canvas object
  */
  _init(){

    var parentElem = document.getElementById( this.getMetadata("parentDivID") );

    if(! parentElem ){
      return false;
    }

    // reset content
    if(this.getMetadata("reset")){
      while (parentElem.firstChild) {
          parentElem.removeChild(parentElem.firstChild);
      }
    }

    // creating a canvas element
    this._canvas = document.createElement("canvas");
    this._canvas.style = "image-rendering: pixelated;";
    this._ctx = this._canvas.getContext('2d');

    // not sure this is useful since the style is "pixelated"
    // (does not seem to well super well with Firefox)
    this._ctx.imageSmoothingEnabled = false;
    this._ctx.mozImageSmoothingEnabled = false;
    this._ctx.webkitImageSmoothingEnabled = false;
    this._ctx.ctxmsImageSmoothingEnabled = false;

    document.getElementById(this.getMetadata("parentDivID")).appendChild(this._canvas);

    return true;
  }

  /**
  * Overwrite the generic (empty) method.
  */
  _run(){
    var that = this;

    // abort if invalid input
    if(!this.hasValidInput() )
      return;

    var image = this._input[0];
    var ncppSrc = image.getComponentsPerPixel();

    // only Image2d with 1 or 4 bands can be displayed
    if( ncppSrc != 1 && ncppSrc != 3 && ncppSrc != 4){
      console.warn("Cannot write Image in canvas if contains other than 1, 3 or 4 bands.");
      return;
    }

    if(!this.getMetadata("parentDivID")){
      console.error("The parent DIV ID to place the canvas element was not specified. Unable to display anything.");
      return;
    }

    // build a new canvas
    if( !this._init() ){
      console.warn("The parent div was not specified or does not exist.");
      return;
    }
    var useAlphaBand = this.getMetadata("alpha");

    // resizing the canvas
    this._canvas.width = image.getWidth();
    this._canvas.height = image.getHeight();

    var canvasImageData = this._ctx.getImageData(0, 0, this._canvas.width, this._canvas.height);
    var canvasImageDataArray = canvasImageData.data;

    // getting Image object data
    var originalImageDataArray = image.getData();

    // input image is RGBA
    if(ncppSrc == 4){
      for(var i=0; i<originalImageDataArray.length; i++){
        if(!useAlphaBand && i%4 == 3){
          canvasImageDataArray[i] = 255;
        }else{
          canvasImageDataArray[i] = this._stretchMinMax( originalImageDataArray[ i ] );
        }
      }

    // input image is mono chanel
    }else if(ncppSrc == 1){

      for(var i=0; i<originalImageDataArray.length; i++){
        var index1D = i*4;
        var stretchedValue = this._stretchMinMax(originalImageDataArray[i]);
        canvasImageDataArray[index1D] = stretchedValue;
        canvasImageDataArray[index1D + 1] = stretchedValue;
        canvasImageDataArray[index1D + 2] = stretchedValue;
        canvasImageDataArray[index1D + 3] = 255;
      }

    // input image is RGB
    }else if(ncppSrc == 3){
      var counter = 0;

      for(var i=0; i<canvasImageDataArray.length; i++){
        if(i%4 == 3){
          canvasImageDataArray[i] = 255;
        }else{
          canvasImageDataArray[i] = this._stretchMinMax(originalImageDataArray[ counter ]);
          counter ++;
        }
      }
    }

    this._ctx.putImageData(canvasImageData, 0, 0);
  }

  /**
  * @private
  * remap the intensity between getMetadata("min") and getMetadata("max")
  * @param {Number} intensity - input pixel value
  * @return {Number} the adjusted number
  */
  _stretchMinMax( intensity ){
    var min = this._metadata.min;
    var max = this._metadata.max;

    if(min == 0 && max == 255){
      return intensity;
    }

    return ( (intensity - min) / (max - min) ) * 255;
  }

}

export { CanvasImageWriter }


text:
from django.db import models

# Create your models here.

class HelpCenter(models.Model):
	HelpCenterName = models.CharField(max_length=64)
	HelpCenterContent = models.TextField(blank=True)
	def __unicode__(self):
		return '%s %s' %(self.id, self.HelpCenterName)

class Seller(models.Model):
	SellerTypeChoices=(
		('l','limited user'),
		('n','normal user'),
	)
	SellerAccount = models.CharField(max_length=64)
	SellerPassword = models.CharField(max_length=32)
	SellerName = models.CharField(max_length=64)
	SellerType = models.CharField(max_length=1,choices=SellerTypeChoices,blank=True)
	SellerRealName = models.CharField(max_length=64,null=True)
	SellerRealID = models.IntegerField(null=True)
	SellerTelephone = models.CharField(max_length=64,blank=True)
	SellerEmail = models.EmailField(blank=True)
	SellerAddress = models.CharField(max_length=64,blank=True)
	def __unicode__(self):
		return '%s %s %s' %(self.id, self.SellerAccount, self.SellerName)

class Shop(models.Model):
	States=(
		(0, 'checking'),
		(1, 'open'),
		(2, 'close')
	)
	ShopDescription = models.TextField(blank=True)
	SellerID = models.ForeignKey(Seller)
	ShopName = models.CharField(max_length=64,blank=True)
	#店铺状态:0-待审核,1-营业,2-歇业
	ShopState = models.IntegerField(choices=States)
	BigImage = models.ImageField(upload_to='images',max_length=255,blank=True,null=True)
	ShopImage = models.ImageField(upload_to='images',max_length=255,blank=True,null=True)
	IsAdv = models.BooleanField()
	IsHomeAdv = models.BooleanField()
	def __unicode__(self):
		return '%s %s' %(self.id, self.ShopName)

class Commodity(models.Model):
	CommodityTypeChoices=(
		('C','Clothing'),
		('A','Accesory'),
		('S','Sport'),
		('J','Jewelry'),
		('D','Digit'),
		('H','Household appliances'),
		('M','Makeup'),
		('F','Food'),
		('E','Entertainment'),
		('O','Others')
	)
	CommodityName = models.CharField(max_length=64)
	CommodityDescription = models.TextField(blank=True)
	CommodityAmount = models.IntegerField(blank=True,null=True)
	SoldAmount = models.IntegerField(blank=True)
	PurchasePrice = models.FloatField(blank=True)
	SellPrice = models.FloatField(blank=True)
	CommodityType = models.CharField(max_length=1,choices=CommodityTypeChoices,blank=True)
	CommodityImage = models.ImageField(upload_to='images',max_length=255,blank=True,null=True)
	CommodityDiscount = models.FloatField(null=True,blank=True)
	ShopID = models.ForeignKey(Shop)
	IsAdv = models.BooleanField()
	IsHomeAdv = models.BooleanField()
	def __unicode__(self):
		return '%s %s %s %s' %(self.id, self.CommodityName, self.CommodityType, self.CommodityAmount)

class Administrator(models.Model):
	AdministratorAccount = models.CharField(max_length=64)
	AdministratorName = models.CharField(max_length=64)
	AdministratorPassword = models.CharField(max_length=16)
	AdministratorTelephone = models.CharField(max_length=64,blank=True)
	AdministratorEmail = models.EmailField()
	def __unicode__(self):
		return '%s %s' %(self.id, self.AdministratorName)

class ShopAdv(models.Model):
	ShopID = models.ForeignKey(Shop)
	OwnerID = models.ForeignKey(Seller)
	AdvertisementContent = models.TextField()
	def __unicode__(self):
		return '%s %s' %(self.id, self.AdvertisementContent)

class CommodityAdv(models.Model):
	CommodityID = models.ForeignKey(Commodity)
	OwnerID = models.ForeignKey(Seller)
	AdvertisementContent = models.TextField()
	def __unicode__(self):
		return '%s %s' %(self.id, self.AdvertisementContent)

class HomeShopAdv(models.Model):
	ShopID = models.ForeignKey(Shop)
	OwnerID = models.ForeignKey(Administrator)
	AdvertisementContent = models.TextField()
	ApplyState = models.BooleanField()
	def __unicode__(self):
		return '%s %s' %(self.id, self.AdvertisementContent)

class HomeCommodityAdv(models.Model):
	CommodityID = models.ForeignKey(Commodity)
	OwnerID = models.ForeignKey(Administrator)
	AdvertisementContent = models.TextField()
	ApplyState = models.BooleanField()
	def __unicode__(self):
		return '%s %s' %(self.id, self.AdvertisementContent)

class System(models.Model):
	BulletinBoardContent = models.CharField(max_length=64,blank=True)
	BulletinBoardDescription = models.TextField(blank=True)
	BulletinBoardDate = models.DateField(blank=True)
	ComissionRate = models.FloatField(blank=True)
	def __unicode__(self):
		return '%s %s %s' %(self.id, self.BulletinBoardDate,self.BulletinBoardContent)

class BlacklistSeller(models.Model):
	BlacklistSellerReason = models.TextField()
	SellerID = models.ForeignKey(Seller)
	AdministratorID = models.ForeignKey(Administrator)
	def __unicode__(self):
		return '%s %s' %(self.id, self.BlacklistSellerReason)

class Discount(models.Model):
	DiscountRate = models.FloatField(blank=True)
	SellerID = models.ForeignKey(Seller)
	ShopID = models.ForeignKey(Shop)
	def __unicode__(self):
		return '%s %s' %(self.id, self.DiscountRate)

class ShopOrder(models.Model):
	StateChoices=(
		(0, 'paying'),
		(1, 'shipping'),
		(2, 'signing'),
		(3, 'commenting'),
		(4, 'refunding'),
		(5, 'refunded'),
		(6, 'refund refuded'),
		(7, 'finish'),
		(8, 'commented')
	)
	ShopOrderState = models.IntegerField(choices=StateChoices)
	ShopOrderDate = models.DateField()
	ShopID = models.ForeignKey(Shop)
	def __unicode__(self):
		return '%s %s %s' %(self.id, self.ShopOrderDate, self.ShopOrderState)

class Customer(models.Model):
	CustomerTypeChoices=(
		('l','limited user'),
		('n','normal user'),
	)
	CustomerAccount = models.CharField(max_length=64)
	CustomerName = models.CharField(max_length=64)
	CustomerPassword = models.CharField(max_length=32)
	CustomerType = models.CharField(max_length=1,choices=CustomerTypeChoices,blank=True)
	CustomerTelephone = models.CharField(max_length=64,blank=True)
	CustomerEmail = models.EmailField()
	CustomerAddress = models.TextField(blank=True)
	def __unicode__(self):
		return u'%s %s %s' %(self.id, self.CustomerAccount, self.CustomerName)

class CustomerOrder(models.Model):
	StateChoices=(
		(0, 'paying'),
		(1, 'shipping'),
		(2, 'signing'),
		(3, 'commenting'),
		(4, 'refunding'),
		(5, 'refunded'),
		(6, 'refund refuded'),
		(7, 'finish'),
		(8, 'commented')
	)
	CustomerOrderState = models.IntegerField(choices=StateChoices)
	CustomerOrderDate = models.DateField()
	CustomerID = models.ForeignKey(Customer)
	def __unicode__(self):
		return '%s %s %s' %(self.id, self.CustomerOrderState, self.CustomerOrderDate)

class OrderList(models.Model):
	#OrderListAccount = models.CharField(max_length=64)
	#订单状态:0-待付款,1-已付款待发货,2-待签收,
	# 3-待评价,4-待退款,5-退款成功,6-卖家拒绝退款
	# 7-交易完成
	StateChoices=(
		(0, 'paying'),
		(1, 'shipping'),
		(2, 'signing'),
		(3, 'commenting'),
		(4, 'refunding'),
		(5, 'refunded'),
		(6, 'refused refunded'),
		(7, 'finish'),
		(8, 'commented')
	)
	OrderListState = models.IntegerField(choices=StateChoices)
	OrderListDate = models.DateField()
	OrderAmount = models.IntegerField(blank=True, null=True)
	ShipNo = models.CharField(max_length = 64)
	#SellerID = models.ForeignKey(Seller)
	ShopOrderID = models.ForeignKey(ShopOrder)
	CustomerOrderID = models.ForeignKey(CustomerOrder)
	CommodityID = models.ForeignKey(Commodity)
	def __unicode__(self):
		return '%s %s %s' %(self.id, self.OrderListDate, self.OrderListState)

class Comment(models.Model):
	CommentContent = models.TextField(blank=True)
	CustomerID = models.ForeignKey(Customer)
	CommodityID = models.ForeignKey(Commodity)
	def __unicode__(self):
		return '%s %s' %(seld.id, self.CommentContent)

class Cart(models.Model):
	CartDate = models.DateField()
	CustomerID = models.ForeignKey(Customer)
	CommodityID = models.ForeignKey(Commodity)
	CartCommodityAmount = models.IntegerField(blank=True, default=1)
	def __unicode__(self):
		return '%s %s %s' %(self.id, self.CartCommodityAmount, self.CartDate)

class Favorite(models.Model):
	FavoriteDate = models.DateField()
	CustomerID = models.ForeignKey(Customer)
	CommodityID = models.ForeignKey(Commodity)
	def __unicode__(self):
		return '%s %s' %(self.id, self.FavoriteDate)

class BlacklistCustomer(models.Model):
	BlacklistCustomerReason = models.TextField()
	AdministratorID = models.ForeignKey(Administrator)
	CustomerID = models.ForeignKey(Customer)
	def __unicode__(self):
		return '%s %s' %(self.id, self.BlacklistCustomerReason)

class Income(models.Model):
	IncomeAmount = models.FloatField()
	def __unicode__(self):
		return '%s %s' %(self.id, self.IncomeAmount)


text:
@interface VCRRequestKey : NSObject <NSCopying>

+ (VCRRequestKey *)keyForObject:(id)object;
+ (VCRRequestKey *)keyForObject:(id)object
                    compareBody:(BOOL)compareBody;

- (id)JSON;

@property (nonatomic, strong, readonly) NSString *URI;
@property (nonatomic, strong, readonly) NSString *method;
@property (nonatomic, strong, readonly) NSData *requestBody;
@property (nonatomic, assign) BOOL compareBody;

@end


text:
"""
=================
Lorentzian Fitter
=================

The simplest and most useful model.

Until 12/23/2011, lorentzian fitting used the complicated and somewhat bloated
gaussfitter.py code.  Now, this is a great example of how to make your own
model!

"""
import model
import numpy

def lorentzian(x,A,dx,w, return_components=False):
    """
    Returns a 1-dimensional lorentzian of form
    A*2*pi*w/((x-dx)**2 + ((w/2)**2))

    [amplitude,center,width]

    return_components does nothing but is required by all fitters

    """
    x = numpy.array(x) # make sure xarr is no longer a spectroscopic axis
    return A/(2.0*numpy.pi)*w/((x-dx)**2 + (w/2.0)**2)

def lorentzian_fitter(multisingle='multi'):
    """
    Generator for lorentzian fitter class
    """

    myclass =  model.SpectralModel(lorentzian, 3,
            parnames=['amplitude','shift','width'],
            parlimited=[(False,False),(False,False),(True,False)],
            parlimits=[(0,0), (0,0), (0,0)],
            shortvarnames=('A',r'\Delta x',r'\sigma'),
            multisingle=multisingle,
            )
    myclass.__name__ = "lorentzian"

    return myclass


text:
from enum import Enum, auto
import time
import subprocess
import os
import sys
from shutil import rmtree
from datetime import datetime
from dataclasses import dataclass, asdict

class Color(Enum):
  HEADER = '\033[95m'
  BLUE = '\033[94m'
  GREEN = '\033[92m'
  ORANGE = '\033[93m'
  RED = '\033[91m'
  BOLD = '\033[1m'
  UNDERLINE = '\033[4m'

def color_text(text: str, color: Color = Color.BOLD, space_before: bool = True) -> str:
  return '{space}{color}{text}{end}'.format(space='\n' if space_before else '', color=color.value, text=text, end='\033[0m')

def abort() -> None:
  print(color_text('Deployment canceled.', Color.RED))
  sys.exit(0)

def set_project_id() -> str:
  project_set = False
  while not project_set:
    prompt = input(color_text('Enter the GCP project ID you want to deploy to? '))
    subprocess.check_output(['gcloud', 'config', 'set', 'project', prompt])
    current_project_id = subprocess.check_output(['gcloud', 'config', 'list', '--format', 'value(core.project)']).decode('utf-8').replace('\n','')
    if current_project_id == prompt:
        project_set = True
  return current_project_id

def get_project_id() -> str:
  current_project_id = subprocess.check_output(['gcloud', 'config', 'list', '--format', 'value(core.project)']).decode('utf-8').replace('\n','')
  prompt = input(color_text('DQM will be deployed within GCP project "{}", is that OK? (Y/n) '.format(current_project_id)))
  project_id = current_project_id if prompt.lower() != 'n' else set_project_id()
  print(color_text('DQM will be deployed within GCP project "{}".'.format(project_id), Color.BLUE))
  return project_id

def check_source_dir() -> None:
  if os.path.isdir('./dqm'):
    prompt = input(color_text('Existing "dqm" dir in current path should be deleted, proceed? ([Y]es/[s]kip) '))
    # if prompt.lower() == 'n':
      # abort()
    if prompt.lower() != 's':
      rmtree('./dqm')

def clone_repo() -> None:
  if input(color_text('Next step -> Download sources ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['git', 'clone', 'https://github.com/google/dqm.git'])

def clone_repo() -> None:
  if input(color_text('Next step -> Download sources ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['git', 'clone', 'https://github.com/google/dqm.git'])

def install_frontend_deps() -> None:
  if input(color_text('Next step -> Install frontend dependencies ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['npm', 'install'], cwd='dqm/frontend')

def build_frontend() -> None:
  if input(color_text('Next step -> Build frontend (it can take a little while...) ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['npm', 'run', 'build'], cwd='dqm/frontend')

def install_pipenv() -> None:
  if input(color_text('Next step -> Install pipenv ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['pip3', 'install', '--user', 'pipenv'])

def install_backend_deps() -> None:
  if input(color_text('Next step -> Install backend dependencies ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['python3', '-m', 'pipenv', 'install', '--dev'], cwd='dqm/backend')

def enable_apis() -> None:
  if input(color_text('Next step -> Enable APIs ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['gcloud', 'services', 'enable', 'analytics.googleapis.com'])
    subprocess.check_output(['gcloud', 'services', 'enable', 'analyticsreporting.googleapis.com'])

def create_gae_app() -> None:
  if input(color_text('Next step -> Create App Engine application ([Y]es/[s]kip) ')).lower() != 's':
    try:
      subprocess.check_output(['gcloud', 'app', 'create'])
    except subprocess.CalledProcessError as e:
      print(color_text('Failed to create App Engine app (this is normal if you have an existing app).', Color.ORANGE))
      prompt = input(color_text('Continue anyway and deploy on existing app? (Y/n) '))
      if prompt.lower() == 'n':
        abort()

def create_sa_keys() -> None:
  if input(color_text('Next step -> Download service account key file ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['gcloud', 'iam', 'service-accounts', 'keys', 'create', './key.json', '--iam-account', f'{project_id}@appspot.gserviceaccount.com'], cwd='dqm/backend')

def setup_database() -> (str, str, str):
  if input(color_text('Next step -> Database setup ([Y]es/[s]kip) ')).lower() == 's':
    return None, None, None
  else:
    prompt = input(color_text('Do you want to reuse an existing SQL instance? (y/N) ', Color.BOLD))
    create_sql_instance = True if prompt.lower() != 'y' else False
    sql_instance_name = input(color_text('SQL instance name (dqm)? ', Color.BOLD)) or 'dqm'
    sql_instance_region = input(color_text('SQL instance region (europe-west1)? ', Color.BOLD)) or 'europe-west1'
    if create_sql_instance:
      print(color_text('Creating SQL instance (it can take a little while)...', Color.BLUE))
      subprocess.check_output(['gcloud', 'sql', 'instances', 'create', sql_instance_name, '--region={}'.format(sql_instance_region)])

    prompt = input(color_text('Do you want to reuse an existing MySQL database? (y/N) ', Color.BOLD))
    create_sql_db = True if prompt.lower() != 'y' else False
    sql_db_name = input(color_text('MySQL database name (dqm)? ', Color.BOLD)) or 'dqm'
    if create_sql_db:
      print(color_text('Creating MySQL database...', Color.BLUE))
      subprocess.check_output(['gcloud', 'sql', 'databases', 'create', sql_db_name, '--instance={}'.format(sql_instance_name)])

    prompt = input(color_text('Do you want to reuse an existing MySQL user? (y/N) ', Color.BOLD))
    create_sql_user = True if prompt.lower() != 'y' else False
    sql_user_name = input(color_text('MySQL user name (dqmuser)? ', Color.BOLD)) or 'dqmuser'
    if create_sql_user:
      print(color_text('Creating MySQL user...', Color.BLUE))
      subprocess.check_output(['gcloud', 'sql', 'users', 'create', sql_user_name, '--instance={}'.format(sql_instance_name)])

    print(color_text('Connecting to database...', Color.BLUE))
    subprocess.check_output(['wget', 'https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64', '-O', 'cloud_sql_proxy'], cwd='dqm/backend')
    subprocess.check_output(['chmod', '+x', 'cloud_sql_proxy'], cwd='dqm/backend')
    connection_name = f'{project_id}:{sql_instance_region}:{sql_instance_name}'
    subprocess.Popen(['./cloud_sql_proxy', f'-instances={connection_name}=tcp:3306'], stdout=subprocess.PIPE, cwd='dqm/backend')

    # Wait for database connection to be available...
    time.sleep(4)

    prompt = input(color_text('Do you want to migrate database schema now? (Y/n) ', Color.BOLD))
    migrate_database = True if prompt.lower() != 'n' else False
    if migrate_database:
      print(color_text('Migrating database...', Color.BLUE))
      os.putenv('DQM_CLOUDSQL_CONNECTION_NAME', connection_name)
      os.putenv('DQM_CLOUDSQL_DATABASE', sql_db_name)
      os.putenv('DQM_CLOUDSQL_USER', sql_user_name)
      subprocess.check_output(['python3', '-m', 'pipenv', 'run', 'python', 'manage.py', 'makemigrations'], cwd='dqm/backend')
      subprocess.check_output(['python3', '-m', 'pipenv', 'run', 'python', 'manage.py', 'makemigrations', 'dqm'], cwd='dqm/backend')
      subprocess.check_output(['python3', '-m', 'pipenv', 'run', 'python', 'manage.py', 'migrate'], cwd='dqm/backend')

    return connection_name, sql_user_name, sql_db_name

def update_app_yaml(connection_name: str, sql_user_name: str, sql_db_name: str) -> None:
  if input(color_text('Next step -> Uupdate app.yaml file ([Y]es/[s]kip) ')).lower() != 's':
    with open('dqm/backend/app.yaml', 'r') as f:
      content = f.read()
      content = content.replace('DQM_CLOUDSQL_CONNECTION_NAME: ""', f'DQM_CLOUDSQL_CONNECTION_NAME: "{connection_name}"')
      content = content.replace('DQM_CLOUDSQL_USER: "dqmuser"', f'DQM_CLOUDSQL_USER: "{sql_user_name}"')
      content = content.replace('DQM_CLOUDSQL_DATABASE: "dqm"', f'DQM_CLOUDSQL_DATABASE: "{sql_db_name}"')
    with open('dqm/backend/app.yaml', 'w') as f:
      f.write(content)

def generate_requirements() -> None:
  if input(color_text('Next step -> Generate requirements.txt file ([Y]es/[s]kip) ')).lower() != 's':
    with open('dqm/backend/requirements.txt', 'w') as f:
      subprocess.call(['python3', '-m', 'pipenv', 'lock', '--requirements'], cwd='dqm/backend', stdout=f)

def deploy() -> None:
  if input(color_text('Next step -> Deploy to App Engine ([Y]es/[s]kip) ')).lower() != 's':
    subprocess.check_output(['gcloud', 'app', 'deploy'], cwd='dqm/backend')

if __name__ == '__main__':
  print(color_text('┌────────────────────────────────────────────────┐', Color.HEADER, space_before=False))
  print(color_text('│ Welcome to Data Quality Manager GCP installer! │', Color.HEADER, space_before=False))
  print(color_text('└────────────────────────────────────────────────┘', Color.HEADER, space_before=False))

  project_id = get_project_id()
  check_source_dir()
  clone_repo()
  install_frontend_deps()
  build_frontend()
  install_pipenv()
  install_backend_deps()
  enable_apis()
  create_gae_app()
  create_sa_keys()
  connection_name, sql_user_name, sql_db_name = setup_database()
  if all([connection_name, sql_user_name, sql_db_name]):
    update_app_yaml(connection_name, sql_user_name, sql_db_name)
  generate_requirements()
  deploy()

  print(color_text('All good, thanks for using DQM :)', Color.GREEN))


text:
<!DOCTYPE html>

		<title>threejs webgl - materials - hdr environment mapping</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

			threejs - High dynamic range (RGBE) Image-based Lighting (IBL)
using run-time generated pre-filtered roughness mipmaps (PMREM)

			Created by Prashant Sharma and Ben Houston.


text:
name "curl"
default_version "7.84.0"

dependency "zlib"
dependency "openssl"
dependency "cacerts"

license "MIT"
license_file "COPYING"
skip_transitive_dependency_licensing true

# version_list: url=https://curl.se/download/ filter=*.tar.gz
version("7.85.0") { source sha256: "78a06f918bd5fde3c4573ef4f9806f56372b32ec1829c9ec474799eeee641c27" }
version("7.84.0") { source sha256: "3c6893d38d054d4e378267166858698899e9d87258e8ff1419d020c395384535" }
version("7.83.1") { source sha256: "93fb2cd4b880656b4e8589c912a9fd092750166d555166370247f09d18f5d0c0" }
version("7.82.0") { source sha256: "910cc5fe279dc36e2cca534172c94364cf3fcf7d6494ba56e6c61a390881ddce" }
version("7.81.0") { source sha256: "ac8e1087711084548d788ef18b9b732c8de887457b81f616fc681d1044b32f98" }
version("7.80.0") { source sha256: "dab997c9b08cb4a636a03f2f7f985eaba33279c1c52692430018fae4a4878dc7" }
version("7.79.1") { source sha256: "370b11201349816287fb0ccc995e420277fbfcaf76206e309b3f60f0eda090c2" }

source url: "https://curl.haxx.se/download/curl-#{version}.tar.gz"
internal_source url: "#{ENV["ARTIFACTORY_REPO_URL"]}/#{name}/#{name}-#{version}.tar.gz",
                authorization: "X-JFrog-Art-Api:#{ENV["ARTIFACTORY_TOKEN"]}"

relative_path "curl-#{version}"

build do
  env = with_standard_compiler_flags(with_embedded_path)

  if freebsd? && version.satisfies?("< 7.82.0")
    # from freebsd ports - IPv6 Hostcheck patch
    patch source: "curl-freebsd-hostcheck.patch", plevel: 1, env: env
  end

  delete "#{project_dir}/src/tool_hugehelp.c"

  if aix?
    # alpn doesn't appear to work on AIX when connecting to certain sites, most
    # importantly for us https://www.github.com Since git uses libcurl under
    # the covers, this functionality breaks the handshake on connection, giving
    # a cryptic error. This patch essentially forces disabling of ALPN on AIX,
    # which is not really what we want in a http/2 world, but we're not there
    # yet.
    patch_env = env.dup
    patch_env["PATH"] = "/opt/freeware/bin:#{env["PATH"]}" if aix?
    patch source: "curl-aix-disable-alpn.patch", plevel: 0, env: patch_env

    # otherwise gawk will die during ./configure with variations on the theme of:
    # "/opt/omnibus-toolchain/embedded/lib/libiconv.a(shr4.o) could not be loaded"
    env["LIBPATH"] = "/usr/lib:/lib"
  elsif solaris2?
    # Without /usr/gnu/bin first in PATH the libtool fails during make on Solaris
    env["PATH"] = "/usr/gnu/bin:#{env["PATH"]}"
  end

  configure_options = [
    "--prefix=#{install_dir}/embedded",
    "--disable-option-checking",
    "--disable-manual",
    "--disable-debug",
    "--enable-optimize",
    "--disable-ldap",
    "--disable-ldaps",
    "--disable-rtsp",
    "--enable-proxy",
    "--disable-pop3",
    "--disable-imap",
    "--disable-smtp",
    "--disable-gopher",
    "--disable-dependency-tracking",
    "--enable-ipv6",
    "--without-brotli",
    "--without-libidn2",
    "--without-gnutls",
    "--without-librtmp",
    "--without-zsh-functions-dir",
    "--without-fish-functions-dir",
    "--disable-mqtt",
    "--with-ssl=#{install_dir}/embedded",
    "--with-zlib=#{install_dir}/embedded",
    "--with-ca-bundle=#{install_dir}/embedded/ssl/certs/cacert.pem",
    "--without-zstd",
  ]

  configure(*configure_options, env: env)

  make "-j #{workers}", env: env
  make "install", env: env
end


text: process.stdout.write('pipes stdio');


text:
package com.parse.starter.Login.Flashcard;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by vamnoize on 29/8/2558.
 */
public class ParseHelp {
    String TABLE_NAME_DATA = "RememberTable";
    String TABLE_NAME_CAT = "Categories";
    String id;

    public void  AddCategory (String CatName){
        ParseObject player = new ParseObject(TABLE_NAME_CAT);
        player.put("CategoriesName", CatName);
        player.saveInBackground();
    }

    public void AddData (String wFront,String wBack){
        ParseObject player = new ParseObject(TABLE_NAME_DATA);
        player.put("TextFront", wFront);
        player.put("TextBack", wBack);
        player.saveInBackground();
    }

    public void AddData (String catName,String wFront,String pathFront,ParseFile fileFront,String wBack,String pathBack,ParseFile fileBack){

        ParseObject player = new ParseObject(TABLE_NAME_DATA);
        player.put("CategoriesName",catName);
        player.put("TextFront", wFront);
        player.put("PathImgFront", pathFront);
        player.put("FileImgFront", fileFront);

        player.put("TextBack", wBack);
        player.put("PathImgBack", pathBack);
        player.put("FileImgBack", fileBack);
        player.saveInBackground();
    }
/*
  //public List<setItem> DataList = new ArrayList<setItem>();
  private List<setItem> myDataList = new ArrayList<setItem>();

  public List<setItem> getData(){

      final DataList datalist = new DataList();

      ParseQuery<ParseObject> query = ParseQuery.getQuery("player");
      query.whereEqualTo("name", "rgxh");

      query.findInBackground(new FindCallback<ParseObject>() {
          public void done(List<ParseObject> commentList, ParseException e) {

              for (int i = 0; i < commentList.size(); i++) {

                  id = commentList.get(i).getString("objectID");
                  String name = commentList.get(i).getString("name");
                  String title = commentList.get(i).getString("title");

                  datalist.datalist(id,name,title);

                 /* setItem cWord = new setItem();

                  cWord.setItemID(id);
                  cWord.setItemName(name);
                  cWord.setItemTitle(title);
                  DataList.add(cWord);
dada

                 // Log.d("vamvamtest11", String.valueOf(DataList.size()));
              }
              Log.d("vamvamtest222", String.valueOf(datalist.DataList().size()));
              myDataList = datalist.DataList();

          }
      });
        Log.d("vamvamtest2", String.valueOf(myDataList));
      return datalist.DataList();
    }
*/

}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}

module Database.Neo4j.Types
  (
    Server(..)
  , DValue(..)
  ) where

import Control.Applicative ((<$>))

import Data.Text (Text)
import Data.Data (Data)
import Data.Int (Int64)
import Data.Typeable (Typeable)

import qualified Data.Vector as V

import qualified Data.Aeson as A
import Data.Scientific (toRealFloat, coefficient, base10Exponent)

data DValue
  = Int !Int64
  | Float !Double
  | String !Text
  | Bool !Bool
  | DColl !(V.Vector DValue)
  | DObj !A.Object
  | Null
  deriving (Eq, Show, Data, Typeable)

instance A.FromJSON DValue where
  parseJSON (A.Object o) = return $ DObj o
  parseJSON (A.Array a) = DColl <$> V.mapM A.parseJSON a
  parseJSON (A.String xs) = return $ String xs
  parseJSON (A.Bool b) = return $ Bool b
  parseJSON A.Null = return Null
  parseJSON (A.Number n) = return $! numberToValue
    where
      numberToValue
        -- If the number is larger than Int64, it must be
        -- a float64 (Double in Haskell).
        | n > maxInt = Float $ toRealFloat n
        | e < 0 = Float $ realToFrac n
        | otherwise = Int $ fromIntegral $ coefficient n * 10 ^ e
        where
          e = base10Exponent n
      maxInt = fromIntegral (maxBound :: Int64)

instance A.ToJSON DValue where
  toJSON (Int n) = A.toJSON n
  toJSON (Float d) = A.toJSON d
  toJSON (String xs) = A.toJSON xs
  toJSON (Bool b) = A.toJSON b
  toJSON (DObj o) = A.Object o
  toJSON (DColl xs) = A.Array (V.map A.toJSON xs)
  toJSON Null = A.Null

-- | Server location.
data Server = Server
  { serverURI :: !Text
  -- ^ full URI to server API (db/data/) -- http://host:port/db/data/
  } deriving Show


text:
function SynthNode.makeRBuffer(node)
  if node.buffer == nil then return end
  local bindex = 1
  for i=1,SynthNode.rbuffsize,1 do
    local qsize = Queue.size(node.buffer)
    if bindex <= qsize then
      local s = Queue.get(node.buffer, qsize - bindex)
      s = s / g_maxAmplitude * 20.0
      node.rbuffer[i] = s
      -- renderstep should be set for each synthnode.
      if node.renderstep == nil then
        bindex = bindex + SynthNode.renderstep
      else
        bindex = bindex + node.renderstep
      end
    else
      node.rbuffer[i] = 0.0
    end
  end
end

function SynthNode.updateSynthNode(node)
  SynthNode[node.updateFn](node)
  SynthNode.makeRBuffer(node)
end


text:
package com.aspectran.core.activity.response.transform;

import com.aspectran.core.activity.Activity;
import com.aspectran.core.activity.response.Response;
import com.aspectran.core.activity.response.ResponseException;
import com.aspectran.core.context.rule.TransformRule;
import com.aspectran.core.context.rule.type.FormatType;
import com.aspectran.core.context.rule.type.ResponseType;
import com.aspectran.core.util.logging.Logger;
import com.aspectran.core.util.logging.LoggerFactory;

/**
 * The Class TransformResponse.
 *
 * Created: 2008. 03. 22 PM 5:51:58
 */
public abstract class TransformResponse implements Response {

    private static final Logger logger = LoggerFactory.getLogger(TransformResponse.class);

    private final TransformRule transformRule;

    /**
     * Instantiates a new TransformResponse.
     * @param transformRule the transform rule
     */
    public TransformResponse(TransformRule transformRule) {
        this.transformRule = transformRule;
    }

    @Override
    public ResponseType getResponseType() {
        return TransformRule.RESPONSE_TYPE;
    }

    @Override
    public String getContentType() {
        return transformRule.getContentType();
    }

    /**
     * Gets the format type.
     * @return the format type
     */
    public FormatType getFormatType() {
        return transformRule.getFormatType();
    }

    /**
     * Gets the transform rule.
     * @return the transform rule
     */
    public TransformRule getTransformRule() {
        return transformRule;
    }

    @Override
    public void commit(Activity activity) throws ResponseException {
        if (activity.getResponseAdapter() == null) {
            if (logger.isTraceEnabled()) {
                logger.trace("No response adapter in activity " + activity);
            }
            return;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Response " + transformRule);
        }

        try {
            transform(activity);
        } catch (Exception e) {
            throw new TransformResponseException(transformRule, e);
        }
    }

    abstract protected void transform(Activity activity) throws Exception;

    @Override
    public String toString() {
        return transformRule.toString();
    }

}


text:
class SubjectTypesController < ApplicationController
  before_action :set_subject_type, only: [:show, :edit, :update, :destroy]
  before_action :check_policy, only: [:index, :new, :create]

  # GET /subject_types
  # GET /subject_types.json
  def index
    @subject_types = SubjectType.order(:position)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @subject_types }
    end
  end

  # GET /subject_types/1
  # GET /subject_types/1.json
  def show
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @subject_type }
    end
  end

  # GET /subject_types/new
  # GET /subject_types/new.json
  def new
    @subject_type = SubjectType.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @subject_type }
    end
  end

  # GET /subject_types/1/edit
  def edit
  end

  # POST /subject_types
  # POST /subject_types.json
  def create
    @subject_type = SubjectType.new(subject_type_params)

    respond_to do |format|
      if @subject_type.save
        format.html { redirect_to @subject_type, notice:  t('controller.successfully_created', model: t('activerecord.models.subject_type')) }
        format.json { render json: @subject_type, status: :created, location: @subject_type }
      else
        format.html { render action: "new" }
        format.json { render json: @subject_type.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /subject_types/1
  # PUT /subject_types/1.json
  def update
    if params[:move]
      move_position(@subject_type, params[:move])
      return
    end

    respond_to do |format|
      if @subject_type.update(subject_type_params)
        format.html { redirect_to @subject_type, notice:  t('controller.successfully_updated', model: t('activerecord.models.subject_type')) }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @subject_type.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /subject_types/1
  # DELETE /subject_types/1.json
  def destroy
    @subject_type.destroy

    respond_to do |format|
      format.html { redirect_to subject_types_url, notice: t('controller.successfully_deleted', model: t('activerecord.models.subject_type')) }
      format.json { head :no_content }
    end
  end

  private
  def set_subject_type
    @subject_type = SubjectType.find(params[:id])
    authorize @subject_type
  end

  def check_policy
    authorize SubjectType
  end

  def subject_type_params
    params.require(:subject_type).permit(:name, :display_name, :note)
  end
end


text:
<!--
  ~ Copyright (c) 2010-2017 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<role oid="3931573a-2d85-11e6-8ac1-3c970e44b9e2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3">
    <name>CSV File - Account only</name>
    <description>Role to create normal account on CSV File target resource.</description>
    <inducement>
    	<construction>
    		<!-- The c: prefix in type must be there due to a JAXB bug -->
    		<resourceRef oid="ef2bc95b-76e0-48e2-86d6-3d4f02d3fafe" type="c:ResourceType"/>
    	</construction>
    </inducement>
</role>


text:
""" Lab packages System tests
"""

__author__ = "Yash Tatkondawar"
__copyright__ = "Copyright (c) 2019 Dianomic Systems Inc."
__license__ = "Apache 2.0"
__version__ = "${VERSION}"

import subprocess
import http.client
import json
import pytest
import os
import time
import urllib.parse

SCRIPTS_DIR_ROOT = os.environ.get("FOGLAMP_ROOT") + "/tests/system/lab/scripts/"

# TODO:pass version to install script
def setup_module(module):
    try:
        subprocess.run(["cd $FOGLAMP_ROOT/tests/system/lab && ./remove"], shell=True, check=True)
    except subprocess.CalledProcessError:
        assert False, "remove package script failed!"

    try:
        subprocess.run(["cd $FOGLAMP_ROOT/tests/system/lab && ./install"], shell=True, check=True)
    except subprocess.CalledProcessError:
        assert False, "install package script failed"

def post_request(foglamp_url, post_url, payload):
    conn = http.client.HTTPConnection(foglamp_url)
    conn.request("POST", post_url, json.dumps(payload))
    res = conn.getresponse()
    assert 200 == res.status
    res = res.read().decode()
    r = json.loads(res)
    # print(r)
    return r

def get_request(foglamp_url, get_url):
    con = http.client.HTTPConnection(foglamp_url)
    con.request("GET", get_url)
    resp = con.getresponse()
    r = json.loads(resp.read().decode())
    # print(r)
    return r

def put_request(foglamp_url, put_url, payload):
    conn = http.client.HTTPConnection(foglamp_url)
    conn.request("PUT", put_url, json.dumps(payload))
    res = conn.getresponse()
    assert 200 == res.status
    r = json.loads(res.read().decode())
    # print(r)
    return r

class TestSouth:
    def test_south_sinusoid(self, foglamp_url, retries, wait_time):
        data = {"name": "Sine", "type": "south", "plugin": "sinusoid", "enabled": True, "config": {}}
        post_url = "/foglamp/service"
        post_request(foglamp_url, post_url, data)

        time.sleep(wait_time * 2)

        while retries:
            get_url = "/foglamp/south"
            result = get_request(foglamp_url, get_url)

            assert len(result["services"])
            assert "name" in result["services"][0]
            assert "Sine" == result["services"][0]["name"]

            assert "assets" in result["services"][0]
            if "asset" in result["services"][0]["assets"][0]:
                assert "sinusoid" == result["services"][0]["assets"][0]["asset"]
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! sinusoid data NOT seen in South tab." + foglamp_url + "/foglamp/south"

    def test_sinusoid_in_asset(self, foglamp_url):
        get_url = "/foglamp/asset"
        result = get_request(foglamp_url, get_url)
        assert len(result)
        assert "assetCode" in result[0]
        assert "sinusoid" == result[0]["assetCode"], "sinusoid data NOT seen in Asset tab"

    def test_sinusoid_ping(self, foglamp_url):
        get_url = "/foglamp/ping"
        ping_result = get_request(foglamp_url, get_url)
        assert "dataRead" in ping_result
        assert 0 < ping_result['dataRead'], "sinusoid data NOT seen in ping header"

    def test_sinusoid_graph(self, foglamp_url):
        get_url = "/foglamp/asset/sinusoid?seconds=600"
        result = get_request(foglamp_url, get_url)
        assert len(result)
        assert "reading" in result[0]
        assert "sinusoid" in result[0]["reading"]
        assert 0 < result[0]["reading"]["sinusoid"]

    def test_delete_south_sinusoid(self, foglamp_url):
        conn = http.client.HTTPConnection(foglamp_url)
        conn.request("DELETE", '/foglamp/service/Sine')
        res = conn.getresponse()
        assert 200 == res.status

        get_url = "/foglamp/south"
        result = get_request(foglamp_url, get_url)
        assert [] == result["services"]

        get_url = "/foglamp/service"
        result = get_request(foglamp_url, get_url)
        assert "Sine" not in [s["name"] for s in result["services"]]

        get_url = "/foglamp/category"
        result = get_request(foglamp_url, get_url)
        assert "Sine" not in [s["key"] for s in result["categories"]]

        get_url = "/foglamp/schedule"
        result = get_request(foglamp_url, get_url)
        assert "Sine" not in [s["name"] for s in result["schedules"]]

@pytest.mark.skip(reason="FIXME: To enable North verification on the basis of "
                         "--skip-verify-north-interface fixture value")
class TestNorth:

    def test_north_pi_egress(self, foglamp_url, pi_host, pi_port, pi_token, retries):
        payload = {"name": "PI Server", "plugin": "PI_Server_V2", "type": "north", "schedule_repeat": 30,
                   "schedule_type": "3", "schedule_enabled": True,
                   "config": {"URL": {"value": "https://{}:{}/ingress/messages".format(pi_host, pi_port)},
                              "producerToken": {"value": pi_token}, "compression": {"value": "false"}}}
        post_request(foglamp_url, "/foglamp/scheduled/task", payload)

        while retries:
            r = get_request(foglamp_url, "/foglamp/north")
            if "sent" in r[0]:
                assert 0 < r[0]["sent"]
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! PI data sent not seen in North tab." + foglamp_url + "/foglamp/north"

    def test_north_ping(self, foglamp_url):
        r = get_request(foglamp_url, "/foglamp/ping")
        assert "dataSent" in r
        assert 0 < r['dataSent']

    def test_north_stats_history(self, foglamp_url, retries, wait_time):
        while retries:
            # time.sleep(wait_time)
            get_url = "/foglamp/statistics/history?minutes=10"
            r = get_request(foglamp_url, get_url)
            if "PI Server" in r["statistics"][0]:
                assert 0 < r["statistics"][0]["PI Server"]
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! PI data sent not seen in sent graph. " + foglamp_url + "/foglamp/statistics/history?minutes=10"

class TestSinusoidMaxSquare:

    def add_sinusoid_with_square_and_max_filter(self, foglamp_url):
        data = {"name": "Sine", "type": "south", "plugin": "sinusoid", "enabled": True, "config": {}}
        post_url = "/foglamp/service"
        post_request(foglamp_url, post_url, data)

        # Square expression filter
        data = {"name": "Square", "plugin": "expression",
                "filter_config": {"name": "square", "expression": "if(sinusoid>0,0.5,-0.5)", "enable": "true"}}
        post_request(foglamp_url, "/foglamp/filter", data)

        data = {"pipeline": ["Square"]}
        put_url = "/foglamp/filter/Sine/pipeline?allow_duplicates=true&append_filter=true"
        put_request(foglamp_url, put_url, data)

        # Max expression filter
        data = {"name": "Max2", "plugin": "expression",
                "filter_config": {"name": "max", "expression": "max(sinusoid, square)", "enable": "true"}}
        post_url = "/foglamp/filter"
        post_request(foglamp_url, post_url, data)

        data = {"pipeline": ["Max2"]}
        put_url = "/foglamp/filter/Sine/pipeline?allow_duplicates=true&append_filter=true"
        put_request(foglamp_url, put_url, data)

    def test_sinusoid_max_square(self, foglamp_url, retries, wait_time):
        self.add_sinusoid_with_square_and_max_filter(foglamp_url)
        time.sleep(wait_time * 2)
        while retries:
            get_url = "/foglamp/asset/sinusoid?seconds=600"
            r = get_request(foglamp_url, get_url)
            if "square" in r[0]["reading"] and "max" in r[0]["reading"]:
                assert 0 < r[0]["reading"]["square"]
                assert 0 < r[0]["reading"]["max"]
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! square and max data not seen in sinusoid graph." + foglamp_url + "/foglamp/asset/sinusoid?seconds=600"

class TestRandomwalk:

    def test_add_randomwalk_south(self, foglamp_url, wait_time):
        payload = {"name": "Random", "type": "south", "plugin": "randomwalk", "enabled": True, "config": {}}
        post_url = "/foglamp/service"
        post_request(foglamp_url, post_url, payload)

        time.sleep(wait_time*2)

        # verify Random service
        get_url = "/foglamp/service"
        result = get_request(foglamp_url, get_url)
        assert "Random" in [s["name"] for s in result["services"]]

    def test_randomwalk_with_filter_python35(self, foglamp_url, wait_time, retries):
        data = {"name": "Ema", "plugin": "python35", "filter_config": {"config": {"rate": 0.07}, "enable": "true"}}
        post_request(foglamp_url, "/foglamp/filter", data)

        data = {"pipeline": ["Ema"]}
        put_url = "/foglamp/filter/Random/pipeline?allow_duplicates=true&append_filter=true"
        put_request(foglamp_url, put_url, data)

        url = foglamp_url + '/foglamp/category/Random_Ema/script/upload'
        script_path = 'script=@{}/ema.py'.format(SCRIPTS_DIR_ROOT)
        upload_script = "curl -sX POST '{}' -F '{}'".format(url, script_path)
        exit_code = os.system(upload_script)
        assert exit_code == 0

        time.sleep(wait_time)

        while retries:
            get_url = "/foglamp/asset/randomwalk?seconds=600"
            data = get_request(foglamp_url, get_url)
            if len(data) and "randomwalk" in data[0]["reading"] and "ema" in data[0]["reading"]:
                assert 0 < data[0]["reading"]["randomwalk"]
                assert 0 < data[0]["reading"]["ema"]
                # TODO: verify asset tracker entry
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! randomwalk and ema data not seen in randomwalk graph." + foglamp_url + "/foglamp/asset/randomwalk?seconds=600"

    def test_delete_randomwalk_south(self, foglamp_url):
        conn = http.client.HTTPConnection(foglamp_url)
        conn.request("DELETE", '/foglamp/service/Random')
        res = conn.getresponse()
        assert 200 == res.status, "ERROR! Failed to delete randomwalk service"

        get_url = "/foglamp/service"
        result = get_request(foglamp_url, get_url)
        assert "Random" not in [s["name"] for s in result["services"]]

        get_url = "/foglamp/category"
        result = get_request(foglamp_url, get_url)
        assert "Random" not in [c["key"] for c in result["categories"]]

        get_url = "/foglamp/schedule"
        result = get_request(foglamp_url, get_url)
        assert "Random" not in [sch["name"] for sch in result["schedules"]]

class TestRandomwalk1:

    def test_randomwalk1_south_with_python35_filter(self, foglamp_url, wait_time, retries):
        print("Add Randomwalk south service again ...")
        data = {"name": "Random1", "type": "south", "plugin": "randomwalk", "enabled": True,
                "config": {"assetName": {"value": "randomwalk1"}}}
        post_request(foglamp_url, "/foglamp/service", data)

        # need to wait for FogLAMP to be ready to accept python file
        time.sleep(wait_time)

        data = {"name": "PF", "plugin": "python35", "filter_config": {"config": {"rate": 0.07}, "enable": "true"}}
        post_request(foglamp_url, "/foglamp/filter", data)

        # Apply PF to Random
        data = {"pipeline": ["PF"]}
        put_url = "/foglamp/filter/Random1/pipeline?allow_duplicates=true&append_filter=true"
        put_request(foglamp_url, put_url, data)

        print("upload trendc script...")
        url = foglamp_url + '/foglamp/category/Random1_PF/script/upload'

        script_path = 'script=@{}/trendc.py'.format(SCRIPTS_DIR_ROOT)
        upload_script = "curl -sX POST '{}' -F '{}'".format(url, script_path)
        exit_code = os.system(upload_script)
        assert exit_code == 0

        time.sleep(wait_time)

        while retries:
            get_url = "/foglamp/asset/randomwalk1?seconds=600"
            data = get_request(foglamp_url, get_url)
            if len(data) and "randomwalk" in data[0]["reading"] and "ema_long" in data[0]["reading"]:
                assert 0 < data[0]["reading"]["randomwalk"]
                assert 0 < data[0]["reading"]["ema_long"]
                # TODO: verify ema_short and trend in reading
                # TODO: verify asset tracker entry
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! randomwalk and ema_long data not seen in randomwalk1 graph." + foglamp_url + "/foglamp/asset/randomwalk1?seconds=600"

    def test_randomwalk1_python35_filter_script_content_reconfig(self, foglamp_url, retries, wait_time):
        copy_file = "cp {}/trendc.py {}/trendc.py.bak".format(SCRIPTS_DIR_ROOT, SCRIPTS_DIR_ROOT)
        exit_code = os.system(copy_file)
        assert exit_code == 0

        sed_cmd = "sed -i \"s/reading\[b'ema_long/reading\[b'ema_longX/g\" {}/trendc.py".format(SCRIPTS_DIR_ROOT)
        exit_code = os.system(sed_cmd)
        assert exit_code == 0

        print("upload modified trendc script...")
        url = foglamp_url + '/foglamp/category/Random1_PF/script/upload'
        script_path = 'script=@{}/trendc.py'.format(SCRIPTS_DIR_ROOT)
        upload_script = "curl -sX POST '{}' -F '{}'".format(url, script_path)
        exit_code = os.system(upload_script)
        assert exit_code == 0

        time.sleep(wait_time)

        while retries:
            get_url = "/foglamp/asset/randomwalk1?seconds=600"
            data = get_request(foglamp_url, get_url)
            if len(data) and "randomwalk" in data[0]["reading"] and "ema_longX" in data[0]["reading"]:
                assert 0 < data[0]["reading"]["randomwalk"]
                assert 0 < data[0]["reading"]["ema_longX"]
                break
                # TODO: verify asset tracker entry
            retries -= 1

        move_file = "mv {}/trendc.py.bak {}/trendc.py".format(SCRIPTS_DIR_ROOT, SCRIPTS_DIR_ROOT)
        exit_code = os.system(move_file)
        assert exit_code == 0, "{} cmd failed!".format(move_file)

        if retries == 0:
            assert False, "TIMEOUT! randomwalk and ema_longX data not seen in randomwalk1 graph." + foglamp_url + "/foglamp/asset/randomwalk1?seconds=600"

    def test_randomwalk1_python35_filter_script_reconfig(self, foglamp_url, retries, wait_time):
        url = foglamp_url + '/foglamp/category/Random1_PF/script/upload'
        script_path = 'script=@{}/ema.py'.format(SCRIPTS_DIR_ROOT)
        upload_script = "curl -sX POST '{}' -F '{}'".format(url, script_path)
        exit_code = os.system(upload_script)
        assert exit_code == 0

        time.sleep(wait_time)

        while retries:
            get_url = "/foglamp/asset/randomwalk1?seconds=600"
            data = get_request(foglamp_url, get_url)
            if len(data) and "randomwalk" in data[0]["reading"] and "ema" in data[0]["reading"]:
                assert 0 < data[0]["reading"]["randomwalk"]
                assert 0 < data[0]["reading"]["ema"]
                # TODO: verify asset tracker entry
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! randomwalk and ema data not seen in randomwalk1 graph." + foglamp_url + "/foglamp/asset/randomwalk1?seconds=600"

@pytest.mark.skipif(os.uname()[4][:3] != 'arm', reason="only compatible with arm architecture")
class TestEnviroPhat:
    def test_enviro_phat(self, foglamp_url, retries, wait_time):
        data = {"name": "Enviro", "type": "south", "plugin": "envirophat", "enabled": True,
                "config": {"assetNamePrefix": {"value": "e_"}}}
        post_request(foglamp_url, "/foglamp/service", data)

        data = {"name": "Fahrenheit", "plugin": "expression",
                "filter_config": {"name": "temp_fahr", "expression": "temperature*1.8+32", "enable": "true"}}
        post_request(foglamp_url, "/foglamp/filter", data)

        data = {"pipeline": ["Fahrenheit"]}
        put_url = "/foglamp/filter/Enviro/pipeline?allow_duplicates=true&append_filter=true"
        put_request(foglamp_url, put_url, data)

        time.sleep(wait_time*2)

        while retries:
            get_url = "/foglamp/asset/e_weather?seconds=600"
            data = get_request(foglamp_url, get_url)
            if len(data) and "temperature" in data[0]["reading"] and "max" in data[0]["reading"]:
                assert data[0]["reading"]["temperature"] != ""
                assert data[0]["reading"]["temp_fahr"] != ""
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! temperature and max data not seen in e_weather graph." + foglamp_url + "/foglamp/asset/e_weather?seconds=600"

class TestEventEngine:
    """This will test the Notification service in foglamp."""

    def test_event_engine(self, foglamp_url, retries, wait_time):
        payload = {"name": "FogLAMP Notifications", "type": "notification", "enabled": True}
        post_url = "/foglamp/service"
        post_request(foglamp_url, post_url, payload)

        time.sleep(wait_time)

        svc_found = False
        while retries:
            get_url = "/foglamp/service"
            resp = get_request(foglamp_url, get_url)
            for item in resp["services"]:
                if item['name'] == "FogLAMP Notifications":
                    svc_found = True
                    assert item['status'] == "running"
                    break  # break for loop
            if svc_found:
                break  # break while loop
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! event engine is not running." + foglamp_url + "/foglamp/service"

    def test_positive_sine_notification(self, foglamp_url, retries, wait_time):
        """Add Notification with Threshold Rule and Asset Notification (Positive Sine)"""

        payload = {"name": "Positive Sine", "description": "Positive Sine notification instance", "rule": "Threshold",
                   "channel": "asset", "notification_type": "retriggered", "enabled": True}
        post_url = "/foglamp/notification"
        post_request(foglamp_url, post_url, payload)

        payload = {"asset": "sinusoid", "datapoint": "sinusoid"}
        put_url = "/foglamp/category/rulePositive Sine"
        put_request(foglamp_url, urllib.parse.quote(put_url), payload)

        payload = {"asset": "positive_sine", "description": "positive", "enable": "true"}
        put_url = "/foglamp/category/deliveryPositive Sine"
        put_request(foglamp_url, urllib.parse.quote(put_url), payload)

        time.sleep(wait_time)

        while retries:
            get_url = "/foglamp/asset/positive_sine?seconds=600"
            resp = get_request(foglamp_url, get_url)
            if len(resp) and "event" in resp[0]["reading"] and "rule" in resp[0]["reading"]:
                assert resp[0]["reading"]["event"] == "triggered"
                assert resp[0]["reading"]["rule"] == "Positive Sine"
                break
            retries -= 1

        if retries == 0:
            assert False, "TIMEOUT! positive_sine event not fired." + foglamp_url + "/foglamp/asset/positive_sine?seconds=600"

    def test_negative_sine_notification(self, foglamp_url, remove_data_file, retries, wait_time):
        """Add Notification with Threshold Rule and Asset Notification (Negative Sine)"""
        remove_data_file("/tmp/out")

        payload = {"name": "Negative Sine", "description": "Negative Sine notification instance", "rule": "Threshold",
                   "channel": "python35", "notification_type": "retriggered", "enabled": True}
        post_request(foglamp_url, "/foglamp/notification", payload)

        # Upload Python Script (write_out.py)
        url = foglamp_url + urllib.parse.quote('/foglamp/category/deliveryNegative Sine/script/upload')
        script_path = 'script=@{}/write_out.py'.format(SCRIPTS_DIR_ROOT)
        upload_script = "curl -sX POST '{}' -F '{}'".format(url, script_path)
        exit_code = os.system(upload_script)
        assert exit_code == 0

        payload = {"asset": "sinusoid", "datapoint": "sinusoid", "condition": "<"}
        put_request(foglamp_url, urllib.parse.quote("/foglamp/category/ruleNegative Sine"), payload)

        payload = {"enable": "true"}
        put_request(foglamp_url, urllib.parse.quote("/foglamp/category/deliveryNegative Sine"), payload)

        s = wait_time * 2
        for _ in range(retries):
            if os.path.exists("/tmp/out"):
                break
            time.sleep(s)
            print("sleeping for {}s before retrying the existence check of '/tmp/out'".format(s))

        if not os.path.exists("/tmp/out"):
            assert False, "TIMEOUT! negative_sine event not fired. No /tmp/out file."

    def test_event_toggled_sent_clear(self, foglamp_url, wait_time, retries):
        print("Add sinusoid")
        payload = {"name": "sin #1", "plugin": "sinusoid", "type": "south", "enabled": True}
        post_url = "/foglamp/service"
        resp = post_request(foglamp_url, post_url, payload)
        assert resp["id"] != "", "Failed to add sin #1"
        assert resp["name"] == "sin #1", "Failed to add sin #1"

        print("Create event instance with threshold and asset; with notification trigger type toggled")
        payload = {"name": "test #1", "description": "test notification instance", "rule": "Threshold",
                   "channel": "asset", "notification_type": "toggled", "enabled": True}
        post_url = "/foglamp/notification"
        post_request(foglamp_url, post_url, payload)

        get_url = "/foglamp/notification"
        resp = get_request(foglamp_url, get_url)
        assert "test #1" in [s["name"] for s in resp["notifications"]]

        print("Set rule")
        payload = {"asset": "sinusoid", "datapoint": "sinusoid", "trigger_value": "0.8"}
        put_url = "/foglamp/category/ruletest #1"
        put_request(foglamp_url, urllib.parse.quote(put_url), payload)

        get_url = "/foglamp/category/ruletest #1"
        resp = get_request(foglamp_url, urllib.parse.quote(get_url))
        assert resp["asset"]["value"] == "sinusoid"
        assert resp["datapoint"]["value"] == "sinusoid"
        assert resp["trigger_value"]["value"] == "0.8"

        print("Set delivery")
        payload = {"asset": "sin 0.8", "description": "asset notification", "enable": "true"}
        put_url = "/foglamp/category/deliverytest #1"
        put_request(foglamp_url, urllib.parse.quote(put_url), payload)

        get_url = "/foglamp/category/deliverytest #1"
        resp = get_request(foglamp_url, urllib.parse.quote(get_url))
        assert resp["asset"]["value"] == "sin 0.8"
        assert resp["enable"]["value"] == "true"

        s = wait_time*2

        print("Verify sin 0.8 has been created")
        while retries:
            time.sleep(s)
            get_url = "/foglamp/asset/sin 0.8"
            resp = get_request(foglamp_url, urllib.parse.quote(get_url))
            if len(resp) > 0:
                assert True
                break
            retries -= 1

        # TODO: FOGL-3115 verify asset tracker entry

        if retries == 0:
            assert False, "TIMEOUT! sin 0.8 event not fired." + foglamp_url + "/foglamp/asset/sin 0.8"

        print("When rule is triggred, There should be audit entries for NTFSN & NTFCL")
        get_url = "/foglamp/audit?limit=1&source=NTFSN&severity=INFORMATION"
        resp = get_request(foglamp_url, get_url)
        assert len(resp['audit'])
        assert "test #1" in [s["details"]["name"] for s in resp["audit"]]
        for audit_detail in resp['audit']:
            if "test #1" == audit_detail['details']['name']:
                assert "INFORMATION" == audit_detail['severity']
                assert "NTFSN" == audit_detail['source']

        time.sleep(2)  # let clear event to trigger

        get_url = "/foglamp/audit?limit=1&source=NTFCL&severity=INFORMATION"
        resp = get_request(foglamp_url, get_url)
        assert len(resp['audit'])
        assert "test #1" in [s["details"]["name"] for s in resp["audit"]]
        for audit_detail in resp['audit']:
            if "test #1" == audit_detail['details']['name']:
                assert "INFORMATION" == audit_detail['severity']
                assert "NTFCL" == audit_detail['source']


text:
require 'formula'

class Xapian < Formula
  desc "C++ search engine library with many bindings"
  homepage 'http://xapian.org'
  url 'http://oligarchy.co.uk/xapian/1.2.19/xapian-core-1.2.19.tar.xz'
  sha1 'a8679cd0f708e32f2ec76bcdc198cd9fa2e1d65e'

  bottle do
    sha1 "51971954b89b767f45c0cdbec9b3bc39c4704d2e" => :yosemite
    sha1 "90cc658d5639598783c165938edce758f44657f4" => :mavericks
    sha1 "fd032717423f8440865e9b6b3e82b3d1b70f8fad" => :mountain_lion
  end

  option "java",   "Java bindings"
  option "php",    "PHP bindings"
  option "ruby",   "Ruby bindings"

  depends_on :python => :optional

  resource 'bindings' do
    url 'http://oligarchy.co.uk/xapian/1.2.19/xapian-bindings-1.2.19.tar.xz'
    sha1 '5aa4a5f8d2f8dbc604f7e785a087668543ede9a1'
  end

  skip_clean :la

  def build_any_bindings?
    build.include? 'ruby' or build.with? 'python' or build.include? 'java' or build.include? 'php'
  end

  def install
    system "./configure", "--disable-dependency-tracking",
                          "--prefix=#{prefix}"
    system "make install"
    return unless build_any_bindings?

    resource('bindings').stage do
      args = %W[
        --disable-dependency-tracking
        --prefix=#{prefix}
        XAPIAN_CONFIG=#{bin}/xapian-config
        --without-csharp
        --without-tcl
      ]

      if build.include? 'java'
        args << '--with-java'
      else
        args << '--without-java'
      end

      if build.include? 'ruby'
        ruby_site = lib+'ruby/site_ruby'
        ENV['RUBY_LIB'] = ENV['RUBY_LIB_ARCH'] = ruby_site
        args << '--with-ruby'
      else
        args << '--without-ruby'
      end

      if build.with? 'python'
        (lib+'python2.7/site-packages').mkpath
        ENV['PYTHON_LIB'] = lib+'python2.7/site-packages'
        # configure looks for python2 and system python doesn't install one
        ENV["PYTHON"] = which "python"
        args << "--with-python"
      else
        args << "--without-python"
      end

      if build.include? 'php'
        extension_dir = lib+'php/extensions'
        extension_dir.mkpath
        args << "--with-php" << "PHP_EXTENSION_DIR=#{extension_dir}"
      else
        args << "--without-php"
      end
      system "./configure", *args
      system "make install"
    end
  end

  def caveats
    if build.include? 'ruby'
      <<-EOS.undent
        You may need to add the Ruby bindings to your RUBYLIB from:
          #{HOMEBREW_PREFIX}/lib/ruby/site_ruby

      EOS
    end
  end
end


text:
@*
 * Copyright 2022 HM Revenue & Customs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *@

@import config.ApplicationConfig
@import include._
@import include.status._
@import play.twirl.api.HtmlFormat

@this(main2: include.main2)

@(regNo: String, businessName: Option[String], feeResponse: Option[FeeResponse] = None,
        displayCheckOrUpdateLink: Boolean = true, yourRegistrationInfo: Html = HtmlFormat.empty,
        unreadNotifications: Int = 0, registrationStatus: Html, feeInformation: Html, displayContactLink: Boolean = false,
        withdrawOrDeregisterInformation: Html = HtmlFormat.empty)(implicit request: Request[_],m:Messages, lang: Lang, appConfig: ApplicationConfig)

@main2(title = "Your registration", showURRBanner = true) {

@Messages("your.registration")

            @* empty for layout reasons *@

    @if(!yourRegistrationInfo.equals(HtmlFormat.empty)) {

            @yourRegistrationInfo

                @* empty for layout reasons *@

    }

            @businessName.map { bn =>

@Messages("status.business")

                    @bn

                    @if(displayCheckOrUpdateLink){
                        @Messages("status.amendment.edit")
                    }

            }

@Messages("your.registration.status")

            @registrationStatus

@Messages("your.registration.messages")

@Messages("notifications.youHaveMessages") @if(unreadNotifications > 0){@unreadNotifications}

    @if(!feeInformation.equals(HtmlFormat.empty)) {

            @feeInformation

    }

    @if(displayContactLink) {

@Messages("status.submissionreadyforreview.description.5")
                @Messages("status.submissionreadyforreview.description.5.link")
                @Messages("full.stop")

    }

            @withdrawOrDeregisterInformation

            @* empty for layout reasons *@

    @before_you_go()

    @printLink(linkId="status-submitted-print", gaTag=Some("status-submitted:click:print"))
}


text:
#ifndef ActivityManager_H
#define ActivityManager_H

#include <utils/String16.h>

namespace android {

// Perform a ContentProvider.openFile() call for the given URI.
//
// Returns the native file descriptor for the opened stream, < 0 on error.
extern int openContentProviderFile(const String16& uri);

}

#endif


text:
// Sanity check integration test for kernel_info
// Spec file: specs/kernel_info.table

#include <osquery/tests/integration/tables/helper.h>

namespace osquery {
namespace table_tests {

class KernelInfo : public testing::Test {
  protected:
    void SetUp() override {
      setUpEnvironment();
    }
};

TEST_F(KernelInfo, test_sanity) {
  QueryData data = execute_query("select * from kernel_info");
  ValidationMap row_map = {{"version", NonEmptyString},
                           {"arguments", NormalType},
                           {"path", NormalType},
                           {"device", NonEmptyString}};
  validate_rows(data, row_map);
}

} // namespace table_tests
} // namespace osquery


text:
package org.wso2.andes.server.cluster.coordination.hazelcast.custom.serializer.wrapper;

import org.wso2.andes.server.slot.Slot;

import java.io.Serializable;
import java.util.TreeSet;

/**
 * This class is a wrapper class to a TreeSet<Slot>.It encapsulates a Treeset in order to
 * customize the serialization of a Slot treeset in hazelcast. This class is used because general
 * TreeSet class should not affect with the custom serialization.
 */
public class TreeSetSlotWrapper implements Serializable {

    private TreeSet<Slot> slotTreeSet = new TreeSet<Slot>();

    public TreeSet<Slot> getSlotTreeSet() {
        return slotTreeSet;
    }

    public void setSlotTreeSet(TreeSet<Slot> stringTreeSet) {
        this.slotTreeSet = stringTreeSet;
    }
}


text: I have added new project for testing remote feature of GitHub


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

enum EDDSFlags
{
	DDSF_Caps			= 0x00000001,
	DDSF_Height			= 0x00000002,
	DDSF_Width			= 0x00000004,
	DDSF_PixelFormat	= 0x00001000
};

enum EDDSCaps
{
	DDSC_CubeMap			= 0x00000200,
	DDSC_CubeMap_AllFaces	= 0x00000400 | 0x00000800 | 0x00001000 | 0x00002000 | 0x00004000 | 0x00008000,
	DDSC_Volume				= 0x00200000,
};

#ifndef MAKEFOURCC
#define MAKEFOURCC(ch0, ch1, ch2, ch3)\
	((uint32)(uint8)(ch0) | ((uint32)(uint8)(ch1) << 8) |\
	((uint32)(uint8)(ch2) << 16) | ((uint32)(uint8)(ch3) << 24 ))
#endif

enum EDDSPixelFormat
{
	DDSPF_FourCC		= 0x00000004,
	DDSPF_RGB			= 0x00000040,
	DDSPF_DXT1			= MAKEFOURCC('D','X','T','1'),
	DDSPF_DXT3			= MAKEFOURCC('D','X','T','3'),
	DDSPF_DXT5			= MAKEFOURCC('D','X','T','5')
};

// .DDS subheader.
#pragma pack(push,1)
struct FDDSPixelFormatHeader
{
	uint32 dwSize;
	uint32 dwFlags;
	uint32 dwFourCC;
	uint32 dwRGBBitCount;
	uint32 dwRBitMask;
	uint32 dwGBitMask;
	uint32 dwBBitMask;
	uint32 dwABitMask;
};
#pragma pack(pop)

// .DDS header.
#pragma pack(push,1)
struct FDDSFileHeader
{
	uint32 dwSize;
	uint32 dwFlags;
	uint32 dwHeight;
	uint32 dwWidth;
	uint32 dwLinearSize;
	uint32 dwDepth;
	uint32 dwMipMapCount;
	uint32 dwReserved1[11];
	FDDSPixelFormatHeader ddpf;
	uint32 dwCaps;
	uint32 dwCaps2;
	uint32 dwCaps3;
	uint32 dwCaps4;
	uint32 dwReserved2;
};
#pragma pack(pop)

class FDDSLoadHelper
{
public:
	/** @param Buffer must not be 0 */
	ENGINE_API FDDSLoadHelper(const uint8* Buffer, uint32 Length);

	bool IsValid() const;

	/** @return PF_Unknown for DDS that are not valid or where the format is not [yet] supported */
	ENGINE_API EPixelFormat ComputePixelFormat() const;

	/** @return TSF_Invalid for DDS that are not valid or where the format is not [yet] supported */
	ENGINE_API ETextureSourceFormat ComputeSourceFormat() const;

	/** @param DDS, must not be 0 */
	ENGINE_API uint32 ComputeMipMapCount() const;

	ENGINE_API bool IsValidCubemapTexture() const;

	ENGINE_API bool IsValid2DTexture() const;

	/** @param Face should only be provide for cube map textures. */
	ENGINE_API const uint8* GetDDSDataPointer(ECubeFace Face = CubeFace_PosX) const;

	/** Extracts the cube map size from the texture name */
	ENGINE_API const uint8* GetDDSDataPointer(const UTexture2D& Texture) const;

// for now we allow direct access to the header but that could be changed

	/** !=0 if valid */
	const FDDSFileHeader* DDSHeader;
};


text:
<?php

namespace DTS\eBaySDK\MerchantData\Enums\Test;

use DTS\eBaySDK\MerchantData\Enums\PayPalAccountLevelCodeType;

class PayPalAccountLevelCodeTypeTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new PayPalAccountLevelCodeType();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\MerchantData\Enums\PayPalAccountLevelCodeType', $this->obj);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>详情页</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <link rel="stylesheet" type="text/css" href="./css/base.css">
    <link rel="stylesheet" type="text/css" href="./css/main.css">

楼主

                                {{item.fileName}}
                                打开附件

正在加载中...

                    暂无评论


text: #include "AtomicReference.h"