text:
'use strict';
/**
 * This code represents the Attribute Pool Object of the original Etherpad.
 * 90% of the code is still like in the original Etherpad
 * Look at https://github.com/ether/pad/blob/master/infrastructure/ace/www/easysync2.js
 * You can find a explanation what a attribute pool is here:
 * https://github.com/ether/etherpad-lite/blob/master/doc/easysync/easysync-notes.txt
 */

/*
 * Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
 *
 * 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.
 */

/**
 * A `[key, value]` pair of strings describing a text attribute.
 *
 * @typedef {[string, string]} Attribute
 */

/**
 * Maps an attribute's identifier to the attribute.
 *
 * @typedef {Object.<number, Attribute>} NumToAttrib
 */

/**
 * An intermediate representation of the contents of an attribute pool, suitable for serialization
 * via `JSON.stringify` and transmission to another user.
 *
 * @typedef {Object} Jsonable
 * @property {NumToAttrib} numToAttrib - The pool's attributes and their identifiers.
 * @property {number} nextNum - The attribute ID to assign to the next new attribute.
 */

/**
 * Represents an attribute pool, which is a collection of attributes (pairs of key and value
 * strings) along with their identifiers (non-negative integers).
 *
 * The attribute pool enables attribute interning: rather than including the key and value strings
 * in changesets, changesets reference attributes by their identifiers.
 *
 * There is one attribute pool per pad, and it includes every current and historical attribute used
 * in the pad.
 */
class AttributePool {
  constructor() {
    /**
     * Maps an attribute identifier to the attribute's `[key, value]` string pair.
     *
     * TODO: Rename to `_numToAttrib` once all users have been migrated to call `getAttrib` instead
     * of accessing this directly.
     * @private
     * TODO: Convert to an array.
     * @type {NumToAttrib}
     */
    this.numToAttrib = {}; // e.g. {0: ['foo','bar']}

    /**
     * Maps the string representation of an attribute (`String([key, value])`) to its non-negative
     * identifier.
     *
     * TODO: Rename to `_attribToNum` once all users have been migrated to use `putAttrib` instead
     * of accessing this directly.
     * @private
     * TODO: Convert to a `Map` object.
     * @type {Object.<string, number>}
     */
    this.attribToNum = {}; // e.g. {'foo,bar': 0}

    /**
     * The attribute ID to assign to the next new attribute.
     *
     * TODO: This property will not be necessary once `numToAttrib` is converted to an array (just
     * push onto the array).
     *
     * @private
     * @type {number}
     */
    this.nextNum = 0;
  }

  /**
   * Add an attribute to the attribute set, or query for an existing attribute identifier.
   *
   * @param {Attribute} attrib - The attribute's `[key, value]` pair of strings.
   * @param {boolean} [dontAddIfAbsent=false] - If true, do not insert the attribute into the pool
   *     if the attribute does not already exist in the pool. This can be used to test for
   *     membership in the pool without mutating the pool.
   * @returns {number} The attribute's identifier, or -1 if the attribute is not in the pool.
   */
  putAttrib(attrib, dontAddIfAbsent = false) {
    const str = String(attrib);
    if (str in this.attribToNum) {
      return this.attribToNum[str];
    }
    if (dontAddIfAbsent) {
      return -1;
    }
    const num = this.nextNum++;
    this.attribToNum[str] = num;
    this.numToAttrib[num] = [String(attrib[0] || ''), String(attrib[1] || '')];
    return num;
  }

  /**
   * @param {number} num - The identifier of the attribute to fetch.
   * @returns {Attribute} The attribute with the given identifier, or nullish if there is no such
   *     attribute.
   */
  getAttrib(num) {
    const pair = this.numToAttrib[num];
    if (!pair) {
      return pair;
    }
    return [pair[0], pair[1]]; // return a mutable copy
  }

  /**
   * @param {number} num - The identifier of the attribute to fetch.
   * @returns {string} Eqivalent to `getAttrib(num)[0]` if the attribute exists, otherwise the empty
   *     string.
   */
  getAttribKey(num) {
    const pair = this.numToAttrib[num];
    if (!pair) return '';
    return pair[0];
  }

  /**
   * @param {number} num - The identifier of the attribute to fetch.
   * @returns {string} Eqivalent to `getAttrib(num)[1]` if the attribute exists, otherwise the empty
   *     string.
   */
  getAttribValue(num) {
    const pair = this.numToAttrib[num];
    if (!pair) return '';
    return pair[1];
  }

  /**
   * Executes a callback for each attribute in the pool.
   *
   * @param {Function} func - Callback to call with two arguments: key and value. Its return value
   *     is ignored.
   */
  eachAttrib(func) {
    for (const n of Object.keys(this.numToAttrib)) {
      const pair = this.numToAttrib[n];
      func(pair[0], pair[1]);
    }
  }

  /**
   * @returns {Jsonable} An object that can be passed to `fromJsonable` to reconstruct this
   * attribute pool. The returned object can be converted to JSON.
   */
  toJsonable() {
    return {
      numToAttrib: this.numToAttrib,
      nextNum: this.nextNum,
    };
  }

  /**
   * Replace the contents of this attribute pool with values from a previous call to `toJsonable`.
   *
   * @param {Jsonable} obj - Object returned by `toJsonable` containing the attributes and their
   *     identifiers.
   */
  fromJsonable(obj) {
    this.numToAttrib = obj.numToAttrib;
    this.nextNum = obj.nextNum;
    this.attribToNum = {};
    for (const n of Object.keys(this.numToAttrib)) {
      this.attribToNum[String(this.numToAttrib[n])] = Number(n);
    }
    return this;
  }

  /**
   * Asserts that the data in the pool is consistent. Throws if inconsistent.
   */
  check() {
    if (!Number.isInteger(this.nextNum)) throw new Error('nextNum property is not an integer');
    if (this.nextNum < 0) throw new Error('nextNum property is negative');
    for (const prop of ['numToAttrib', 'attribToNum']) {
      const obj = this[prop];
      if (obj == null) throw new Error(`${prop} property is null`);
      if (typeof obj !== 'object') throw new TypeError(`${prop} property is not an object`);
      const keys = Object.keys(obj);
      if (keys.length !== this.nextNum) {
        throw new Error(`${prop} size mismatch (want ${this.nextNum}, got ${keys.length})`);
      }
    }
    for (let i = 0; i < this.nextNum; ++i) {
      const attr = this.numToAttrib[`${i}`];
      if (!Array.isArray(attr)) throw new TypeError(`attrib ${i} is not an array`);
      if (attr.length !== 2) throw new Error(`attrib ${i} is not an array of length 2`);
      const [k, v] = attr;
      if (k == null) throw new TypeError(`attrib ${i} key is null`);
      if (typeof k !== 'string') throw new TypeError(`attrib ${i} key is not a string`);
      if (v == null) throw new TypeError(`attrib ${i} value is null`);
      if (typeof v !== 'string') throw new TypeError(`attrib ${i} value is not a string`);
      const attrStr = String(attr);
      if (this.attribToNum[attrStr] !== i) throw new Error(`attribToNum for ${attrStr} !== ${i}`);
    }
  }
}

module.exports = AttributePool;

redpajama_set_name: RedPajamaGithub


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

class EditProduct extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('produtos_model');
        $this->load->model('Usuarios_model');
        $this->Usuarios_model->logged();

    }

    public function index() {

    	$this->load->view('edit_product');

    }

    public function editar($id)
    {
    	$data['produto']= $this->produtos_model->getProdutosById($id);
    	//var_dump($data);
    	$this->load->view('edit_product',$data);
    }

    public function update($id)
    {

	    $this->load->helper('form');
	    $this->load->library('form_validation');

	    $this->form_validation->set_rules('inputIdProduct', 'Id Not found', 'required');
	    $this->form_validation->set_rules('inputNomeProduct', 'Nome', 'required');
	    $this->form_validation->set_rules('inputPrecoProduto', 'Preço', 'required');

	    if ($this->form_validation->run() === FALSE)
	    {
	        $this->load->view('edit_product');

	    }
	    else
	    {
	        $this->produtos_model->updateProdutos($id);
	        redirect('Produtos');
	    }
    }

}


text:
from .version import __version__

from .command_decoder import CommandDecoder
from .disconnect_command import DisconnectCommand

from . import enums
from . import data_types
from . import game
from . import lobby


text:
import React from 'react';
import PropTypes from 'prop-types';
import { compose } from 'react-apollo';
import _ from 'underscore';

import ItemEmbed from '../../components/ItemEmbed';
import itemDetailQuery from '../../graphql/queries/detail';

class ItemEmbedContainer extends React.Component {
	render() {
		let item = null;
		console.log(this.props);
		console.log(this.props);
		console.log(this.props);
		console.log(this.props);

		if (
			this.props.itemDetailQuery
			&& this.props.itemDetailQuery.ORPHEUS_project
		) {
			item = this.props.itemDetailQuery.ORPHEUS_project.item;
		}

		if (!item) {
			return null;
		}

		return (
			<ItemEmbed
				{...item}
			/>
		);
	}
}

ItemEmbedContainer.propTypes = {
	itemDetailQuery: PropTypes.object,
};

export default compose(
	itemDetailQuery,
)(ItemEmbedContainer);


text:
<webscript>
  <shortname>Get blog posts (draft)</shortname>
  <description>Gets all draft posts for a blog.</description>
  <url>/api/blog/site/{site}/{container}/{path}/posts/mydrafts</url>
  <url>/api/blog/site/{site}/{container}/posts/mydrafts</url>
  <url>/api/blog/node/{store_type}/{store_id}/{id}/posts/mydrafts</url>
  <format default="json">argument</format>
  <authentication>user</authentication>
  <transaction allow="readonly">required</transaction>
</webscript>


text:
#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_PARAM_RESOLVER_LOCAL_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_PARAM_RESOLVER_LOCAL_H_

#include <functional>
#include <memory>
#include <set>
#include <string>
#include <vector>

#include "tensorflow/core/framework/collective.h"
#include "tensorflow/core/lib/gtl/flatmap.h"
#include "tensorflow/core/protobuf/config.pb.h"

namespace tensorflow {
class CompleteGroupRequest;
class CompleteGroupResponse;
class CompleteInstanceRequest;
class CompleteInstanceResponse;
class DeviceMgr;

// Implements ParamResolverInterface for a single-task context.
// It also implements the functionality necessary to serve as the
// group leader for param resolution in a multi-task context.
class CollectiveParamResolverLocal : public ParamResolverInterface {
 public:
  CollectiveParamResolverLocal(const ConfigProto& config,
                               const DeviceMgr* dev_mgr,
                               DeviceResolverInterface* dev_resolver,
                               const string& task_name);

  ~CollectiveParamResolverLocal() override {}

  void CompleteParamsAsync(const string& device, CollectiveParams* cp,
                           CancellationManager* cancel_mgr,
                           const StatusCallback& done) override;

  void CompleteGroupAsync(const CompleteGroupRequest* request,
                          CompleteGroupResponse* response,
                          CancellationManager* cancel_mgr,
                          const StatusCallback& done) override;

  void CompleteInstanceAsync(const CompleteInstanceRequest* request,
                             CompleteInstanceResponse* response,
                             CancellationManager* cancel_mgr,
                             const StatusCallback& done) override;

 protected:
  // For access to InstanceRec and CompleteDefaultRanking.
  friend class CollectiveParamResolverLocalTest;

  // Used to complete/verify CollGroup.
  struct GroupRec {
    CollGroupParams group;
    mutable mutex mu;
    Status status GUARDED_BY(mu);
    std::set<string> device_set GUARDED_BY(mu);
    std::vector<string> device_list GUARDED_BY(mu);
    std::set<string> task_set GUARDED_BY(mu);
    std::vector<string> task_list GUARDED_BY(mu);
    std::vector<StatusCallback> waiting GUARDED_BY(mu);
  };

  // Finds the GroupRec that corresponds to cp->group_key.
  // Also populates cp->group from that group_rec.
  // Will wait until GroupRec is fully populated or an error arises before
  // calling done.  Callback GroupRec* arg is only valid if status is ok.
  // Ownership of GroupRec stays with this object and does not pass to the
  // callback.
  typedef std::function<void(const Status& s, const GroupRec* gr)>
      GroupRecCallback;
  void CompleteGroupLocal(const string& device, CollectiveParams* cp,
                          const GroupRecCallback& done)
      LOCKS_EXCLUDED(group_mu_);

  // Used to complete/verify CollInstance.
  struct InstanceRec;

  typedef std::function<void(InstanceRec*)> IRConsumer;
  struct InstanceRec {
    // This structure has two mutexes so that a possibly long
    // initialization can be done without holding the instance_mu_
    // table lock the whole time (which can cause an excessive number
    // of threads to block on it), and because the compiler may not
    // permit mutex locks to be taken in more than one order.
    //
    // out_mu guards access to most of the fields.
    // in_mu guards access to a queue of consumer callbacks wanting to
    // read the fields guarded by out_mu.
    //
    // The in_mu should be locked only while holding instance_mu_; the
    // out_mu should be locked only while not holding
    // instance_mu_.
    //
    // When is_init is false (the initial value) any potential user
    // other than the creator should queue a callback on init_waiters.
    // As soon as the shared member of this structure is fully
    // initialized is_init will be set true and those callbacks will
    // be invoked.
    //
    // Once inserted in the table this structure will never be replaced
    // so users can capture the pointer while holding instance_mu_,
    // drop that lock, then take a lock on out_mu before
    // reading/modifying its values.
    mutex in_mu;
    bool is_init GUARDED_BY(in_mu);
    std::vector<IRConsumer> init_waiters GUARDED_BY(in_mu);

    // A thread that wishes to acquire out_mu must ensure that it is available
    // by invoking WaitForOutMu().
    mutex out_mu;
    condition_variable out_cv;
    bool out_mu_available GUARDED_BY(out_mu);
    // Values to be shared by all instances, constant after initialization.
    CollectiveParams shared GUARDED_BY(out_mu);
    // If an error occurs during initialization this structure stays in
    // the table with a non-OK status.  Purging the table and restarting
    // needs to be done at a higher level.
    Status status GUARDED_BY(out_mu);

    // These fields are used to count the instances that have called
    // in and become known while resolving broadcast source identity and
    // communicator key.
    int source_rank GUARDED_BY(out_mu);
    string communicator_key GUARDED_BY(out_mu);
    int known_count GUARDED_BY(out_mu);
    std::vector<bool> known GUARDED_BY(out_mu);
    std::vector<IRConsumer> known_waiters GUARDED_BY(out_mu);

    InstanceRec()
        : is_init(false),
          out_mu_available(true),
          source_rank(-1),
          known_count(0) {}

    // If out_mu is unavailable during distributed device locality
    // initialization, wait on out_cv until it is available again.
    void WaitForOutMu(mutex_lock& lock) EXCLUSIVE_LOCKS_REQUIRED(out_mu);
  };

  // Find the InstanceRec with the same instance_key as cp.  If it doesn't
  // already exist, create and initialize from gr and cp.
  //
  // Precondition: *gr must be a complete GroupRec, i.e. the value set
  // by CompleteGroupLocal. *cp must be populated with all the fields
  // required by InitInstanceSharedParams.  Ownership of InstanceRec stays
  // with this object and does not pass to the callback.
  typedef std::function<void(const Status& s, InstanceRec* ir)>
      InstanceRecCallback;
  void FindInstanceRec(const GroupRec* gr, CollectiveParams* cp,
                       const InstanceRecCallback& done)
      LOCKS_EXCLUDED(instance_mu_, gr->mu, group_mu_);

  // Populate *ir with device membership from gr, then initialize to be specific
  // to cp->instance_key, i.e. order the devices and tasks.
  //
  // Preconditions:
  //  cp is populated with all DeviceLocalities
  void InitInstanceSharedParams(const GroupRec* gr, const CollectiveParams* cp,
                                InstanceRec* ir, const StatusCallback& done)
      UNLOCK_FUNCTION(ir->out_mu) LOCKS_EXCLUDED(gr->mu);

  void CallInitInstanceSharedParams(const GroupRec* gr,
                                    const CollectiveParams* cp, InstanceRec* ir,
                                    const InstanceRecCallback& done)
      LOCKS_EXCLUDED(ir->out_mu, gr->mu);

  // Establishes the final order of ir->shared.instance.device_names and
  // ir->shared.instance.task_names by considering localities of all devices.
  void CompleteDefaultRanking(const GroupRec* gr, const CollectiveParams* cp,
                              InstanceRec* ir,
                              const std::vector<DeviceLocality>& localities)
      EXCLUSIVE_LOCKS_REQUIRED(ir->out_mu);

  // Finish populating *cp.
  // Precondition: *gr has been fully populated by CompleteGroupLocal.
  void CompleteInstanceLocal(const string& device, const GroupRec* gr,
                             CollectiveParams* cp, bool is_source,
                             const StatusCallback& done)
      LOCKS_EXCLUDED(instance_mu_, gr->mu, group_mu_);

  // Finish populating *cp from fully initialized *ir.
  // Precondition: *gr and *ir are fully populated.
  void CompleteInstanceFromInitializedIRec(const string& device,
                                           const GroupRec* gr,
                                           CollectiveParams* cp,
                                           InstanceRec* ir, bool is_source,
                                           const StatusCallback& done)
      LOCKS_EXCLUDED(ir->out_mu);

  // Complete source data and/or nccl communicator key.
  // Precondition: *cp has complete group data and default_rank.
  void WaitForGroup(InstanceRec* ir, CollectiveParams* cp, bool is_source,
                    bool init_source, bool init_nccl, const IRConsumer& f)
      LOCKS_EXCLUDED(ir->out_mu);

  // If cp.device_names contains only devices local to this process
  // populates *localities, else returns an error.
  Status GetLocalDeviceLocalities(const CollectiveParams& cp,
                                  std::vector<DeviceLocality>* localities);

  // Sets CollTaskParams.is_local and CollectiveParams.default_rank.
  // Precondition: cp->device_names is fully populated and in final order.
  void CompleteTaskIsLocal(const string& task_name, CollectiveParams* cp);

  // Sets cp->instance_default_rank according to location of device in
  // current ordering of cp->instance.device_names.
  void SetDefaultRank(const string& device, CollectiveParams* cp);

  // Sets cp->instance.type based on collective op type, and attempts to assign
  // best implementation.
  void AssignCollectiveType(CollectiveParams* cp);

  // Helper to grab status under lock, invoke callback out of lock.
  void CallbackWithStatus(const InstanceRecCallback& done, InstanceRec* irec)
      LOCKS_EXCLUDED(irec->out_mu);

  const bool nccl_;
  const DeviceMgr* dev_mgr_;
  DeviceResolverInterface* dev_resolver_;  // Not owned.
  string task_name_;
  mutex group_mu_;
  gtl::FlatMap<int32, std::unique_ptr<GroupRec>> group_table_
      GUARDED_BY(group_mu_);
  mutex instance_mu_;
  gtl::FlatMap<int32, std::unique_ptr<InstanceRec>> instance_table_
      GUARDED_BY(instance_mu_);
};

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_PARAM_RESOLVER_LOCAL_H_


text:
#ifndef MHOSTINFO_HPP
#define MHOSTINFO_HPP

#include <string>
#include <MStringList>

using namespace std;
class MTcpSocket;

/**
* @class MHostInfo
* @brief class of getting host info
* eg: get peer ip, get local ip, get ns...
*/
class MHostInfo
{
public:
    MHostInfo();
    ~MHostInfo();

    /**
    * @brief get the address of this class
    * @retval if MStringList is empty
    * then retrieve the merrno
    */
    MStringList address();
    int port();

public:
    /**
    * @brief get fd's peer info
    */
    static MHostInfo getPeerInfo(int fd);
    /**
    * @brief get fd's local info
    */
    static MHostInfo getLocalInfo(int fd);
    /**
    * @brief dns lookup
    * @return MHostInfo which has series of ips
    * if the MHostInfo.address() is empty,
    * then should retrieve the merrno
    */
    static MHostInfo lookupHost(const MString &host);

private:
    MStringList _address;
    int _port;
};

#endif // MHOSTINFO_HPP


text:
package hu.sztaki.ilab.longneck.weblog.parser.postprocessor;

import hu.sztaki.ilab.longneck.Field;
import hu.sztaki.ilab.longneck.Record;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;

/**
 * Postprocessor that extracts protocol method and protocol type from the
 * request parameter and builds a proper request url.
 *
 * Note: No info on http / https protocols! All url-s will begin wiht http:// now.
 *
 * This class is thread-safe.
 *
 * E.g:
 *
 *

 * Input:
 * virtualhost:         www.example.com
 * request:             POST /mysite/index.php?id=123&value=abc HTTP/1.1
 *
 * Output:
 * virtualhost:         www.example.com
 * request:             POST /mysite/index.php?id=123&value=abc HTTP/1.1
 * requestUrl:          http://www.example.com/mysite/index.php?id=123&value=abc
 * requestProtMethod:   POST
 * requestProtType:     HTTP/1.1
 *
 *

 *
 * @author Bendig Loránd <lbendig@ilab.sztaki.hu>
 *
 */
public class SplitRequestPostProcessor extends AbstractCachingPostProcessor implements PostProcessor {

    private static final Logger LOG = Logger.getLogger(SplitRequestPostProcessor.class);

    private final Pattern reqSplitPattern = Pattern.compile("^(\\S+)\\s*(\\/*\\S+)\\s*(\\S*)$");

    private final String ATTR_REQ_PROT_METHOD_POSTFIX = "ProtMethod";

    private final String ATTR_REQ_PROT_TYPE_POSTFIX = "ProtType";

    private final String ATTR_REQ_URL = "Url";

    /**
     * Extracts protocol method and protocol type from the
     * request parameter as well as builds request url.
     *
     * @see hu.sztaki.ilab.longneck.weblog.parser.postprocessor.PostProcessor#doPostProcess(
     * java.lang.String, hu.sztaki.ilab.longneck.weblog.parser.processor.LogAttribute, hu.sztaki.ilab.longneck.Record)
     */
    @Override
    public void doPostProcess(String elementName, String elementValue, List<String> relatedFields,
            Record record, boolean caching) {

        try {

            if (elementValue == null) {
                LOG.warn(String.format("Couldn't postprocess field %1$s . No value present", elementName));
                return;
            }

            // fetch virtualhost field using the postprocessor's field definition
            String virtualhostFieldName = relatedFields.get(0); // only one field should be defined
            Field virtualhostField = record.get(virtualhostFieldName);

            if (virtualhostField == null) {
                throw new Exception("Can't find virtualhost field named \"" + virtualhostFieldName + "\"");
            }

            if (caching) {
                // false if the cash is not initialized yet.
                if (!this.isCaching()) {
                    initCache();
                } else {
                    List<Field> splitFields;
                    splitFields = getCacheElement(elementValue);
                    // cache hit
                    if (splitFields != null) {
                        for (Field f : splitFields) {
                            record.add(f);
                        }
                        return;
                    }
                }
            }

            Field reqMethodField = new Field(elementName + ATTR_REQ_PROT_METHOD_POSTFIX);
            Field reqUrl = new Field(elementName + ATTR_REQ_URL);
            Field reqTypeField = new Field(elementName + ATTR_REQ_PROT_TYPE_POSTFIX);

            Matcher m = reqSplitPattern.matcher(elementValue);
            if (m.matches()) {

                reqMethodField.setValue(m.group(1));
                // Note: No info on http / https protocols! All url-s will begin wiht http:// now.
                reqUrl.setValue("http://" + virtualhostField.getValue() + m.group(2));
                reqTypeField.setValue(m.group(3));

                if (caching && this.isCaching()) {
                    List<Field> splitFields;
                    splitFields = new ArrayList<Field>(3);
                    splitFields.add(reqMethodField);
                    splitFields.add(reqUrl);
                    splitFields.add(reqTypeField);

                    putCacheElement(elementValue, splitFields);
                }
                record.add(reqMethodField);
                record.add(reqUrl);
                record.add(reqTypeField);

            }
            else {
                LOG.debug("Request is invalid or non-HTTP compliant! " + elementValue);
            }

        } catch (Exception e) {
            LOG.error("Couldn't postprocess request parameter: " + elementValue);
        }

    }
}


text:
package com.nigel.ecustlock;

import java.io.File;

import com.nigel.service.LockService;
import com.support.Cfg;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

	View switchLayout = null;
	Switch toggleService = null;
	Button btnModifyPwd = null;
	Button btnOpenTrain = null;
	Button btnConfig = null;
//	Button btnMfccTest = null;
	Button btnUserManager = null;
	Button btnTestAuth = null;
	Button btnDeveloper = null;
	View layTrain = null;
	TextView tvTrainDesc = null;

	final String life_tag = "MainActivity";

	boolean trained = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Log.v(life_tag, "onCreate");

		this.switchLayout = (View) super.findViewById(R.id.switch_layout);
		this.toggleService = (Switch) super.findViewById(R.id.service_switch);
		this.btnModifyPwd = (Button) super.findViewById(R.id.btn_modify_passwd);
		this.btnOpenTrain = (Button) super.findViewById(R.id.btn_open_train);
		this.btnConfig = (Button) super.findViewById(R.id.btn_config);
//		this.btnMfccTest = (Button) super.findViewById(R.id.btn_mfcctest);
		this.btnUserManager = (Button) super.findViewById(R.id.btn_user_manager);
		this.btnTestAuth = (Button) super.findViewById(R.id.btn_test_auth);
		this.btnDeveloper = (Button) super.findViewById(R.id.btn_record_30);
		this.tvTrainDesc = (TextView) super.findViewById(R.id.tv_train_desc);

		layTrain = super.findViewById(R.id.layout_train);

		this.btnModifyPwd.setOnClickListener(this);
		this.btnOpenTrain.setOnClickListener(this);
		this.btnConfig.setOnClickListener(this);
//		this.btnMfccTest.setOnClickListener(this);
		this.btnTestAuth.setOnClickListener(this);
		this.btnDeveloper.setOnClickListener(this);

		layTrain.setOnClickListener(this);

		Intent intent = getIntent();
		String userName = intent.getStringExtra("user_name");
		if ( userName.equals("admin") ) {
			this.btnUserManager.setVisibility(View.VISIBLE);
			this.switchLayout.setVisibility(View.VISIBLE);
			this.btnConfig.setVisibility(View.VISIBLE);
			this.btnDeveloper.setVisibility(View.VISIBLE);

			this.btnUserManager.setOnClickListener(this);
//			if (LockService.isRunning(getApplicationContext())) {
			if (LockService.getStatus() == LockService.Status.RUNNING) {
				this.toggleService.setChecked(true);
			}
			else {
				this.toggleService.setChecked(false);
			}
			this.toggleService.setOnCheckedChangeListener( new StartServiceOnCheckedChangeListenerImpl() );
			Cfg.getInstance().setUserName(userName);
		}
		else {
			this.btnUserManager.setVisibility(View.GONE);
			this.switchLayout.setVisibility(View.GONE);
			this.btnConfig.setVisibility(View.GONE);
			this.btnDeveloper.setVisibility(View.GONE);

			Cfg.getInstance().setUserName(userName);
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.v(life_tag, "onStart");
		userCheck();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.v(life_tag, "onResume");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.v(life_tag, "onPause");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.v(life_tag, "onStop");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.v(life_tag, "onDestroy");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.v(life_tag, "onRestart");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * ¼ì²éÓû§Ä¿Â¼½á¹¹
	 */
	private void userCheck() {
		String username = Cfg.getInstance().getUserName();
		String rootDir = Cfg.getInstance().getRootDir();
		String userFileDir = rootDir + Cfg.getInstance().getUsersPath() + File.separator
				+ username + File.separator;
		File userDir = new File(userFileDir);
		Log.d("userDir", userFileDir);
		if (!userDir.exists())
			userDir.mkdirs();

		File featrue = new File(userFileDir + username + Cfg.getInstance().getFeaSuf());
		File model = new File(userFileDir + username + Cfg.getInstance().getMdlSuf());
		if ( featrue.exists() && model.exists() ) {
			trained = true;
			tvTrainDesc.setText("ÒÑѵÁ·");
		}
		else {
			trained = false;
			tvTrainDesc.setText("ÉÐδѵÁ·");
		}
		Log.d("trained", ""+trained);
	}

	private class StartServiceOnCheckedChangeListenerImpl implements OnCheckedChangeListener {

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			Intent service = new Intent(MainActivity.this, LockService.class);
            if (isChecked) {
    			MainActivity.this.startService(service);
            } else {
    			MainActivity.this.stopService(service);
            }
		}

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		Intent intent = null;
		switch (id) {
			case R.id.btn_config:
				intent = new Intent(MainActivity.this, ConfigActivity.class);
				MainActivity.this.startActivity(intent);
				break;
			case R.id.btn_open_train:
			case R.id.layout_train:
				intent = new Intent(MainActivity.this, TrainActivity.class);
				MainActivity.this.startActivity(intent);
				break;
			case R.id.btn_modify_passwd:
				intent = new Intent(MainActivity.this, PasswordActivity.class);
				MainActivity.this.startActivity(intent);
				break;
//			case R.id.btn_mfcctest:
//				intent = new Intent(MainActivity.this, MfccTestActivity.class);
//				MainActivity.this.startActivity(intent);
//				break;
			case R.id.btn_user_manager:
				intent = new Intent(MainActivity.this, UsersActivity.class);
				MainActivity.this.startActivity(intent);
				break;
			case R.id.btn_test_auth:
				intent = new Intent(MainActivity.this, LockActivity.class);
				MainActivity.this.startActivity(intent);
				break;
			case R.id.btn_record_30:
				intent = new Intent(MainActivity.this, DeveloperActivity.class);
				MainActivity.this.startActivity(intent);
				break;
			default:
				break;
		}
	}

}


text:
import pycurl
def curl_result(c):
    effective_url = c.getinfo(pycurl.EFFECTIVE_URL)
    primary_ip = c.getinfo(pycurl.PRIMARY_IP)
    primary_port = c.getinfo(pycurl.PRIMARY_PORT)
    local_ip = c.getinfo(pycurl.LOCAL_IP)
    local_port = c.getinfo(pycurl.LOCAL_PORT)
    speed_download = c.getinfo(pycurl.SPEED_DOWNLOAD)
    size_download = c.getinfo(pycurl.SIZE_DOWNLOAD)
    redirect_time = c.getinfo(pycurl.REDIRECT_TIME)
    redirect_count = c.getinfo(pycurl.REDIRECT_COUNT)
    redirect_url = c.getinfo(pycurl.REDIRECT_URL)
    http_code = c.getinfo(pycurl.HTTP_CODE)
    response_code = c.getinfo(pycurl.RESPONSE_CODE)
    total_time = c.getinfo(pycurl.TOTAL_TIME)
    content_type = c.getinfo(pycurl.CONTENT_TYPE)
    namelookup_time = c.getinfo(pycurl.NAMELOOKUP_TIME)
    info_filetime = c.getinfo(pycurl.INFO_FILETIME)
    http_connectcode = c.getinfo(pycurl.HTTP_CONNECTCODE)
    starttransfer_time = c.getinfo(pycurl.STARTTRANSFER_TIME)
    pretransfer_time = c.getinfo(pycurl.PRETRANSFER_TIME)
    header_size = c.getinfo(pycurl.HEADER_SIZE)
    request_size = c.getinfo(pycurl.REQUEST_SIZE)
    ssl_verifyresult = c.getinfo(pycurl.SSL_VERIFYRESULT)
    num_connects = c.getinfo(pycurl.NUM_CONNECTS)

    return {
        'effective_url': effective_url,
        'primary_ip': primary_ip,
        'primary_port': primary_port,
        'local_ip': local_ip,
        'local_port': local_port,
        'speed_download': speed_download,
        'size_download': size_download,
        'redirect_time': redirect_time,
        'redirect_count': redirect_count,
        'redirect_url': redirect_url,
        'http_code': http_code,
        'response_code': response_code,
        'total_time': total_time,
        'content_type': content_type,
        'namelookup_time': namelookup_time,
        'info_filetime': info_filetime,
        'http_connectcode': http_connectcode,
        'starttransfer_time': starttransfer_time,
        'pretransfer_time': pretransfer_time,
        'header_size': header_size,
        'request_size': request_size,
        'ssl_verifyresult': ssl_verifyresult,
        'num_connects': num_connects,
        # 'proxy_ssl_verifyresult': proxy_ssl_verifyresult,
        # 'app_connecttime': app_connecttime,

    }


text:
package kapacitor

import (
	"fmt"
	"log"
	"sync"
	"time"

	"github.com/influxdata/kapacitor/models"
	"github.com/influxdata/kapacitor/pipeline"
)

type StatsNode struct {
	node
	s       *pipeline.StatsNode
	en      Node
	closing chan struct{}
	closed  bool
	mu      sync.Mutex
}

// Create a new  StreamNode which filters data from a source.
func newStatsNode(et *ExecutingTask, n *pipeline.StatsNode, l *log.Logger) (*StatsNode, error) {
	// Lookup the executing node for stats.
	en := et.lookup[n.SourceNode.ID()]
	if en == nil {
		return nil, fmt.Errorf("no node found for %s", n.SourceNode.Name())
	}
	sn := &StatsNode{
		node:    node{Node: n, et: et, logger: l},
		s:       n,
		en:      en,
		closing: make(chan struct{}),
	}
	sn.node.runF = sn.runStats
	sn.node.stopF = sn.stopStats
	return sn, nil
}

func (s *StatsNode) runStats([]byte) error {
	ticker := time.NewTicker(s.s.Interval)
	defer ticker.Stop()
	point := models.Point{
		Name: "stats",
		Tags: map[string]string{"node": s.en.Name()},
	}
	for {
		select {
		case <-s.closing:
			return nil
		case now := <-ticker.C:
			s.timer.Start()
			point.Time = now.UTC()
			stats := s.en.nodeStatsByGroup()
			for group, stat := range stats {
				point.Fields = stat.Fields
				point.Group = group
				point.Dimensions = stat.Dimensions
				point.Tags = stat.Tags
				s.timer.Pause()
				for _, out := range s.outs {
					err := out.CollectPoint(point)
					if err != nil {
						return err
					}
				}
				s.timer.Resume()
			}
			s.timer.Stop()
		}
	}
}

func (s *StatsNode) stopStats() {
	s.mu.Lock()
	defer s.mu.Unlock()
	if !s.closed {
		s.closed = true
		close(s.closing)
	}
}


text:
<!--

    Copyright 2015 Maven Source Dependencies
    Plugin contributors as indicated by the @author tags.

    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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.l2x6.maven.it</groupId>
    <artifactId>it-srcdeps-tag</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>
  <artifactId>mod-1</artifactId>

  <dependencies>
      <dependency>
        <groupId>org.l2x6.maven.srcdeps.itest</groupId>
        <artifactId>srcdeps-test-artifact</artifactId>
      </dependency>
  </dependencies>

</project>


text:
class BadSessionError < StandardError; end
class UnavailableError < StandardError; end
class RequestFailedError < StandardError; end

module Rockstar
  class Track < Base
    attr_accessor :artist, :artist_mbid, :name, :mbid, :playcount, :rank, :url, :now_playing
    attr_accessor :summary, :content, :streamable, :album, :album_mbid, :date, :date_uts, :duration
    alias_method :now_playing?, :now_playing

    # only seems to be used on top tracks for tag
    attr_accessor :count, :thumbnail, :image, :images

    # for weekly top tracks
    attr_accessor :chartposition

    class << self
      def new_from_xml(xml, doc=nil)
        artist          = (xml).at(:artist)['name']               if (xml).at(:artist) && !(xml).at(:artist)['name'].nil?
        artist          = (xml).at(:artist).at(:name).inner_html  if artist.nil? && (xml).at(:artist) && (xml).at(:artist).at(:name)
        artist          = (xml).at(:artist).inner_html            if artist.nil? && (xml).at(:artist)
        artist          = doc.root['artist']                      if artist.nil? && doc.root['artist']
        name            = (xml).at(:name).inner_html              if (xml).at(:name)
        name            = xml['name']                             if name.nil? && xml['name']

        track = Track.new(artist, name)
        track.load_info(xml)
        track
      end

      def love(artist, track, session_key)
        doc = Hpricot::XML(Track.connection.post("track.love", true, {track: track, artist: artist, sk: session_key}))
        doc.at("lfm")["status"]
      end

      # Search a song
      #
      # limit (Optional) : The number of results to fetch per page. Defaults to 30.
      # page (Optional) : The page number to fetch. Defaults to first page.
      # track (Required) : The track name
      # artist (Optional) : Narrow your search by specifying an artist.
      def search(params = {})
        if params[:track].blank?
          raise ArgumentError, "Missing required argument"
        end

        query = {
          track: params[:track]
        }

        query[:limit]  = params[:limit]  if params[:limit]
        query[:page]   = params[:page]   if params[:page]
        query[:track]  = params[:track]  if params[:track]
        query[:artist] = params[:artist] if params[:artist]

        get_instance('track.search', :search, :track, query, false)
      end

      # Scrobble a song
      #
      # Possible parameters:
      #    session_key (required) : the session key you got during authentification
      #    track       (required) : name of the track
      #    artist      (required) : name of the artist of the track
      #    time        (required) : a time object set to the time the track started playing
      #    album                  : Name of the album
      #    albumArtist            : Name of the album artist if artist differs
      #    trackNumber            : Number of the track
      #    mbid                   : MusicBrainz ID of the track
      #    duration               : track length
      def scrobble(params = {})
        if params[:session_key].blank? || params[:track].blank? || params[:time].nil? || params[:artist].blank?
          raise ArgumentError, "Missing required argument"
        end

        query = {
          sk: params[:session_key],
          "track[0]"    => params[:track],
          "timestamp[0]"=> params[:time].utc.to_i,
          "artist[0]"   => params[:artist]
        }

        query["album[0]"]       = params[:album] if !params[:album].blank?
        query["albumArtist[0]"] = params[:albumArtist] if !params[:albumArtist].blank?
        query["trackNumber[0]"] = params[:trackNumber] if !params[:trackNumber].blank?
        query["mbid[0]"]        = params[:mbid] if !params[:mbid].blank?
        query["duration[0]"]    = params[:duration] if !params[:duration].blank?

        doc = Hpricot::XML(Track.connection.post("track.scrobble", true, query))

        if doc.at("lfm")["status"] == "failed"
          case doc.at("lfm").at("error")["code"].to_i
            when 9
              raise BadSessionError, doc.at("lfm").at("error").inner_html
            when 11, 16
              raise UnavailableError, doc.at("lfm").at("error").inner_html
           else
              raise RequestFailedError, doc.at("lfm").at("error").inner_html
           end
        end

        doc.at("lfm")["status"]
       end

      # Update the current playing song
      #
      # Possible parameters:
      #    session_key (required) : the session key you got during authentification
      #    track       (required) : name of the track
      #    artist      (required) : name of the artist of the track
      #    album                  : Name of the album
      #    albumArtist            : Name of the album artist if artist differs
      #    trackNumber            : Number of the track
      #    mbid                   : MusicBrainz ID of the track
      #    duration               : track length
      def updateNowPlaying(params = {})
        if params[:session_key].blank? || params[:track].blank? || params[:artist].blank?
          raise ArgumentError, "Missing required argument"
        end

        query = {
          sk: params[:session_key],
          "track"    => params[:track],
          "artist"   => params[:artist]
        }

        query["album"]       = params[:album] if !params[:album].blank?
        query["albumArtist"] = params[:albumArtist] if !params[:albumArtist].blank?
        query["trackNumber"] = params[:trackNumber] if !params[:trackNumber].blank?
        query["mbid"]        = params[:mbid] if !params[:mbid].blank?
        query["duration"]    = params[:duration] if !params[:duration].blank?

        doc = Hpricot::XML(Track.connection.post("track.updateNowPlaying", true, query))

        if doc.at("lfm")["status"] == "failed"
          case doc.at("lfm").at("error")["code"].to_i
            when 9
              raise BadSessionError, doc.at("lfm").at("error").inner_html
            when 11, 16
              raise UnavailableError, doc.at("lfm").at("error").inner_html
           else
              raise RequestFailedError, doc.at("lfm").at("error").inner_html
           end
        end

        doc.at("lfm")["status"]
      end

    end

    def initialize(artist, name, o={})
      raise ArgumentError, "Artist is required" if artist.blank?
      raise ArgumentError, "Name is required" if name.blank?
      @artist = artist
      @name = name

      options = {include_info: false}.merge(o)
      load_info if options[:include_info]
    end

    def load_info(xml=nil)
      unless xml
        doc = self.class.fetch_and_parse("track.getInfo", {artist: @artist, track: @name})
        xml = (doc / :track).first
      end

      return self if xml.nil?

      self.now_playing	 = xml['nowplaying'] == 'true' ? true : false
      self.artist_mbid   = (xml).at(:artist)['mbid']               if (xml).at(:artist) && (xml).at(:artist)['mbid']
      self.artist_mbid   = (xml).at(:artist).at(:mbid).inner_html  if artist_mbid.nil? && (xml).at(:artist) && (xml).at(:artist).at(:mbid)
      self.mbid          = (xml).at(:mbid).inner_html              if (xml).at(:mbid)
      self.playcount     = (xml).at(:playcount).inner_html         if (xml).at(:playcount)
      self.chartposition = self.rank = xml['rank']                 if xml['rank']
      self.url           = Base.fix_url((xml).at(:url).inner_html) if (xml).at(:url)
      self.streamable    = (xml).at(:track)['streamable']          if (xml).at(:track) && (xml).at(:track)['streamable']
      self.streamable    = (xml).at(:streamable).inner_html == '1' ? 'yes' : 'no' if streamable.nil? && (xml).at(:streamable)
      self.duration      = (xml).at(:duration).inner_html.to_i     if (xml).at(:duration)

      self.count         = xml['count']                            if xml['count']
      self.album         = (xml).at(:album).inner_html             if (xml).at(:album)
      self.album_mbid    = (xml).at(:album)['mbid']                if (xml).at(:album) && (xml).at(:album)['mbid']
      self.date          = Base.parse_time((xml).at(:date).inner_html)  if (xml).at(:date)
      self.date_uts      = (xml).at(:date)['uts']                  if (xml).at(:date) && (xml).at(:date)['uts']

      if wiki_xml = xml.at(:wiki)
        self.summary     = wiki_xml.at(:summary).to_plain_text     if wiki_xml.at(:summary)
        self.content     = wiki_xml.at(:content).to_plain_text     if wiki_xml.at(:content)
      end

      self.images = {}
      (xml/'image').each {|image|
        self.images[image['size']] = image.inner_html if self.images[image['size']].nil?
      }

      self.thumbnail = images['small']
      self.image     = images['medium']

      self
    end

    def albums(force=false)
      get_instance("track.getInfo", :albums, :album, {track: @name, artist: @artist}, force)
    end

    def fans(force=false)
      get_instance("track.getTopFans", :fans, :user, {track: @name, artist: @artist}, force)
    end

    def tags(force=false)
      get_instance("track.getTopTags", :tags, :tag, {track: @name, artist: @artist}, force)
    end

    def similar(limit = 10, force = false)
      get_instance('track.getSimilar', :similar, :track, {track: @name, artist: @artist, limit: limit}, force)
    end

    # The session_key is returned by auth.session.key
    def love(session_key)
      Track.love(@artist, @name, session_key)
    end

    # scrobble this track
    #   time :       a time object set to the time the track started playing
    #   session_key: the session key you got during authentification
    def scrobble(time, session_key)
      Track.scrobble({
        session_key: session_key,
        time: time,
        track: @name,
        artist: @artist,
        album: @album,
        mbid: @mbid
      })
    end

    # inform last.fm that this track is currently playing
    #   time :       a time object set to the time the track started playing
    #   session_key: the session key you got during authentification
    def updateNowPlaying(time, session_key)
      Track.updateNowPlaying({
        session_key: session_key,
        time: time,
        track: @name,
        artist: @artist,
        album: @album,
        mbid: @mbid
      })
    end
  end
end


text:
package("skia")

    set_homepage("https://skia.org/")
    set_description("A complete 2D graphic library for drawing Text, Geometries, and Images.")

    set_urls("https://skia.googlesource.com/skia.git",
             "https://github.com/google/skia.git")

    add_versions("68046c", "68046cd7be837bd31bc8f0e821a2f82a02dda9cf")

    add_deps("python2", "ninja")

    add_links("skia")
    add_includedirs("include")
    add_includedirs("include/android")
    add_includedirs("include/atlastext")
    add_includedirs("include/c")
    add_includedirs("include/codec")
    add_includedirs("include/config")
    add_includedirs("include/core")
    add_includedirs("include/docs")
    add_includedirs("include/effects")
    add_includedirs("include/encode")
    add_includedirs("include/gpu")
    add_includedirs("include/pathops")
    add_includedirs("include/ports")
    add_includedirs("include/private")
    add_includedirs("include/svg")
    add_includedirs("include/third_party")
    add_includedirs("include/utils")

    -- @note windows: only can build for vs2017 or vs2015 update 3
    on_install("macosx", "linux", "windows", function (package)
        local pathes = os.getenv("PATH") or ""
        pathes = pathes .. path.envsep() .. path.join(os.curdir(), "depot_tools")
        pathes = pathes .. path.envsep() .. path.join(os.curdir(), "bin")
        local args = {is_official_build = false,
                      is_component_build = false,
                      is_debug = package:debug(),
                      skia_enable_gpu = true,
                      skia_enable_pdf = false,
                      skia_enable_nvpr = false,
                      skia_enable_tools = false,
                      skia_use_icu = false,
                      skia_use_sfntly = false,
                      skia_use_piex = false,
                      skia_use_freetype = false,
                      skia_use_harfbuzz = false,
                      skia_use_libheif = false,
                      skia_use_expat = false,
                      skia_use_libjpeg_turbo = false,
                      skia_use_libpng = false,
                      skia_use_libwebp = false,
                      skia_use_zlib = false}
        args.cc  = package:build_getenv("cc")
        args.cxx = package:build_getenv("cxx")
        local argstr = ""
        for k, v in pairs(args) do
            if type(v) == "string" then
                argstr = argstr .. ' ' .. k .. '=\"' .. v .. "\""
            else
                argstr = argstr .. ' ' .. k .. '=' .. tostring(v)
            end
        end
        os.vrun("python2 tools/git-sync-deps")
        os.vrun("bin/gn gen build --args='%s'", argstr:trim())
        os.vrun("ninja -C build")
        os.cp("include", package:installdir())
        os.cp("third_party/skcms/*.h", package:installdir("third_party/skcms"))
        if is_plat("windows") then
            os.cp("build/*.lib", package:installdir("lib"))
        else
            os.cp("build/*.a", package:installdir("lib"))
        end
    end)

    on_test(function (package)
        assert(package:check_cxxsnippets({test = [[
            static void test() {
                SkPaint paint;
                paint.setStyle(SkPaint::kFill_Style);
            }
        ]]}, {configs = {languages = "c++14"}, includes = "core/SkPaint.h", defines = "DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN"}))
    end)


text:
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace EventBus.Tests
{
    public class TestIntegrationOtherEventHandler : IIntegrationEventHandler<TestIntegrationEvent>
    {
        public bool Handled { get; private set; }

        public TestIntegrationOtherEventHandler()
        {
            Handled = false;
        }

        public async Task Handle(TestIntegrationEvent @event)
        {
            Handled = true;
        }
    }
}


text:
/*!
 * \file affinecompose.c
 *

 *
 *      Composable coordinate transforms
 *           l_float32   *createMatrix2dTranslate()
 *           l_float32   *createMatrix2dScale()
 *           l_float32   *createMatrix2dRotate()
 *
 *      Special coordinate transforms on pta
 *           PTA         *ptaTranslate()
 *           PTA         *ptaScale()
 *           PTA         *ptaRotate()
 *
 *      Special coordinate transforms on boxa
 *           BOXA        *boxaTranslate()
 *           BOXA        *boxaScale()
 *           BOXA        *boxaRotate()
 *
 *      General coordinate transform on pta and boxa
 *           PTA         *ptaAffineTransform()
 *           BOXA        *boxaAffineTransform()
 *
 *      Matrix operations
 *           l_int32      l_productMatVec()
 *           l_int32      l_productMat2()
 *           l_int32      l_productMat3()
 *           l_int32      l_productMat4()
 *

 */

#include <math.h>
#include "allheaders.h"

/*-------------------------------------------------------------*
 *                Composable coordinate transforms             *
 *-------------------------------------------------------------*/
/*!
 * \brief   createMatrix2dTranslate()
 *
 * \param[in]    transx  x component of translation wrt. the origin
 * \param[in]    transy  y component of translation wrt. the origin
 * \return  3x3 transform matrix, or NULL on error
 *
 *

 * Notes:
 *      (1) The translation is equivalent to:
 *             v' = Av
 *          where v and v' are 1x3 column vectors in the form
 *             v = [x, y, 1]^    ^ denotes transpose
 *          and the affine tranlation matrix is
 *             A = [ 1   0   tx
 *                   0   1   ty
 *                   0   0    1  ]
 *
 *      (2) We consider translation as with respect to a fixed origin.
 *          In a clipping operation, the origin moves and the points
 *          are fixed, and you use (-tx, -ty) where (tx, ty) is the
 *          translation vector of the origin.
 *

 */
l_float32 *
createMatrix2dTranslate(l_float32  transx,
                        l_float32  transy)
{
l_float32  *mat;

    PROCNAME("createMatrix2dTranslate");

    if ((mat = (l_float32 *)LEPT_CALLOC(9, sizeof(l_float32))) == NULL)
        return (l_float32 *)ERROR_PTR("mat not made", procName, NULL);
    mat[0] = mat[4] = mat[8] = 1;
    mat[2] = transx;
    mat[5] = transy;
    return mat;
}

/*!
 * \brief   createMatrix2dScale()
 *
 * \param[in]    scalex  horizontal scale factor
 * \param[in]    scaley  vertical scale factor
 * \return  3x3 transform matrix, or NULL on error
 *
 *

 * Notes:
 *      (1) The scaling is equivalent to:
 *             v' = Av
 *         where v and v' are 1x3 column vectors in the form
 *              v = [x, y, 1]^    ^ denotes transpose
 *         and the affine scaling matrix is
 *             A = [ sx  0    0
 *                   0   sy   0
 *                   0   0    1  ]
 *
 *      (2) We consider scaling as with respect to a fixed origin.
 *          In other words, the origin is the only point that doesn't
 *          move in the scaling transform.
 *

 */
l_float32 *
createMatrix2dScale(l_float32  scalex,
                    l_float32  scaley)
{
l_float32  *mat;

    PROCNAME("createMatrix2dScale");

    if ((mat = (l_float32 *)LEPT_CALLOC(9, sizeof(l_float32))) == NULL)
        return (l_float32 *)ERROR_PTR("mat not made", procName, NULL);
    mat[0] = scalex;
    mat[4] = scaley;
    mat[8] = 1;
    return mat;
}

/*!
 * \brief   createMatrix2dRotate()
 *
 * \param[in]    xc, yc  location of center of rotation
 * \param[in]    angle  rotation in radians; clockwise is positive
 * \return  3x3 transform matrix, or NULL on error
 *
 *

 * Notes:
 *      (1) The rotation is equivalent to:
 *             v' = Av
 *          where v and v' are 1x3 column vectors in the form
 *             v = [x, y, 1]^    ^ denotes transpose
 *          and the affine rotation matrix is
 *             A = [ cosa   -sina    xc*1-cosa + yc*sina
 *                   sina    cosa    yc*1-cosa - xc*sina
 *                     0       0                 1         ]
 *
 *          If the rotation is about the origin, xc, yc) = (0, 0 and
 *          this simplifies to
 *             A = [ cosa   -sina    0
 *                   sina    cosa    0
 *                     0       0     1 ]
 *
 *          These relations follow from the following equations, which
 *          you can convince yourself are correct as follows.  Draw a
 *          circle centered on xc,yc) and passing through (x,y), with
 *          (x',y') on the arc at an angle 'a' clockwise from (x,y).
 *           [ Hint: cosa + b = cosa * cosb - sina * sinb
 *                   sina + b = sina * cosb + cosa * sinb ]
 *
 *            x' - xc =  x - xc) * cosa - (y - yc * sina
 *            y' - yc =  x - xc) * sina + (y - yc * cosa
 *

 */
l_float32 *
createMatrix2dRotate(l_float32  xc,
                     l_float32  yc,
                     l_float32  angle)
{
l_float32   sina, cosa;
l_float32  *mat;

    PROCNAME("createMatrix2dRotate");

    if ((mat = (l_float32 *)LEPT_CALLOC(9, sizeof(l_float32))) == NULL)
        return (l_float32 *)ERROR_PTR("mat not made", procName, NULL);
    sina = sin(angle);
    cosa = cos(angle);
    mat[0] = mat[4] = cosa;
    mat[1] = -sina;
    mat[2] = xc * (1.0 - cosa) + yc * sina;
    mat[3] = sina;
    mat[5] = yc * (1.0 - cosa) - xc * sina;
    mat[8] = 1;
    return mat;
}

/*-------------------------------------------------------------*
 *            Special coordinate transforms on pta             *
 *-------------------------------------------------------------*/
/*!
 * \brief   ptaTranslate()
 *
 * \param[in]    ptas for initial points
 * \param[in]    transx  x component of translation wrt. the origin
 * \param[in]    transy  y component of translation wrt. the origin
 * \return  ptad  translated points, or NULL on error
 *
 *

 * Notes:
 *      (1) See createMatrix2dTranslate() for details of transform.
 *

 */
PTA *
ptaTranslate(PTA       *ptas,
             l_float32  transx,
             l_float32  transy)
{
l_int32    i, npts;
l_float32  x, y;
PTA       *ptad;

    PROCNAME("ptaTranslate");

    if (!ptas)
        return (PTA *)ERROR_PTR("ptas not defined", procName, NULL);

    npts = ptaGetCount(ptas);
    if ((ptad = ptaCreate(npts)) == NULL)
        return (PTA *)ERROR_PTR("ptad not made", procName, NULL);
    for (i = 0; i < npts; i++) {
        ptaGetPt(ptas, i, &x, &y);
        ptaAddPt(ptad, x + transx, y + transy);
    }

    return ptad;
}

/*!
 * \brief   ptaScale()
 *
 * \param[in]    ptas for initial points
 * \param[in]    scalex  horizontal scale factor
 * \param[in]    scaley  vertical scale factor
 * \return  0 if OK; 1 on error
 *
 *

 * Notes:
 *      (1) See createMatrix2dScale() for details of transform.
 *

 */
PTA *
ptaScale(PTA       *ptas,
         l_float32  scalex,
         l_float32  scaley)
{
l_int32    i, npts;
l_float32  x, y;
PTA       *ptad;

    PROCNAME("ptaScale");

    if (!ptas)
        return (PTA *)ERROR_PTR("ptas not defined", procName, NULL);

    npts = ptaGetCount(ptas);
    if ((ptad = ptaCreate(npts)) == NULL)
        return (PTA *)ERROR_PTR("ptad not made", procName, NULL);
    for (i = 0; i < npts; i++) {
        ptaGetPt(ptas, i, &x, &y);
        ptaAddPt(ptad, scalex * x, scaley * y);
    }

    return ptad;
}

/*!
 * \brief   ptaRotate()
 *
 * \param[in]    ptas for initial points
 * \param[in]    xc, yc  location of center of rotation
 * \param[in]    angle  rotation in radians; clockwise is positive
 * \return  0 if OK; 1 on error
 *
 *

 * Notes;
 *      (1) See createMatrix2dScale() for details of transform.
 *      (2) This transform can be thought of as composed of the
 *          sum of two parts:
 *           a) an (x,y)-dependent rotation about the origin:
 *              xr = x * cosa - y * sina
 *              yr = x * sina + y * cosa
 *           b) an (x,y)-independent translation that depends on the
 *              rotation center and the angle:
 *              xt = xc - xc * cosa + yc * sina
 *              yt = yc - xc * sina - yc * cosa
 *          The translation part (xt,yt) is equal to the difference
 *          between the center (xc,yc) and the location of the
 *          center after it is rotated about the origin.
 *

 */
PTA *
ptaRotate(PTA       *ptas,
          l_float32  xc,
          l_float32  yc,
          l_float32  angle)
{
l_int32    i, npts;
l_float32  x, y, xp, yp, sina, cosa;
PTA       *ptad;

    PROCNAME("ptaRotate");

    if (!ptas)
        return (PTA *)ERROR_PTR("ptas not defined", procName, NULL);

    npts = ptaGetCount(ptas);
    if ((ptad = ptaCreate(npts)) == NULL)
        return (PTA *)ERROR_PTR("ptad not made", procName, NULL);
    sina = sin(angle);
    cosa = cos(angle);
    for (i = 0; i < npts; i++) {
        ptaGetPt(ptas, i, &x, &y);
        xp = xc + (x - xc) * cosa - (y - yc) * sina;
        yp = yc + (x - xc) * sina + (y - yc) * cosa;
        ptaAddPt(ptad, xp, yp);
    }

    return ptad;
}

/*-------------------------------------------------------------*
 *            Special coordinate transforms on boxa            *
 *-------------------------------------------------------------*/
/*!
 * \brief   boxaTranslate()
 *
 * \param[in]    boxas
 * \param[in]    transx  x component of translation wrt. the origin
 * \param[in]    transy  y component of translation wrt. the origin
 * \return  boxad  translated boxas, or NULL on error
 *
 * Notes:
 *      (1) See createMatrix2dTranslate() for details of transform.
 */
BOXA *
boxaTranslate(BOXA       *boxas,
              l_float32  transx,
              l_float32  transy)
{
PTA   *ptas, *ptad;
BOXA  *boxad;

    PROCNAME("boxaTranslate");

    if (!boxas)
        return (BOXA *)ERROR_PTR("boxas not defined", procName, NULL);

    ptas = boxaConvertToPta(boxas, 4);
    ptad = ptaTranslate(ptas, transx, transy);
    boxad = ptaConvertToBoxa(ptad, 4);
    ptaDestroy(&ptas);
    ptaDestroy(&ptad);
    return boxad;
}

/*!
 * \brief   boxaScale()
 *
 * \param[in]    boxas
 * \param[in]    scalex  horizontal scale factor
 * \param[in]    scaley  vertical scale factor
 * \return  boxad  scaled boxas, or NULL on error
 *
 * Notes:
 *      (1) See createMatrix2dScale() for details of transform.
 */
BOXA *
boxaScale(BOXA      *boxas,
          l_float32  scalex,
          l_float32  scaley)
{
PTA   *ptas, *ptad;
BOXA  *boxad;

    PROCNAME("boxaScale");

    if (!boxas)
        return (BOXA *)ERROR_PTR("boxas not defined", procName, NULL);

    ptas = boxaConvertToPta(boxas, 4);
    ptad = ptaScale(ptas, scalex, scaley);
    boxad = ptaConvertToBoxa(ptad, 4);
    ptaDestroy(&ptas);
    ptaDestroy(&ptad);
    return boxad;
}

/*!
 * \brief   boxaRotate()
 *
 * \param[in]    boxas
 * \param[in]    xc, yc  location of center of rotation
 * \param[in]    angle  rotation in radians; clockwise is positive
 * \return  boxad  scaled boxas, or NULL on error
 *
 * Notes:
 *      (1) See createMatrix2dRotate() for details of transform.
 */
BOXA *
boxaRotate(BOXA      *boxas,
           l_float32  xc,
           l_float32  yc,
           l_float32  angle)
{
PTA   *ptas, *ptad;
BOXA  *boxad;

    PROCNAME("boxaRotate");

    if (!boxas)
        return (BOXA *)ERROR_PTR("boxas not defined", procName, NULL);

    ptas = boxaConvertToPta(boxas, 4);
    ptad = ptaRotate(ptas, xc, yc, angle);
    boxad = ptaConvertToBoxa(ptad, 4);
    ptaDestroy(&ptas);
    ptaDestroy(&ptad);
    return boxad;
}

/*-------------------------------------------------------------*
 *            General affine coordinate transform              *
 *-------------------------------------------------------------*/
/*!
 * \brief   ptaAffineTransform()
 *
 * \param[in]    ptas for initial points
 * \param[in]    mat  3x3 transform matrix; canonical form
 * \return  ptad  transformed points, or NULL on error
 */
PTA *
ptaAffineTransform(PTA        *ptas,
                   l_float32  *mat)
{
l_int32    i, npts;
l_float32  vecs[3], vecd[3];
PTA       *ptad;

    PROCNAME("ptaAffineTransform");

    if (!ptas)
        return (PTA *)ERROR_PTR("ptas not defined", procName, NULL);
    if (!mat)
        return (PTA *)ERROR_PTR("transform not defined", procName, NULL);

    vecs[2] = 1;
    npts = ptaGetCount(ptas);
    if ((ptad = ptaCreate(npts)) == NULL)
        return (PTA *)ERROR_PTR("ptad not made", procName, NULL);
    for (i = 0; i < npts; i++) {
        ptaGetPt(ptas, i, &vecs[0], &vecs[1]);
        l_productMatVec(mat, vecs, vecd, 3);
        ptaAddPt(ptad, vecd[0], vecd[1]);
    }

    return ptad;
}

/*!
 * \brief   boxaAffineTransform()
 *
 * \param[in]    boxas
 * \param[in]    mat  3x3 transform matrix; canonical form
 * \return  boxad  transformed boxas, or NULL on error
 */
BOXA *
boxaAffineTransform(BOXA       *boxas,
                    l_float32  *mat)
{
PTA   *ptas, *ptad;
BOXA  *boxad;

    PROCNAME("boxaAffineTransform");

    if (!boxas)
        return (BOXA *)ERROR_PTR("boxas not defined", procName, NULL);
    if (!mat)
        return (BOXA *)ERROR_PTR("transform not defined", procName, NULL);

    ptas = boxaConvertToPta(boxas, 4);
    ptad = ptaAffineTransform(ptas, mat);
    boxad = ptaConvertToBoxa(ptad, 4);
    ptaDestroy(&ptas);
    ptaDestroy(&ptad);
    return boxad;
}

/*-------------------------------------------------------------*
 *                      Matrix operations                      *
 *-------------------------------------------------------------*/
/*!
 * \brief   l_productMatVec()
 *
 * \param[in]    mat  square matrix, as a 1-dimensional %size^2 array
 * \param[in]    vecs input column vector of length %size
 * \param[in]    vecd result column vector
 * \param[in]    size matrix is %size x %size; vectors are length %size
 * \return  0 if OK, 1 on error
 */
l_int32
l_productMatVec(l_float32  *mat,
                l_float32  *vecs,
                l_float32  *vecd,
                l_int32     size)
{
l_int32  i, j;

    PROCNAME("l_productMatVec");

    if (!mat)
        return ERROR_INT("matrix not defined", procName, 1);
    if (!vecs)
        return ERROR_INT("input vector not defined", procName, 1);
    if (!vecd)
        return ERROR_INT("result vector not defined", procName, 1);

    for (i = 0; i < size; i++) {
        vecd[i] = 0;
        for (j = 0; j < size; j++) {
            vecd[i] += mat[size * i + j] * vecs[j];
        }
    }
    return 0;
}

/*!
 * \brief   l_productMat2()
 *
 * \param[in]    mat1  square matrix, as a 1-dimensional size^2 array
 * \param[in]    mat2  square matrix, as a 1-dimensional size^2 array
 * \param[in]    matd  square matrix; product stored here
 * \param[in]    size of matrices
 * \return  0 if OK, 1 on error
 */
l_int32
l_productMat2(l_float32  *mat1,
              l_float32  *mat2,
              l_float32  *matd,
              l_int32     size)
{
l_int32  i, j, k, index;

    PROCNAME("l_productMat2");

    if (!mat1)
        return ERROR_INT("matrix 1 not defined", procName, 1);
    if (!mat2)
        return ERROR_INT("matrix 2 not defined", procName, 1);
    if (!matd)
        return ERROR_INT("result matrix not defined", procName, 1);

    for (i = 0; i < size; i++) {
        for (j = 0; j < size; j++) {
            index = size * i + j;
            matd[index] = 0;
            for (k = 0; k < size; k++)
                 matd[index] += mat1[size * i + k] * mat2[size * k + j];
        }
    }
    return 0;
}

/*!
 * \brief   l_productMat3()
 *
 * \param[in]    mat1  square matrix, as a 1-dimensional size^2 array
 * \param[in]    mat2  square matrix, as a 1-dimensional size^2 array
 * \param[in]    mat3  square matrix, as a 1-dimensional size^2 array
 * \param[in]    matd  square matrix; product stored here
 * \param[in]    size  of matrices
 * \return  0 if OK, 1 on error
 */
l_int32
l_productMat3(l_float32  *mat1,
              l_float32  *mat2,
              l_float32  *mat3,
              l_float32  *matd,
              l_int32     size)
{
l_float32  *matt;

    PROCNAME("l_productMat3");

    if (!mat1)
        return ERROR_INT("matrix 1 not defined", procName, 1);
    if (!mat2)
        return ERROR_INT("matrix 2 not defined", procName, 1);
    if (!mat3)
        return ERROR_INT("matrix 3 not defined", procName, 1);
    if (!matd)
        return ERROR_INT("result matrix not defined", procName, 1);

    if ((matt = (l_float32 *)LEPT_CALLOC(size * size, sizeof(l_float32)))
        == NULL)
        return ERROR_INT("matt not made", procName, 1);
    l_productMat2(mat1, mat2, matt, size);
    l_productMat2(matt, mat3, matd, size);
    LEPT_FREE(matt);
    return 0;
}

/*!
 * \brief   l_productMat4()
 *
 * \param[in]    mat1  square matrix, as a 1-dimensional size^2 array
 * \param[in]    mat2  square matrix, as a 1-dimensional size^2 array
 * \param[in]    mat3  square matrix, as a 1-dimensional size^2 array
 * \param[in]    mat4  square matrix, as a 1-dimensional size^2 array
 * \param[in]    matd  square matrix; product stored here
 * \param[in]    size  of matrices
 * \return  0 if OK, 1 on error
 */
l_int32
l_productMat4(l_float32  *mat1,
              l_float32  *mat2,
              l_float32  *mat3,
              l_float32  *mat4,
              l_float32  *matd,
              l_int32     size)
{
l_float32  *matt;

    PROCNAME("l_productMat4");

    if (!mat1)
        return ERROR_INT("matrix 1 not defined", procName, 1);
    if (!mat2)
        return ERROR_INT("matrix 2 not defined", procName, 1);
    if (!mat3)
        return ERROR_INT("matrix 3 not defined", procName, 1);
    if (!matd)
        return ERROR_INT("result matrix not defined", procName, 1);

    if ((matt = (l_float32 *)LEPT_CALLOC(size * size, sizeof(l_float32)))
         == NULL)
        return ERROR_INT("matt not made", procName, 1);
    l_productMat3(mat1, mat2, mat3, matt, size);
    l_productMat2(matt, mat4, matd, size);
    LEPT_FREE(matt);
    return 0;
}


text:
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>or-tools/src/base/jniutil.h Source File - Doxy</title>
    <link rel="shortcut icon" href="../../../favicon.ico">

    <link href="../../../doxygen.css" rel="stylesheet" type="text/css">
    <link href="../../../tabs.css" rel="stylesheet" type="text/css">

          Generated on: Thu Mar 29 07:46:58 PDT 2012
            for custom file set

        <tt>//
            doxy/
            or-tools/
            src/
            base/
            </tt>

Main Page

Namespaces

Classes

Files

or-tools/src/base/jniutil.h
Go to the documentation of this file.

00001 // Copyright 2010-2012 Google
00002 // Licensed under the Apache License, Version 2.0 (the "License");
00003 // you may not use this file except in compliance with the License.
00004 // You may obtain a copy of the License at
00005 //
00006 //     http://www.apache.org/licenses/LICENSE-2.0
00007 //
00008 // Unless required by applicable law or agreed to in writing, software
00009 // distributed under the License is distributed on an "AS IS" BASIS,
00010 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00011 // See the License for the specific language governing permissions and
00012 // limitations under the License.
00013
00014 #ifndef OR_TOOLS_BASE_JNIUTIL_H_
00015 #define OR_TOOLS_BASE_JNIUTIL_H_
00016
00017 #include <jni.h>
00018 #include <string>
00019 #include "base/logging.h"
00020
00021 class JNIUtil {
00022  public:
00023   // Creates a java jstring from a null-terminated UTF-8 encoded C String
00024   // The caller must delete the jstring reference
00025   static jstring MakeJString(JNIEnv* env, const char* cstr) {
00026     if (cstr == NULL) return NULL;
00027     return env->NewStringUTF(cstr);
00028   }
00029
00030   // Creates a null-terminated UTF-8 encoded C string from a jstring.
00031   // The returned string should be "delete[]"-ed when no longer needed.
00032   static char* MakeCString(JNIEnv* env, jstring str) {
00033     if (str == NULL) return NULL;
00034     jsize length = env->GetStringUTFLength(str);
00035     const char* src = env->GetStringUTFChars(str, NULL);
00036     char* dst = new char[length+1];
00037     memcpy(dst, src, length);
00038     dst[length] = '\0';
00039     env->ReleaseStringUTFChars(str, src);
00040     return dst;
00041   }
00042
00043   // Creates a new char array from a jbyteArray.
00044   // The caller must delete[] the returned array.
00045   static char* MakeCharArray(JNIEnv* env, jbyteArray a, int* size) {
00046     jsize n = env->GetArrayLength(a);
00047     *size = n;
00048     jbyte* jba = new jbyte[n];
00049
00050     env->GetByteArrayRegion(a, 0, n, jba);
00051     // We make use of the fact that jbyte's are really just chars
00052     // If this changes (different VM, etc.) things will break.
00053     return reinterpret_cast<char*>(jba);
00054   }
00055
00056   // Produces a jbyteArray from a char array.
00057   static jbyteArray MakeJByteArray(JNIEnv* env, const char* a, int size) {
00058     // Create empty array object
00059     jbyteArray output = env->NewByteArray(size);
00060     // Fill it
00061     env->SetByteArrayRegion(output, 0, size, reinterpret_cast<const jbyte*>(a));
00062     return output;
00063   }
00064 };
00065
00066 #endif  // OR_TOOLS_BASE_JNIUTIL_H_


text:
static const char* FILTER_TYPES[] = {
	"Sobel 3x3",
	"Scharr 3x3",
	"Prewitt 3x3",
	0
};

static const char* CLASS = "Bumpy";
static const char* HELP = "Bumps.";

static DD::Image::Iop* build( Node* node ) {
	return new Bumpy(node);
}

const DD::Image::Iop::Description Bumpy::description(CLASS, "KasumiL5x/Bumpy", build);

Bumpy::Bumpy( Node* node )
	: Iop(node) {
	_sourceChannel = DD::Image::Chan_Red;
	for( int i = 0; i < 3; ++i ) {
		_normalChannels[i] = DD::Image::Channel(DD::Image::Chan_Red + i);
	}
	_strength = 1.0;
	_invertX = false;
	_invertY = false;
	_invertZ = false;
	_normalize = false;
}

Bumpy::~Bumpy() {
}

void Bumpy::knobs( DD::Image::Knob_Callback f ) {
	DD::Image::Input_Channel_knob(f, &_sourceChannel, 1, 0, "source_channel", "Source Channel");
	DD::Image::Tooltip(f, "Which channel to use in the filter.");
	DD::Image::Newline(f);

	DD::Image::Channel_knob(f, _normalChannels, 3, "normal", "Output Channels");
	DD::Image::Tooltip(f, "Which channels to output the XYZ normal to.");
	DD::Image::Newline(f);

	DD::Image::Float_knob(f, &_strength, DD::Image::IRange(0.1, 100.0), "strength", "Strength");
	DD::Image::Tooltip(f, "Intensity of the filtering.");
	DD::Image::Newline(f);

	DD::Image::Bool_knob(f, &_invertX, "invert_x", "Invert X");
	DD::Image::Bool_knob(f, &_invertY, "invert_y", "Invert Y");
	DD::Image::Bool_knob(f, &_invertZ, "invert_z", "Invert Z");
	DD::Image::Newline(f);

	DD::Image::Bool_knob(f, &_normalize, "normalize", "Normalize");
	DD::Image::Tooltip(f, "Normalizes result into a [0,1] range.");

	DD::Image::Newline(f);

	DD::Image::Enumeration_knob(f, &_filterType, FILTER_TYPES, "filter", "Filter");
	DD::Image::Tooltip(f, "Which filter is used to derive a normal map from the input data.");
}

void Bumpy::_validate( bool for_real ) {
	copy_info();

	// build input mask
	_inputChannels.clear();
	_inputChannels += _sourceChannel;

	// safety check input channel to stop reading invalid data
	if( !DD::Image::intersect(input0().channels(), _inputChannels) ) {
		std::cerr << "Bumpy warning: Input image does not contain requested input channel; skipping.\n";
		set_out_channels(DD::Image::Mask_None);
		info_.turn_on(DD::Image::Mask_None);
		return;
	}

	// build output mask
	_outputChannels.clear();
	for( int i = 0; i < 3; ++i ) {
		_outputChannels += _normalChannels[i];
	}

	// set output channels
	set_out_channels(_outputChannels);
	info_.turn_on(_outputChannels);
}

void Bumpy::_request( int x, int y, int r, int t, DD::Image::ChannelMask channels, int count ) {
	// request input channel and expand the input area for the filter
	DD::Image::ChannelSet newMask(channels);
	newMask += _inputChannels;
	input0().request(x-1, y-1, r+1, t+1, newMask, count+1);
}

void Bumpy::engine( int y, int x, int r, DD::Image::ChannelMask channels, DD::Image::Row& out) {
	// copy input
	input0().get(y, x, r, channels, out);

	int currX = x-1;
	const int currR = r+1;

	// read input tile
	const DD::Image::Interest interest(input0(), currX, y-1, currR, r+1, _inputChannels);
	DD::Image::Row in0(currX, currR);
	input0().get(y+1, currX, currR, channels, in0);
	DD::Image::Row in1(currX, currR);
	input0().get(y, currX, currR, channels, in1);
	DD::Image::Row in2(currX, currR);
	input0().get(y-1, currX, currR, channels, in2);

	// output pointers
	float* outR = out.writable(_normalChannels[0]) + x;
	float* outG = out.writable(_normalChannels[1]) + x;
	float* outB = out.writable(_normalChannels[2]) + x;
	const float* END = outR + (r - x);

	// loop through all pixels
	while( outR < END ) {
		// compute normal using a filter
		DD::Image::Vector3 normal;
		switch( _filterType ) {
			case 0: {
				normal = sobelFilter(currX, in0, in1, in2);
				break;
			}

			case 1: {
				normal = scharrFilter(currX, in0, in1, in2);
				break;
			}

			case 2: {
				normal = prewittFilter(currX, in0, in1, in2);
				break;
			}

			default: {
				normal = DD::Image::Vector3(1.0f, 0.0f, 1.0f); // obvious pink error, hopefully
			}
		}
		// normalize for mathematical sanity
		normal.normalize();

		// inversions
		if( _invertX ) {
			normal.x = -normal.x;
		}
		if( _invertY ) {
			normal.y = -normal.y;
		}
		if( _invertZ ) {
			normal.z = -normal.z;
		}

		// output raw normal or [0,1] normal
		if( _normalize ) {
			*outR++= normal.x * 0.5f + 0.5f;
			*outG++= normal.y * 0.5f + 0.5f;
			*outB++= normal.z * 0.5f + 0.5f;
		} else {
			*outR++= normal.x;
			*outG++= normal.y;
			*outB++= normal.z;
		}

		++currX;
	}
}

const char* Bumpy::Class() const {
	return CLASS;
}

const char* Bumpy::node_help() const {
	return HELP;
}

DD::Image::Vector3 Bumpy::sobelFilter( const int x, const DD::Image::Row& in0, const DD::Image::Row& in1, const DD::Image::Row& in2 ) const {
	// idea and algorithm from the following link:
	// http://stackoverflow.com/questions/2368728/can-normal-maps-be-generated-from-a-texture

	const float* ptr = nullptr;

	// get the filter values using the following sobel kernel:
	// TL TC TR
	// CL CC CR -> CC is the current pixel
	// BL BC BR
	//
	// https://en.wikipedia.org/wiki/Sobel_operator
	//
	// tl;dr the X component of the vector is sobel in X
	// and the Y component of the vector is sobel in Y,
	// then the Z can be the "strength"
	//
	ptr = in0[_sourceChannel] + x;       // set pointer to TL
	const float topLeft = (*ptr++);      // get TL and move to TC
	const float topCenter = (*ptr++);    // get TC and move to TR
	const float topRight = (*ptr);       // get TR
	ptr = in1[_sourceChannel] + x;       // set pointer to CL
	const float centerLeft = (*ptr);     // get CL
	ptr += 2;                            // skip CC and set pointer to CR
	const float centerRight = (*ptr);    // get CR
	ptr = in2[_sourceChannel] + x;       // set pointer to BL
	const float bottomLeft = (*ptr++);   // get BL and move to BC
	const float bottomCenter = (*ptr++); // get BC and move to BR
	const float bottomRight = (*ptr);    // get BR

	// compute vector using sobel filter
	const float dx = (topRight + 2.0f * centerRight + bottomRight) - (topLeft + 2.0f * centerLeft + bottomLeft);
	const float dy = (bottomLeft + 2.0f * bottomCenter + bottomRight) - (topLeft + 2.0f * topCenter + topRight);
	const float dz = 1.0f / _strength;

	DD::Image::Vector3 vec(dx, dy, dz);
	return vec;
}

DD::Image::Vector3 Bumpy::scharrFilter( const int x, const DD::Image::Row& in0, const DD::Image::Row& in1, const DD::Image::Row& in2 ) const {
	const float* ptr = nullptr;
	ptr = in0[_sourceChannel] + x;       // set pointer to TL
	const float topLeft = (*ptr++);      // get TL and move to TC
	const float topCenter = (*ptr++);    // get TC and move to TR
	const float topRight = (*ptr);       // get TR
	ptr = in1[_sourceChannel] + x;       // set pointer to CL
	const float centerLeft = (*ptr);     // get CL
	ptr += 2;                            // skip CC and set pointer to CR
	const float centerRight = (*ptr);    // get CR
	ptr = in2[_sourceChannel] + x;       // set pointer to BL
	const float bottomLeft = (*ptr++);   // get BL and move to BC
	const float bottomCenter = (*ptr++); // get BC and move to BR
	const float bottomRight = (*ptr);    // get BR

	const float dx = ((3.0f*topLeft) + (10.0f*centerLeft) + (3.0f*bottomLeft)) - ((3.0f*topRight) + (10.0f*centerRight) + (3.0f*bottomRight));
	const float dy = ((3.0f*topLeft) + (10.0f*topCenter) + (3.0f*topRight)) - ((3.0f*bottomLeft) + (10.0f*bottomCenter) + (3.0f*bottomRight));
	const float dz = 1.0f / _strength;

	DD::Image::Vector3 vec(dx, dy, dz);
	return vec;
}

DD::Image::Vector3 Bumpy::prewittFilter( const int x, const DD::Image::Row& in0, const DD::Image::Row& in1, const DD::Image::Row& in2 ) const {
	const float* ptr = nullptr;
	ptr = in0[_sourceChannel] + x;       // set pointer to TL
	const float topLeft = (*ptr++);      // get TL and move to TC
	const float topCenter = (*ptr++);    // get TC and move to TR
	const float topRight = (*ptr);       // get TR
	ptr = in1[_sourceChannel] + x;       // set pointer to CL
	const float centerLeft = (*ptr);     // get CL
	ptr += 2;                            // skip CC and set pointer to CR
	const float centerRight = (*ptr);    // get CR
	ptr = in2[_sourceChannel] + x;       // set pointer to BL
	const float bottomLeft = (*ptr++);   // get BL and move to BC
	const float bottomCenter = (*ptr++); // get BC and move to BR
	const float bottomRight = (*ptr);    // get BR

	const float dx = (topRight + centerRight + bottomRight) - (topLeft + centerLeft + bottomLeft);
	const float dy = (bottomLeft + bottomCenter + bottomRight) - (topLeft + topCenter + topRight);
	const float dz = 1.0f / _strength;

	DD::Image::Vector3 vec(dx, dy, dz);
	return vec;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>fastjson</servlet-name>
        <servlet-class>person.FastJsonServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>fastjson</servlet-name>
        <url-pattern>/fastjson</url-pattern>
    </servlet-mapping>
</web-app>