text:
package crypto

// hash.go supplies a few geneeral hashing functions, using the hashing
// algorithm blake2b. Because changing the hashing algorithm for Sia has much
// stronger implications than changing any of the other algorithms, blake2b is
// the only supported algorithm. Sia is not really flexible enough to support
// multiple.

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"errors"
	"hash"

	"github.com/NebulousLabs/Sia/encoding"

	"golang.org/x/crypto/blake2b"
)

const (
	// HashSize is the length of a Hash in bytes.
	HashSize = 32
)

type (
	// Hash is a BLAKE2b 256-bit digest.
	Hash [HashSize]byte

	// HashSlice is used for sorting
	HashSlice []Hash
)

var (
	// ErrHashWrongLen is the error when encoded value has the wrong
	// length to be a hash.
	ErrHashWrongLen = errors.New("encoded value has the wrong length to be a hash")
)

// NewHash returns a blake2b 256bit hasher.
func NewHash() hash.Hash {
	h, _ := blake2b.New256(nil) // cannot fail with nil argument
	return h
}

// HashAll takes a set of objects as input, encodes them all using the encoding
// package, and then hashes the result.
func HashAll(objs ...interface{}) (hash Hash) {
	h := NewHash()
	enc := encoding.NewEncoder(h)
	for _, obj := range objs {
		enc.Encode(obj)
	}
	h.Sum(hash[:0])
	return
}

// HashBytes takes a byte slice and returns the result.
func HashBytes(data []byte) Hash {
	return Hash(blake2b.Sum256(data))
}

// HashObject takes an object as input, encodes it using the encoding package,
// and then hashes the result.
func HashObject(obj interface{}) (hash Hash) {
	h := NewHash()
	encoding.NewEncoder(h).Encode(obj)
	h.Sum(hash[:0])
	return
}

// These functions implement sort.Interface, allowing hashes to be sorted.
func (hs HashSlice) Len() int           { return len(hs) }
func (hs HashSlice) Less(i, j int) bool { return bytes.Compare(hs[i][:], hs[j][:]) < 0 }
func (hs HashSlice) Swap(i, j int)      { hs[i], hs[j] = hs[j], hs[i] }

// LoadString takes a string, parses the hash value of the string, and sets the
// value of the hash equal to the hash value of the string.
func (h *Hash) LoadString(s string) error {
	// *2 because there are 2 hex characters per byte.
	if len(s) != HashSize*2 {
		return ErrHashWrongLen
	}
	hBytes, err := hex.DecodeString(s)
	if err != nil {
		return errors.New("could not unmarshal hash: " + err.Error())
	}
	copy(h[:], hBytes)
	return nil
}

// MarshalJSON marshales a hash as a hex string.
func (h Hash) MarshalJSON() ([]byte, error) {
	return json.Marshal(h.String())
}

// String prints the hash in hex.
func (h Hash) String() string {
	return hex.EncodeToString(h[:])
}

// UnmarshalJSON decodes the json hex string of the hash.
func (h *Hash) UnmarshalJSON(b []byte) error {
	// *2 because there are 2 hex characters per byte.
	// +2 because the encoded JSON string has a `"` added at the beginning and end.
	if len(b) != HashSize*2+2 {
		return ErrHashWrongLen
	}

	// b[1 : len(b)-1] cuts off the leading and trailing `"` in the JSON string.
	hBytes, err := hex.DecodeString(string(b[1 : len(b)-1]))
	if err != nil {
		return errors.New("could not unmarshal hash: " + err.Error())
	}
	copy(h[:], hBytes)
	return nil
}


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Produce a PDF report (export) from a query
 *
 * @package    PhpMyAdmin-Export
 * @subpackage PDF
 */
if (! defined('PHPMYADMIN')) {
    exit;
}

/**
 * Skip the plugin if TCPDF is not available.
 */
if (! file_exists(TCPDF_INC)) {
    $GLOBALS['skip_import'] = true;
    return;
}

/* Get the export interface */
require_once 'libraries/plugins/ExportPlugin.class.php';
/* Get the PMA_ExportPdf class */
require_once 'libraries/plugins/export/PMA_ExportPdf.class.php';

/**
 * Handles the export for the PDF class
 *
 * @package    PhpMyAdmin-Export
 * @subpackage PDF
 */
class ExportPdf extends ExportPlugin
{
    /**
     * PMA_ExportPdf instance
     *
     * @var PMA_ExportPdf
     */
    private $_pdf;

    /**
     * PDF Report Title
     *
     * @var string
     */
    private $_pdfReportTitle;

    /**
     * Constructor
     */
    public function __construct()
    {
        // initialize the specific export PDF variables
        $this->initSpecificVariables();

        $this->setProperties();
    }

    /**
     * Initialize the local variables that are used for export PDF
     *
     * @return void
     */
    protected function initSpecificVariables()
    {
        if (! empty($_POST['pdf_report_title'])) {
            $this->_setPdfReportTitle($_POST['pdf_report_title']);
        }
        $this->_setPdf(new PMA_ExportPdf('L', 'pt', 'A3'));
    }

    /**
     * Sets the export PDF properties
     *
     * @return void
     */
    protected function setProperties()
    {
        $props = 'libraries/properties/';
        include_once "$props/plugins/ExportPluginProperties.class.php";
        include_once "$props/options/groups/OptionsPropertyRootGroup.class.php";
        include_once "$props/options/groups/OptionsPropertyMainGroup.class.php";
        include_once "$props/options/items/MessageOnlyPropertyItem.class.php";
        include_once "$props/options/items/TextPropertyItem.class.php";
        include_once "$props/options/items/HiddenPropertyItem.class.php";

        $exportPluginProperties = new ExportPluginProperties();
        $exportPluginProperties->setText('PDF');
        $exportPluginProperties->setExtension('pdf');
        $exportPluginProperties->setMimeType('application/pdf');
        $exportPluginProperties->setForceFile(true);
        $exportPluginProperties->setOptionsText(__('Options'));

        // create the root group that will be the options field for
        // $exportPluginProperties
        // this will be shown as "Format specific options"
        $exportSpecificOptions = new OptionsPropertyRootGroup();
        $exportSpecificOptions->setName("Format Specific Options");

        // general options main group
        $generalOptions = new OptionsPropertyMainGroup();
        $generalOptions->setName("general_opts");
        // create primary items and add them to the group
        $leaf = new MessageOnlyPropertyItem();
        $leaf->setName("explanation");
        $leaf->setText(
            __('(Generates a report containing the data of a single table)')
        );
        $generalOptions->addProperty($leaf);
        $leaf = new TextPropertyItem();
        $leaf->setName("report_title");
        $leaf->setText(__('Report title:'));
        $generalOptions->addProperty($leaf);
        $leaf = new HiddenPropertyItem();
        $leaf->setName("structure_or_data");
        $generalOptions->addProperty($leaf);
        // add the main group to the root group
        $exportSpecificOptions->addProperty($generalOptions);

        // set the options for the export plugin property item
        $exportPluginProperties->setOptions($exportSpecificOptions);
        $this->properties = $exportPluginProperties;
    }

    /**
     * Outputs export header
     *
     * @return bool Whether it succeeded
     */
    public function exportHeader ()
    {
        $pdf_report_title = $this->_getPdfReportTitle();
        $pdf = $this->_getPdf();
        $pdf->Open();

        $attr = array('titleFontSize' => 18, 'titleText' => $pdf_report_title);
        $pdf->setAttributes($attr);
        $pdf->setTopMargin(30);

        return true;
    }

    /**
     * Outputs export footer
     *
     * @return bool Whether it succeeded
     */
    public function exportFooter ()
    {
        $pdf = $this->_getPdf();

        // instead of $pdf->Output():
        if (! PMA_exportOutputHandler($pdf->getPDFData())) {
            return false;
        }

        return true;
    }

    /**
     * Outputs database header
     *
     * @param string $db       Database name
     * @param string $db_alias Aliases of db
     *
     * @return bool Whether it succeeded
     */
    public function exportDBHeader ($db, $db_alias = '')
    {
        return true;
    }

    /**
     * Outputs database footer
     *
     * @param string $db Database name
     *
     * @return bool Whether it succeeded
     */
    public function exportDBFooter ($db)
    {
        return true;
    }

    /**
     * Outputs CREATE DATABASE statement
     *
     * @param string $db       Database name
     * @param string $db_alias Aliases of db
     *
     * @return bool Whether it succeeded
     */
    public function exportDBCreate($db, $db_alias = '')
    {
        return true;
    }
    /**
     * Outputs the content of a table in NHibernate format
     *
     * @param string $db        database name
     * @param string $table     table name
     * @param string $crlf      the end of line sequence
     * @param string $error_url the url to go back in case of error
     * @param string $sql_query SQL query for obtaining data
     * @param array  $aliases   Aliases of db/table/columns
     *
     * @return bool Whether it succeeded
     */
    public function exportData(
        $db, $table, $crlf, $error_url, $sql_query, $aliases = array()
    ) {
        $db_alias = $db;
        $table_alias = $table;
        $this->initAlias($aliases, $db_alias, $table_alias);
        $pdf = $this->_getPdf();

        $attr = array(
            'currentDb' => $db, 'currentTable' => $table,
            'dbAlias' => $db_alias, 'tableAlias' => $table_alias,
            'aliases' => $aliases
        );
        $pdf->setAttributes($attr);
        $pdf->mysqlReport($sql_query);

        return true;
    } // end of the 'PMA_exportData()' function

    /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */

    /**
     * Gets the PMA_ExportPdf instance
     *
     * @return PMA_ExportPdf
     */
    private function _getPdf()
    {
        return $this->_pdf;
    }

    /**
     * Instantiates the PMA_ExportPdf class
     *
     * @param PMA_ExportPdf $pdf The instance
     *
     * @return void
     */
    private function _setPdf($pdf)
    {
        $this->_pdf = $pdf;
    }

    /**
     * Gets the PDF report title
     *
     * @return string
     */
    private function _getPdfReportTitle()
    {
        return $this->_pdfReportTitle;
    }

    /**
     * Sets the PDF report title
     *
     * @param string $pdfReportTitle PDF report title
     *
     * @return void
     */
    private function _setPdfReportTitle($pdfReportTitle)
    {
        $this->_pdfReportTitle = $pdfReportTitle;
    }
}
?>

redpajama_set_name: RedPajamaGithub


text:
package herddb.model.planner;

import herddb.core.HerdDBInternalException;
import herddb.core.TableSpaceManager;
import herddb.model.StatementEvaluationContext;
import herddb.model.StatementExecutionException;
import herddb.model.StatementExecutionResult;
import herddb.model.TransactionContext;
import herddb.utils.Wrapper;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.apache.bookkeeper.common.concurrent.FutureUtils;

/**
 * Generic step of planned operation
 *
 * @author eolivelli
 */
public interface PlannerOp extends Wrapper {

    public String getTablespace();

    public default StatementExecutionResult execute(TableSpaceManager tableSpaceManager,
            TransactionContext transactionContext,
            StatementEvaluationContext context, boolean lockRequired, boolean forWrite) throws StatementExecutionException {
        CompletableFuture<StatementExecutionResult> res = executeAsync(tableSpaceManager, transactionContext, context, lockRequired, forWrite);
        try {
            return res.get();
        } catch (InterruptedException err) {
            Thread.currentThread().interrupt();
            throw new StatementExecutionException(err);
        } catch (ExecutionException err) {
            Throwable cause = err.getCause();
            if (cause instanceof HerdDBInternalException && cause.getCause() != null) {
                cause = cause.getCause();
            }
            if (cause instanceof StatementExecutionException) {
                throw (StatementExecutionException) cause;
            } else {
                throw new StatementExecutionException(cause);
            }
        } catch (Throwable t) {
            throw new StatementExecutionException(t);
        }
    }

    public default CompletableFuture<StatementExecutionResult> executeAsync(TableSpaceManager tableSpaceManager,
            TransactionContext transactionContext,
            StatementEvaluationContext context, boolean lockRequired, boolean forWrite) {
        try {
            return CompletableFuture.completedFuture(execute(tableSpaceManager, transactionContext, context, lockRequired, forWrite));
        } catch (StatementExecutionException err) {
            return FutureUtils.exception(err);
        }
    }

    /**
     * Optimize this node, eventually merging this node with its inputs
     *
     * @return
     */
    public default PlannerOp optimize() {
        return this;
    }

    /**
     * This operation is barely a directly a wrapper for a low level Statement.
     * It is expected that unwrap(Statement.class) will return the wrapped statement
     *
     * @return true for simple DML operations
     */
    public default boolean isSimpleStatementWrapper() {
        return false;
    }
}


text:
package org.hl7.fhir.instance.model.valuesets;

// Generated on Sat, Aug 22, 2015 23:00-0400 for FHIR v0.5.0

public enum V3Charset {

        /**
         * HL7 is indifferent to the use of this Charset.
         */
        EBCDIC,
        /**
         * Deprecated for HL7 use.
         */
        ISO10646UCS2,
        /**
         * Deprecated for HL7 use.
         */
        ISO10646UCS4,
        /**
         * HL7 is indifferent to the use of this Charset.
         */
        ISO88591,
        /**
         * HL7 is indifferent to the use of this Charset.
         */
        ISO88592,
        /**
         * HL7 is indifferent to the use of this Charset.
         */
        ISO88595,
        /**
         * HL7 is indifferent to the use of this Charset.
         */
        JIS2022JP,
        /**
         * Required for HL7 use.
         */
        USASCII,
        /**
         * HL7 is indifferent to the use of this Charset.
         */
        UTF7,
        /**
         * Required for Unicode support.
         */
        UTF8,
        /**
         * added to help the parsers
         */
        NULL;
        public static V3Charset fromCode(String codeString) throws Exception {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("EBCDIC".equals(codeString))
          return EBCDIC;
        if ("ISO-10646-UCS-2".equals(codeString))
          return ISO10646UCS2;
        if ("ISO-10646-UCS-4".equals(codeString))
          return ISO10646UCS4;
        if ("ISO-8859-1".equals(codeString))
          return ISO88591;
        if ("ISO-8859-2".equals(codeString))
          return ISO88592;
        if ("ISO-8859-5".equals(codeString))
          return ISO88595;
        if ("JIS-2022-JP".equals(codeString))
          return JIS2022JP;
        if ("US-ASCII".equals(codeString))
          return USASCII;
        if ("UTF-7".equals(codeString))
          return UTF7;
        if ("UTF-8".equals(codeString))
          return UTF8;
        throw new Exception("Unknown V3Charset code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case EBCDIC: return "EBCDIC";
            case ISO10646UCS2: return "ISO-10646-UCS-2";
            case ISO10646UCS4: return "ISO-10646-UCS-4";
            case ISO88591: return "ISO-8859-1";
            case ISO88592: return "ISO-8859-2";
            case ISO88595: return "ISO-8859-5";
            case JIS2022JP: return "JIS-2022-JP";
            case USASCII: return "US-ASCII";
            case UTF7: return "UTF-7";
            case UTF8: return "UTF-8";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/v3/Charset";
        }
        public String getDefinition() {
          switch (this) {
            case EBCDIC: return "HL7 is indifferent to the use of this Charset.";
            case ISO10646UCS2: return "Deprecated for HL7 use.";
            case ISO10646UCS4: return "Deprecated for HL7 use.";
            case ISO88591: return "HL7 is indifferent to the use of this Charset.";
            case ISO88592: return "HL7 is indifferent to the use of this Charset.";
            case ISO88595: return "HL7 is indifferent to the use of this Charset.";
            case JIS2022JP: return "HL7 is indifferent to the use of this Charset.";
            case USASCII: return "Required for HL7 use.";
            case UTF7: return "HL7 is indifferent to the use of this Charset.";
            case UTF8: return "Required for Unicode support.";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case EBCDIC: return "EBCDIC";
            case ISO10646UCS2: return "ISO-10646-UCS-2";
            case ISO10646UCS4: return "ISO-10646-UCS-4";
            case ISO88591: return "ISO-8859-1";
            case ISO88592: return "ISO-8859-2";
            case ISO88595: return "ISO-8859-5";
            case JIS2022JP: return "JIS-2022-JP";
            case USASCII: return "US-ASCII";
            case UTF7: return "UTF-7";
            case UTF8: return "UTF-8";
            default: return "?";
          }
    }

}


text:
function __processArg(obj, key) {
    var arg = null;
    if (obj) {
        arg = obj[key] || null;
        delete obj[key];
    }
    return arg;
}

function Controller() {
    function close() {
        DRAWER.navigation("onlinePurchases", 1);
    }
    function download() {
        DRAWER.navigation("onlinePurchases", 1);
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "hopOn5";
    if (arguments[0]) {
        {
            __processArg(arguments[0], "__parentSymbol");
        }
        {
            __processArg(arguments[0], "$model");
        }
        {
            __processArg(arguments[0], "__itemTemplate");
        }
    }
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.hopOn5 = Ti.UI.createScrollView({
        backgroundColor: "white",
        layout: "vertical",
        fullscreen: "true",
        id: "hopOn5"
    });
    $.__views.hopOn5 && $.addTopLevelView($.__views.hopOn5);
    $.__views.__alloyId664 = Alloy.createController("_header", {
        id: "__alloyId664",
        __parentSymbol: $.__views.hopOn5
    });
    $.__views.__alloyId664.setParent($.__views.hopOn5);
    $.__views.__alloyId665 = Ti.UI.createView({
        layout: "composite",
        height: "50",
        backgroundColor: "red",
        id: "__alloyId665"
    });
    $.__views.hopOn5.add($.__views.__alloyId665);
    $.__views.__alloyId666 = Ti.UI.createLabel({
        text: "HOP ON",
        backgroundColor: "transparent",
        color: "white",
        left: "20",
        id: "__alloyId666"
    });
    $.__views.__alloyId665.add($.__views.__alloyId666);
    $.__views.__alloyId667 = Ti.UI.createImageView({
        backgroundColor: "transparent",
        width: "30",
        height: "30",
        right: "10",
        image: "/images/close_icon.png",
        id: "__alloyId667"
    });
    $.__views.__alloyId665.add($.__views.__alloyId667);
    close ? $.__views.__alloyId667.addEventListener("click", close) : __defers["$.__views.__alloyId667!click!close"] = true;
    $.__views.__alloyId668 = Ti.UI.createView({
        layout: "vertical",
        height: "50",
        backgroundColor: "#F2F2F2",
        id: "__alloyId668"
    });
    $.__views.hopOn5.add($.__views.__alloyId668);
    $.__views.__alloyId669 = Ti.UI.createLabel({
        text: "Step 5 of 5",
        backgroundColor: "transparent",
        color: "black",
        left: "20",
        id: "__alloyId669"
    });
    $.__views.__alloyId668.add($.__views.__alloyId669);
    $.__views.__alloyId670 = Ti.UI.createLabel({
        text: "Complete",
        backgroundColor: "transparent",
        color: "red",
        left: "20",
        id: "__alloyId670"
    });
    $.__views.__alloyId668.add($.__views.__alloyId670);
    $.__views.scrollView = Ti.UI.createScrollView({
        id: "scrollView",
        layout: "vertical",
        width: "100%"
    });
    $.__views.hopOn5.add($.__views.scrollView);
    $.__views.__alloyId671 = Ti.UI.createView({
        layout: "horizontal",
        width: "90%",
        height: "100",
        id: "__alloyId671"
    });
    $.__views.scrollView.add($.__views.__alloyId671);
    $.__views.item_title = Ti.UI.createLabel({
        font: {
            fontSize: "15dp"
        },
        text: "HopOn Registration done. We will keep you update, Thank you.",
        id: "item_title",
        textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
        height: "100",
        width: "90%",
        top: "5"
    });
    $.__views.__alloyId671.add($.__views.item_title);
    $.__views.__alloyId672 = Ti.UI.createView({
        height: "50",
        backgroundColor: "red",
        id: "__alloyId672"
    });
    $.__views.hopOn5.add($.__views.__alloyId672);
    download ? $.__views.__alloyId672.addEventListener("click", download) : __defers["$.__views.__alloyId672!click!download"] = true;
    $.__views.__alloyId673 = Ti.UI.createLabel({
        text: "DOWNLOAD TAX INVOICE",
        color: "white",
        id: "__alloyId673"
    });
    $.__views.__alloyId672.add($.__views.__alloyId673);
    exports.destroy = function() {};
    _.extend($, $.__views);
    $.scrollView.height = Ti.Platform.displayCaps.platformHeight - 200;
    console.log("android");
    $.scrollView.height = PixelsToDPUnits(Ti.Platform.displayCaps.platformHeight) - 200;
    __defers["$.__views.__alloyId667!click!close"] && $.__views.__alloyId667.addEventListener("click", close);
    __defers["$.__views.__alloyId672!click!download"] && $.__views.__alloyId672.addEventListener("click", download);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
{
  var internalInstance = EventPluginUtils.getInstanceFromNode(target);

  if (!internalInstance) {
    return;
  }

  if (typeof internalInstance.tag === "number") {
    invariant(
      fiberHostComponent &&
        typeof fiberHostComponent.restoreControlledState === "function",
      "Fiber needs to be injected to handle a fiber target for controlled " +
        "events. This error is likely caused by a bug in React. Please file an issue."
    );
    const props = EventPluginUtils.getFiberCurrentPropsFromNode(
      internalInstance.stateNode
    );
    fiberHostComponent.restoreControlledState(
      internalInstance.stateNode,
      internalInstance.type,
      props
    );
    return;
  }

  invariant(
    typeof internalInstance.restoreControlledState === "function",
    "The internal instance must be a React host component. " +
      "This error is likely caused by a bug in React. Please file an issue."
  );
  internalInstance.restoreControlledState();
}


text:
namespace BoardGames.Data.Common.Models
{
    public interface IOrderable
    {
        int OrderBy { get; set; }
    }
}


text:
import * as XState from 'xstate';

const { Machine } = XState;

const { assign } = XState.actions;

const setSelected = assign({
  selectedStream: (ctx, event) => event.stream_id,
});

const addPeer = assign({
  remoteStreams: (ctx, event) => console.log('🔥  event', event) || [...ctx.remoteStreams, event.stream_id],
});

const removePeer = assign({
  remoteStreams: (ctx, event) => console.log('🔥  event', event)
    || ctx.remoteStreams.filter(id => id !== event.stream_id),
});

const multipleStreamsAvailable = ctx => ctx.remoteStreams.length + ctx.localStreams.length > 1;

const streamSelectMachine = Machine(
  {
    id: 'stream-select',
    initial: 'single',
    context: {
      localStreams: [],
      remoteStreams: [],
      selectedStream: null,
    },
    states: {
      single: {
        on: {
          PEER_JOIN: {
            target: 'singleWithPreview',
            actions: ['addPeer'],
          },
          PEER_LEAVE: {
            actions: 'removePeer',
          },
          DISPLAY_MODE_CHANGE: {
            target: 'multi',
            cond: 'multipleStreamsAvailable',
          },
        },
      },
      singleWithPreview: {
        on: {
          STREAM_SELECT: {
            target: 'single',
            actions: 'setSelected',
          },
          TIMEOUT: {
            target: 'single',
          },
        },
      },
      multi: {
        on: {
          DISPLAY_MODE_CHANGE: {
            target: 'single',
          },
          PEER_JOIN: {
            target: 'multi',
            actions: 'addPeer',
          },
          PEER_LEAVE: {
            target: 'multi',
            actions: 'removePeer',
          },
        },
      },
    },
  },
  {
    actions: { setSelected, addPeer, removePeer },
    guards: { multipleStreamsAvailable },
  },
);

export default streamSelectMachine;


text:
/**
 * Command line node-dcp application
 */
var fs = require('fs'),
	cplParser = require('./parse_cpl');

if (require.main === module) {

	if (process.argv.length !== 3) {
		console.log("Usage: node node-cpl.js <CPL XML file>");
	}
    else {
        var cplStream = cplParser.createStream();
        fs.createReadStream(process.argv[2]).pipe(cplStream);

     	cplStream.on('cpl', function(cpl) {
            console.log(JSON.stringify(cpl));
            console.log('Duration: ' + cpl.duration);
            console.log('Frames: ' + cpl.frames);
     	});
    }
}


text:
'''
This is how to detect fire in an image using CIELAB colorspace using SimpleCV
'''
print __doc__

from SimpleCV import Image

img = Image("fireexample.jpg", sample=True)
labimg = img.toLAB()
lmean = 160
amean = 135
bmean = 180

l, a, b = labimg.splitChannels()

l1 = l.threshold(lmean)
a1 = a.threshold(amean)
b1 = b.threshold(bmean)

threshImg = a1 <= b1
finImg = l1 & a1 & b1 & threshImg
finImgC = img & finImg
finImgC.show()


text:
package org.http4s
package parser

import org.http4s.headers.{`Content-Range`, Range}
import org.http4s.headers.Range.SubRange

class RangeParserSpec extends Http4sSpec {

  "RangeParser" should {
    "parse Range" in {
      val headers = Seq(
        Range(RangeUnit.Bytes, SubRange(0, 500)),
        Range(RangeUnit.Bytes, SubRange(0, 499), SubRange(500, 999), SubRange(1000, 1500)),
        Range(RangeUnit("page"), SubRange(0, 100)),
        Range(10),
        Range(-90)
      )

      forall(headers) { header =>
        HttpHeaderParser.parseHeader(header.toRaw) must be_\/-(header)
      }
    }
  }

  "parse Content-Range" in {
    val headers = Seq(
      `Content-Range`(RangeUnit.Bytes, SubRange(10, None), None),
      `Content-Range`(RangeUnit.Bytes, SubRange(0, 500), Some(500)),
      `Content-Range`(RangeUnit("page"), SubRange(0, 100), Some(100)),
      `Content-Range`(10),
      `Content-Range`(-90),
      `Content-Range`(SubRange(10, 30))
    )

    forall(headers) { header =>
      HttpHeaderParser.parseHeader(header.toRaw) must be_\/-(header)
    }
  }
}


text:
<?php

class PauseCall
{
   // private $file="TestRecord_1.wav";
    private $nexturl="http://192.168.1.195/IVR/end.php";
    private $app="";
    private $result="result_1234";
    private $params='{"Params_Test":"test"}';
    private $display="DEFAULT";
    private $errorFile="";
    private $digitTimeOut="5";
    private $inputTimeOut="10";
    private $milliSeconds="5000";
    private $terminator="*";
    private $strip="*";
    private $digits="9";
    private $eventlog=false;
    private $maxdigits="";

public function SetNextUrl($targetUrl)
        {

            if(!empty( $targetUrl ) )
              $this->nexturl = $targetUrl;

        }

  public function SetApp($targetApp)
        {
            if( !empty( $targetApp ) )

               $this->app = $targetApp;
        }

  public function SetResult($targetResult)
        {

            if( !empty( $targetResult ) )

               $this->result = $targetResult;
        }

 public function SetParams($targetParams)
        {
            if( !empty( $targetParams ) )

               $this->params = $targetParams;
        }

 public function SetDisplay($targetDisplay)
        {

            if( !empty( $targetDisplay ) )

                $this->display = $targetDisplay;

        }

  public function SeteErorfile($targetErrorFile)
        {

            if( !empty( $targetErrorFile ) )

               $this->errorFile = $targetErrorFile;
        }

  public function SetDigitTimeOut($targetDigitTimeOut)
        {

            if( !empty( $targetDigitTimeOut ) )

              $this->digitTimeOut = $targetDigitTimeOut;
        }

  public function SetInputTimeOut($targetInputTimeOut)
        {

            if( !empty( $targetInputTimeOut ) )

               $this->inputTimeOut = $targetInputTimeOut;
        }

  public function SetMilliSeconds($targetMilliSeconds)
        {

            if( !empty( $targetMilliSeconds ) )

               $this->milliSeconds = $targetMilliSeconds;

        }

  public function SetTerminator($targetTerminator)
        {

            if( !empty( $targetTerminator ) )

                $this->terminator = $targetTerminator;
        }

   public function SetStrip($targetStrip)
        {

            if( !empty( $targetStrip ) )

                $this->strip = $targetStrip;

        }

   public function SetDigits($targetDigits)
        {

            if( !empty( $targetDigits ) )

               $this->digits = $targetDigits;
        }
 public function SetEventLog($targetEventLog)
        {

            if( !empty( $targetEventLog ) )

                $this->eventlog = $targetEventLog;
        }

   public function SetMaxDigits($targetMaxDigits)
        {
            if( !empty( $targetMaxDigits ) )

                $this->maxdigits = $targetMaxDigits;
        }

 function GetResult()
  {
    try
    {
        $jsonStart='{';
        $jsonAction='"action": "pause",';
        $jsonNextUrl='"nexturl": "'.$this->nexturl.'",';
        $jsonApp='"app": "'.$this->app.'",';
        $jsonResult='"result": "'.$this->result.'",';
        $jsonParams='"params": '.$this->params.',';
        $jsonDisplay='"display": "'.$this->display.'",';
        $jsonErrorFile='"errorfile": "'.$this->errorFile.'",';
        $jsonDigitTimeOut='"digittimeout": "'.$this->digitTimeOut.'",';
        $jsonInputTimeOut='"inputtimeout": "'.$this->inputTimeOut.'",';
        $jsonMilliSeconds='"milliseconds": "'.$this->milliSeconds.'",';
        $jsonTerminator='"terminator": "'.$this->terminator.'",';
        $jsonStrip='"strip": "'.$this->strip.'",';
        $jsonMaxDigits='"maxdigits": "'.$this->maxdigit.'",';
        $jsonEventLog='"eventlog": "'.$this->eventlog.'",';
        $jsonDigits='"digits": "'.$this->digits.'"';
        $jsonEnd='}';

        return $jsonStart.$jsonAction.$jsonNextUrl.$jsonApp.$jsonResult.$jsonParams.$jsonDisplay.$jsonErrorFile.$jsonDigitTimeOut.$jsonInputTimeOut.$jsonMilliSeconds.$jsonTerminator.$jsonStrip.$jsonEventLog.$jsonDigits.$jsonMaxDigits.$jsonEnd;
    }
    catch(exception $ex)
    {
        return $ex;
    }
  }

}

?>


text:
```typescript
// RECOMMENDED (doesn't work with system.js)
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
// or
import { BsDropdownModule } from 'ngx-bootstrap';

@NgModule({
  imports: [BsDropdownModule.forRoot(),...]
})
export class AppModule(){}
```


text:
{% extends "layout.html" %}

{% block page_title %}
Publish government data
{% endblock %}

{% block proposition_header %}
{% include "includes/propositional_navigation_service.html" %}
{% endblock %}

{% block header_class %}
with-proposition
{% endblock %}

{% block content %}

  {% include "includes/phase_banner_alpha.html" %}

    {% include "includes/side-navigation.html" %}

      <form
          method="post"
          action="{% if query.change == 1 %}check{% else %}link{% endif %}"
          class="form">

          What time period does this link cover?

        <fieldset>
          <legend>

              Time period

            For example, 3 2016
          </legend>

              Month
              <input
                  class="form-control"
                  id="period-month"
                  name="period-month"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  max="12"
                  value="{{ data.newSet.periodMonth }}">

              Year
              <input
                  class="form-control"
                  id="period-year"
                  name="period-year"
                  type="number"
                  pattern="[0-9]*"
                  min="0"
                  value="{{ data.newSet.periodYear }}">

        </fieldset>

          <input type="submit" class="button" value="Continue" />

      </form>

{% endblock %}


text:
<?php

namespace Oro\Bundle\CommentBundle\Tests\Unit\Entity;

use Oro\Bundle\CommentBundle\Entity\Comment;

class CommentTest extends AbstractEntityTestCase
{
    /** @var Comment */
    protected $entity;

    /**
     * {@inheritDoc}
     */
    public function getEntityFQCN()
    {
        return 'Oro\Bundle\CommentBundle\Entity\Comment';
    }

    public function testPrePersist()
    {
        $this->entity->prePersist();

        $this->assertNotNull($this->entity->getCreatedAt());
        $this->assertNotNull($this->entity->getUpdatedAt());
    }

    public function testPreUpdate()
    {
        $this->entity->preUpdate();

        $this->assertNotNull($this->entity->getUpdatedAt());
    }

    /**
     * @return array
     */
    public function getSetDataProvider()
    {
        $owner        = $this->createMock('Oro\Bundle\UserBundle\Entity\User');
        $organization = $this->createMock('Oro\Bundle\OrganizationBundle\Entity\Organization');
        $createdAt    = new \DateTime('now');
        $updatedAt    = new \DateTime('now');

        return [
            'message'      => ['message', 'some test message', 'some test message'],
            'updatedBy'    => ['updatedBy', $owner, $owner],
            'owner'        => ['owner', $owner, $owner],
            'organization' => ['organization', $organization, $organization],
            'createdAt'    => ['createdAt', $createdAt, $createdAt],
            'updatedAt'    => ['updatedAt', $updatedAt, $updatedAt],
        ];
    }
}


text:
package io.github.jrrickard.winterseries.model;

import com.vmware.xenon.common.ServiceDocument;

public class TeamMember extends ServiceDocument {

    private String team;
    private String participant;

    public String getTeam() {
        return team;
    }

    public void setTeam(String team) {
        this.team = team;
    }

    public String getParticipant() {
        return participant;
    }

    public void setParticipant(String participant) {
        this.participant = participant;
    }
}


text:
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.vsked</groupId>
	<artifactId>youtudemo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>youtudemo Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<log4j2.version>2.9.1</log4j2.version>
	</properties>
	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.glassfish.web/jstl-impl -->
		<dependency>
			<groupId>org.glassfish.web</groupId>
			<artifactId>jstl-impl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${log4j2.version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${log4j2.version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.json/json -->
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20171018</version>
		</dependency>
		<!-- not use this youtu jar from documents please run bat
		<dependency>
			<groupId>com.youtu</groupId>
			<artifactId>youtu</artifactId>
			<version>3.2</version>
		</dependency>
		-->
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

	</dependencies>
	<build>
		<finalName>youtudemo</finalName>
	</build>
</project>


text:
require 'curses'
require 'deathhack/map'

module DeathHack
  class Rogue
    include Curses

    attr_accessor :position

    def initialize
      @position = [rand(0..80),rand(3..25)]
    end

    def dead?
      @dead
    end

    def died_to
      @killer
    end

    def die message
      @dead = true
      @killer = message.dup
    end

    def move direction
      new_position = @position.dup
      case direction
      when :left
        new_position[0] -= 1
      when :right
        new_position[0] += 1
      when :up
        new_position[1] -= 1
      when :down
        new_position[1] += 1
      end

      if new_position[0] < 0 || new_position[0] > cols-1 || new_position[1] < 3 || new_position[1] > lines-1
        return
      end

      creature = Map.creature_at? new_position

      if creature
        collide_with creature
      else
        redraw new_position
      end
    end

    def collide_with creature
      Map.clear_message
      setpos 0,0
      addstr creature.message
      die(creature.message) if creature.deadly?
    end

    def redraw new_position
      setpos *@position.reverse
      addstr '.'
      @position = new_position
      setpos *@position.reverse
      addstr '@'
    end
  end
end


text:
/*
  Copyright 2009  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, and distribute this software
  and its documentation for any purpose and without fee is hereby
  granted, provided that the above copyright notice appear in all
  copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Board specific Dataflash commands header for the AT45DB642D as mounted on the STK526.
 *
 *  \note This file should not be included directly. It is automatically included as needed by the dataflash driver
 *        dispatch header located in LUFA/Drivers/Board/Dataflash.h.
 */

/** \ingroup Group_Dataflash_STK526
 *  @defgroup Group_Dataflash_STK526_AT45DB642D AT45DB642D
 *
 *  @{
 */

#ifndef __DATAFLASH_CMDS_H__
#define __DATAFLASH_CMDS_H__

	/* Public Interface - May be used in end-application: */
		/* Macros: */
			#define DF_STATUS_READY                         (1 << 7)
			#define DF_STATUS_COMPMISMATCH                  (1 << 6)
			#define DF_STATUS_SECTORPROTECTION_ON           (1 << 1)
			#define DF_STATUS_BINARYPAGESIZE_ON             (1 << 0)

			#define DF_MANUFACTURER_ATMEL                   0x1F

			#define DF_CMD_GETSTATUS                        0xD7
			#define DF_CMD_POWERDOWN                        0xB9
			#define DF_CMD_WAKEUP                           0xAB

			#define DF_CMD_MAINMEMTOBUFF1                   0x53
			#define DF_CMD_MAINMEMTOBUFF2                   0x55
			#define DF_CMD_MAINMEMTOBUFF1COMP               0x60
			#define DF_CMD_MAINMEMTOBUFF2COMP               0x61
			#define DF_CMD_AUTOREWRITEBUFF1                 0x58
			#define DF_CMD_AUTOREWRITEBUFF2                 0x59

			#define DF_CMD_MAINMEMPAGEREAD                  0xD2
			#define DF_CMD_CONTARRAYREAD_LF                 0x03
			#define DF_CMD_BUFF1READ_LF                     0xD1
			#define DF_CMD_BUFF2READ_LF                     0xD3

			#define DF_CMD_BUFF1WRITE                       0x84
			#define DF_CMD_BUFF2WRITE                       0x87
			#define DF_CMD_BUFF1TOMAINMEMWITHERASE          0x83
			#define DF_CMD_BUFF2TOMAINMEMWITHERASE          0x86
			#define DF_CMD_BUFF1TOMAINMEM                   0x88
			#define DF_CMD_BUFF2TOMAINMEM                   0x89
			#define DF_CMD_MAINMEMPAGETHROUGHBUFF1          0x82
			#define DF_CMD_MAINMEMPAGETHROUGHBUFF2          0x85

			#define DF_CMD_PAGEERASE                        0x81
			#define DF_CMD_BLOCKERASE                       0x50
			#define DF_CMD_SECTORERASE                      0x7C

			#define DF_CMD_CHIPERASE                        ((char[]){0xC7, 0x94, 0x80, 0x9A})
			#define DF_CMD_CHIPERASE_BYTE1                  0xC7
			#define DF_CMD_CHIPERASE_BYTE2                  0x94
			#define DF_CMD_CHIPERASE_BYTE3                  0x80
			#define DF_CMD_CHIPERASE_BYTE4                  0x9A

			#define DF_CMD_SECTORPROTECTIONOFF              ((char[]){0x3D, 0x2A, 0x7F, 0x9A})
			#define DF_CMD_SECTORPROTECTIONOFF_BYTE1        0x3D
			#define DF_CMD_SECTORPROTECTIONOFF_BYTE2        0x2A
			#define DF_CMD_SECTORPROTECTIONOFF_BYTE3        0x7F
			#define DF_CMD_SECTORPROTECTIONOFF_BYTE4        0x9A

			#define DF_CMD_READMANUFACTURERDEVICEINFO       0x9F

#endif

/** @} */


text:
source ./steps-local-config.sh

$CHERITOOLS/cherictl resume
gnome-terminal --geometry 100x40 --command="./step3-terminal-helper.sh" &


text:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/timer.h>
#include <linux/rtnetlink.h>

#include <net/mac80211.h>
#include "ieee80211_i.h"
#include "driver-ops.h"
#include "rate.h"
#include "sta_info.h"
#include "debugfs_sta.h"
#include "mesh.h"
#include "wme.h"

/**
 * DOC: STA information lifetime rules
 *
 * STA info structures (&struct sta_info) are managed in a hash table
 * for faster lookup and a list for iteration. They are managed using
 * RCU, i.e. access to the list and hash table is protected by RCU.
 *
 * Upon allocating a STA info structure with sta_info_alloc(), the caller
 * owns that structure. It must then insert it into the hash table using
 * either sta_info_insert() or sta_info_insert_rcu(); only in the latter
 * case (which acquires an rcu read section but must not be called from
 * within one) will the pointer still be valid after the call. Note that
 * the caller may not do much with the STA info before inserting it, in
 * particular, it may not start any mesh peer link management or add
 * encryption keys.
 *
 * When the insertion fails (sta_info_insert()) returns non-zero), the
 * structure will have been freed by sta_info_insert()!
 *
 * Station entries are added by mac80211 when you establish a link with a
 * peer. This means different things for the different type of interfaces
 * we support. For a regular station this mean we add the AP sta when we
 * receive an association response from the AP. For IBSS this occurs when
 * get to know about a peer on the same IBSS. For WDS we add the sta for
 * the peer immediately upon device open. When using AP mode we add stations
 * for each respective station upon request from userspace through nl80211.
 *
 * In order to remove a STA info structure, various sta_info_destroy_*()
 * calls are available.
 *
 * There is no concept of ownership on a STA entry, each structure is
 * owned by the global hash table/list until it is removed. All users of
 * the structure need to be RCU protected so that the structure won't be
 * freed before they are done using it.
 */

/* Caller must hold local->sta_lock */
static int sta_info_hash_del(struct ieee80211_local *local,
			     struct sta_info *sta)
{
	struct sta_info *s;

	s = rcu_dereference_protected(local->sta_hash[STA_HASH(sta->sta.addr)],
				      lockdep_is_held(&local->sta_lock));
	if (!s)
		return -ENOENT;
	if (s == sta) {
		RCU_INIT_POINTER(local->sta_hash[STA_HASH(sta->sta.addr)],
				   s->hnext);
		return 0;
	}

	while (rcu_access_pointer(s->hnext) &&
	       rcu_access_pointer(s->hnext) != sta)
		s = rcu_dereference_protected(s->hnext,
					lockdep_is_held(&local->sta_lock));
	if (rcu_access_pointer(s->hnext)) {
		RCU_INIT_POINTER(s->hnext, sta->hnext);
		return 0;
	}

	return -ENOENT;
}

/* protected by RCU */
struct sta_info *sta_info_get(struct ieee80211_sub_if_data *sdata,
			      const u8 *addr)
{
	struct ieee80211_local *local = sdata->local;
	struct sta_info *sta;

	sta = rcu_dereference_check(local->sta_hash[STA_HASH(addr)],
				    lockdep_is_held(&local->sta_lock) ||
				    lockdep_is_held(&local->sta_mtx));
	while (sta) {
		if (sta->sdata == sdata && !sta->dummy &&
		    memcmp(sta->sta.addr, addr, ETH_ALEN) == 0)
			break;
		sta = rcu_dereference_check(sta->hnext,
					    lockdep_is_held(&local->sta_lock) ||
					    lockdep_is_held(&local->sta_mtx));
	}
	return sta;
}

/* get a station info entry even if it is a dummy station*/
struct sta_info *sta_info_get_rx(struct ieee80211_sub_if_data *sdata,
			      const u8 *addr)
{
	struct ieee80211_local *local = sdata->local;
	struct sta_info *sta;

	sta = rcu_dereference_check(local->sta_hash[STA_HASH(addr)],
				    lockdep_is_held(&local->sta_lock) ||
				    lockdep_is_held(&local->sta_mtx));
	while (sta) {
		if (sta->sdata == sdata &&
		    memcmp(sta->sta.addr, addr, ETH_ALEN) == 0)
			break;
		sta = rcu_dereference_check(sta->hnext,
					    lockdep_is_held(&local->sta_lock) ||
					    lockdep_is_held(&local->sta_mtx));
	}
	return sta;
}

/*
 * Get sta info either from the specified interface
 * or from one of its vlans
 */
struct sta_info *sta_info_get_bss(struct ieee80211_sub_if_data *sdata,
				  const u8 *addr)
{
	struct ieee80211_local *local = sdata->local;
	struct sta_info *sta;

	sta = rcu_dereference_check(local->sta_hash[STA_HASH(addr)],
				    lockdep_is_held(&local->sta_lock) ||
				    lockdep_is_held(&local->sta_mtx));
	while (sta) {
		if ((sta->sdata == sdata ||
		     (sta->sdata->bss && sta->sdata->bss == sdata->bss)) &&
		    !sta->dummy &&
		    memcmp(sta->sta.addr, addr, ETH_ALEN) == 0)
			break;
		sta = rcu_dereference_check(sta->hnext,
					    lockdep_is_held(&local->sta_lock) ||
					    lockdep_is_held(&local->sta_mtx));
	}
	return sta;
}

/*
 * Get sta info either from the specified interface
 * or from one of its vlans (including dummy stations)
 */
struct sta_info *sta_info_get_bss_rx(struct ieee80211_sub_if_data *sdata,
				  const u8 *addr)
{
	struct ieee80211_local *local = sdata->local;
	struct sta_info *sta;

	sta = rcu_dereference_check(local->sta_hash[STA_HASH(addr)],
				    lockdep_is_held(&local->sta_lock) ||
				    lockdep_is_held(&local->sta_mtx));
	while (sta) {
		if ((sta->sdata == sdata ||
		     (sta->sdata->bss && sta->sdata->bss == sdata->bss)) &&
		    memcmp(sta->sta.addr, addr, ETH_ALEN) == 0)
			break;
		sta = rcu_dereference_check(sta->hnext,
					    lockdep_is_held(&local->sta_lock) ||
					    lockdep_is_held(&local->sta_mtx));
	}
	return sta;
}

struct sta_info *sta_info_get_by_idx(struct ieee80211_sub_if_data *sdata,
				     int idx)
{
	struct ieee80211_local *local = sdata->local;
	struct sta_info *sta;
	int i = 0;

	list_for_each_entry_rcu(sta, &local->sta_list, list) {
		if (sdata != sta->sdata)
			continue;
		if (i < idx) {
			++i;
			continue;
		}
		return sta;
	}

	return NULL;
}

/**
 * __sta_info_free - internal STA free helper
 *
 * @local: pointer to the global information
 * @sta: STA info to free
 *
 * This function must undo everything done by sta_info_alloc()
 * that may happen before sta_info_insert().
 */
static void __sta_info_free(struct ieee80211_local *local,
			    struct sta_info *sta)
{
	if (sta->rate_ctrl) {
		rate_control_free_sta(sta);
		rate_control_put(sta->rate_ctrl);
	}

#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
	wiphy_debug(local->hw.wiphy, "Destroyed STA %pM\n", sta->sta.addr);
#endif /* CONFIG_MAC80211_VERBOSE_DEBUG */

	kfree(sta);
}

/* Caller must hold local->sta_lock */
static void sta_info_hash_add(struct ieee80211_local *local,
			      struct sta_info *sta)
{
	sta->hnext = local->sta_hash[STA_HASH(sta->sta.addr)];
	RCU_INIT_POINTER(local->sta_hash[STA_HASH(sta->sta.addr)], sta);
}

static void sta_unblock(struct work_struct *wk)
{
	struct sta_info *sta;

	sta = container_of(wk, struct sta_info, drv_unblock_wk);

	if (sta->dead)
		return;

	if (!test_sta_flag(sta, WLAN_STA_PS_STA))
		ieee80211_sta_ps_deliver_wakeup(sta);
	else if (test_and_clear_sta_flag(sta, WLAN_STA_PSPOLL)) {
		clear_sta_flag(sta, WLAN_STA_PS_DRIVER);

		local_bh_disable();
		ieee80211_sta_ps_deliver_poll_response(sta);
		local_bh_enable();
	} else if (test_and_clear_sta_flag(sta, WLAN_STA_UAPSD)) {
		clear_sta_flag(sta, WLAN_STA_PS_DRIVER);

		local_bh_disable();
		ieee80211_sta_ps_deliver_uapsd(sta);
		local_bh_enable();
	} else
		clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
}

static int sta_prepare_rate_control(struct ieee80211_local *local,
				    struct sta_info *sta, gfp_t gfp)
{
	if (local->hw.flags & IEEE80211_HW_HAS_RATE_CONTROL)
		return 0;

	sta->rate_ctrl = rate_control_get(local->rate_ctrl);
	sta->rate_ctrl_priv = rate_control_alloc_sta(sta->rate_ctrl,
						     &sta->sta, gfp);
	if (!sta->rate_ctrl_priv) {
		rate_control_put(sta->rate_ctrl);
		return -ENOMEM;
	}

	return 0;
}

struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata,
				u8 *addr, gfp_t gfp)
{
	struct ieee80211_local *local = sdata->local;
	struct sta_info *sta;
	struct timespec uptime;
	int i;

	sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp);
	if (!sta)
		return NULL;

	spin_lock_init(&sta->lock);
	INIT_WORK(&sta->drv_unblock_wk, sta_unblock);
	INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work);
	mutex_init(&sta->ampdu_mlme.mtx);

	memcpy(sta->sta.addr, addr, ETH_ALEN);
	sta->local = local;
	sta->sdata = sdata;
	sta->last_rx = jiffies;

	do_posix_clock_monotonic_gettime(&uptime);
	sta->last_connected = uptime.tv_sec;
	ewma_init(&sta->avg_signal, 1024, 8);

	if (sta_prepare_rate_control(local, sta, gfp)) {
		kfree(sta);
		return NULL;
	}

	for (i = 0; i < STA_TID_NUM; i++) {
		/*
		 * timer_to_tid must be initialized with identity mapping
		 * to enable session_timer's data differentiation. See
		 * sta_rx_agg_session_timer_expired for usage.
		 */
		sta->timer_to_tid[i] = i;
	}
	for (i = 0; i < IEEE80211_NUM_ACS; i++) {
		skb_queue_head_init(&sta->ps_tx_buf[i]);
		skb_queue_head_init(&sta->tx_filtered[i]);
	}

	for (i = 0; i < NUM_RX_DATA_QUEUES; i++)
		sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX);

#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
	wiphy_debug(local->hw.wiphy, "Allocated STA %pM\n", sta->sta.addr);
#endif /* CONFIG_MAC80211_VERBOSE_DEBUG */

#ifdef CONFIG_MAC80211_MESH
	sta->plink_state = NL80211_PLINK_LISTEN;
	init_timer(&sta->plink_timer);
#endif

	return sta;
}

static int sta_info_finish_insert(struct sta_info *sta,
				bool async, bool dummy_reinsert)
{
	struct ieee80211_local *local = sta->local;
	struct ieee80211_sub_if_data *sdata = sta->sdata;
	struct station_info sinfo;
	unsigned long flags;
	int err = 0;

	lockdep_assert_held(&local->sta_mtx);

	if (!sta->dummy || dummy_reinsert) {
		/* notify driver */
		if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
			sdata = container_of(sdata->bss,
					     struct ieee80211_sub_if_data,
					     u.ap);
		err = drv_sta_add(local, sdata, &sta->sta);
		if (err) {
			if (!async)
				return err;
			printk(KERN_DEBUG "%s: failed to add IBSS STA %pM to "
					  "driver (%d) - keeping it anyway.\n",
			       sdata->name, sta->sta.addr, err);
		} else {
			sta->uploaded = true;
#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
			if (async)
				wiphy_debug(local->hw.wiphy,
					    "Finished adding IBSS STA %pM\n",
					    sta->sta.addr);
#endif
		}

		sdata = sta->sdata;
	}

	if (!dummy_reinsert) {
		if (!async) {
			local->num_sta++;
			local->sta_generation++;
			smp_mb();

			/* make the station visible */
			spin_lock_irqsave(&local->sta_lock, flags);
			sta_info_hash_add(local, sta);
			spin_unlock_irqrestore(&local->sta_lock, flags);
		}

		list_add(&sta->list, &local->sta_list);
	} else {
		sta->dummy = false;
	}

	if (!sta->dummy) {
		ieee80211_sta_debugfs_add(sta);
		rate_control_add_sta_debugfs(sta);

		memset(&sinfo, 0, sizeof(sinfo));
		sinfo.filled = 0;
		sinfo.generation = local->sta_generation;
		cfg80211_new_sta(sdata->dev, sta->sta.addr, &sinfo, GFP_KERNEL);
	}

	return 0;
}

static void sta_info_finish_pending(struct ieee80211_local *local)
{
	struct sta_info *sta;
	unsigned long flags;

	spin_lock_irqsave(&local->sta_lock, flags);
	while (!list_empty(&local->sta_pending_list)) {
		sta = list_first_entry(&local->sta_pending_list,
				       struct sta_info, list);
		list_del(&sta->list);
		spin_unlock_irqrestore(&local->sta_lock, flags);

		sta_info_finish_insert(sta, true, false);

		spin_lock_irqsave(&local->sta_lock, flags);
	}
	spin_unlock_irqrestore(&local->sta_lock, flags);
}

static void sta_info_finish_work(struct work_struct *work)
{
	struct ieee80211_local *local =
		container_of(work, struct ieee80211_local, sta_finish_work);

	mutex_lock(&local->sta_mtx);
	sta_info_finish_pending(local);
	mutex_unlock(&local->sta_mtx);
}

static int sta_info_insert_check(struct sta_info *sta)
{
	struct ieee80211_sub_if_data *sdata = sta->sdata;

	/*
	 * Can't be a WARN_ON because it can be triggered through a race:
	 * something inserts a STA (on one CPU) without holding the RTNL
	 * and another CPU turns off the net device.
	 */
	if (unlikely(!ieee80211_sdata_running(sdata)))
		return -ENETDOWN;

	if (WARN_ON(compare_ether_addr(sta->sta.addr, sdata->vif.addr) == 0 ||
		    is_multicast_ether_addr(sta->sta.addr)))
		return -EINVAL;

	return 0;
}

static int sta_info_insert_ibss(struct sta_info *sta) __acquires(RCU)
{
	struct ieee80211_local *local = sta->local;
	struct ieee80211_sub_if_data *sdata = sta->sdata;
	unsigned long flags;

	spin_lock_irqsave(&local->sta_lock, flags);
	/* check if STA exists already */
	if (sta_info_get_bss_rx(sdata, sta->sta.addr)) {
		spin_unlock_irqrestore(&local->sta_lock, flags);
		rcu_read_lock();
		return -EEXIST;
	}

	local->num_sta++;
	local->sta_generation++;
	smp_mb();
	sta_info_hash_add(local, sta);

	list_add_tail(&sta->list, &local->sta_pending_list);

	rcu_read_lock();
	spin_unlock_irqrestore(&local->sta_lock, flags);

#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
	wiphy_debug(local->hw.wiphy, "Added IBSS STA %pM\n",
			sta->sta.addr);
#endif /* CONFIG_MAC80211_VERBOSE_DEBUG */

	ieee80211_queue_work(&local->hw, &local->sta_finish_work);

	return 0;
}

/*
 * should be called with sta_mtx locked
 * this function replaces the mutex lock
 * with a RCU lock
 */
static int sta_info_insert_non_ibss(struct sta_info *sta) __acquires(RCU)
{
	struct ieee80211_local *local = sta->local;
	struct ieee80211_sub_if_data *sdata = sta->sdata;
	unsigned long flags;
	struct sta_info *exist_sta;
	bool dummy_reinsert = false;
	int err = 0;

	lockdep_assert_held(&local->sta_mtx);

	/*
	 * On first glance, this will look racy, because the code
	 * in this function, which inserts a station with sleeping,
	 * unlocks the sta_lock between checking existence in the
	 * hash table and inserting into it.
	 *
	 * However, it is not racy against itself because it keeps
	 * the mutex locked.
	 */

	spin_lock_irqsave(&local->sta_lock, flags);
	/*
	 * check if STA exists already.
	 * only accept a scenario of a second call to sta_info_insert_non_ibss
	 * with a dummy station entry that was inserted earlier
	 * in that case - assume that the dummy station flag should
	 * be removed.
	 */
	exist_sta = sta_info_get_bss_rx(sdata, sta->sta.addr);
	if (exist_sta) {
		if (exist_sta == sta && sta->dummy) {
			dummy_reinsert = true;
		} else {
			spin_unlock_irqrestore(&local->sta_lock, flags);
			mutex_unlock(&local->sta_mtx);
			rcu_read_lock();
			return -EEXIST;
		}
	}

	spin_unlock_irqrestore(&local->sta_lock, flags);

	err = sta_info_finish_insert(sta, false, dummy_reinsert);
	if (err) {
		mutex_unlock(&local->sta_mtx);
		rcu_read_lock();
		return err;
	}

#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
	wiphy_debug(local->hw.wiphy, "Inserted %sSTA %pM\n",
			sta->dummy ? "dummy " : "", sta->sta.addr);
#endif /* CONFIG_MAC80211_VERBOSE_DEBUG */

	/* move reference to rcu-protected */
	rcu_read_lock();
	mutex_unlock(&local->sta_mtx);

	if (ieee80211_vif_is_mesh(&sdata->vif))
		mesh_accept_plinks_update(sdata);

	return 0;
}

int sta_info_insert_rcu(struct sta_info *sta) __acquires(RCU)
{
	struct ieee80211_local *local = sta->local;
	struct ieee80211_sub_if_data *sdata = sta->sdata;
	int err = 0;

	err = sta_info_insert_check(sta);
	if (err) {
		rcu_read_lock();
		goto out_free;
	}

	/*
	 * In ad-hoc mode, we sometimes need to insert stations
	 * from tasklet context from the RX path. To avoid races,
	 * always do so in that case -- see the comment below.
	 */
	if (sdata->vif.type == NL80211_IFTYPE_ADHOC) {
		err = sta_info_insert_ibss(sta);
		if (err)
			goto out_free;

		return 0;
	}

	/*
	 * It might seem that the function called below is in race against
	 * the function call above that atomically inserts the station... That,
	 * however, is not true because the above code can only
	 * be invoked for IBSS interfaces, and the below code will
	 * not be -- and the two do not race against each other as
	 * the hash table also keys off the interface.
	 */

	might_sleep();

	mutex_lock(&local->sta_mtx);

	err = sta_info_insert_non_ibss(sta);
	if (err)
		goto out_free;

	return 0;
 out_free:
	BUG_ON(!err);
	__sta_info_free(local, sta);
	return err;
}

int sta_info_insert(struct sta_info *sta)
{
	int err = sta_info_insert_rcu(sta);

	rcu_read_unlock();

	return err;
}

/* Caller must hold sta->local->sta_mtx */
int sta_info_reinsert(struct sta_info *sta)
{
	struct ieee80211_local *local = sta->local;
	int err = 0;

	err = sta_info_insert_check(sta);
	if (err) {
		mutex_unlock(&local->sta_mtx);
		return err;
	}

	might_sleep();

	err = sta_info_insert_non_ibss(sta);
	rcu_read_unlock();
	return err;
}

static inline void __bss_tim_set(struct ieee80211_if_ap *bss, u16 aid)
{
	/*
	 * This format has been mandated by the IEEE specifications,
	 * so this line may not be changed to use the __set_bit() format.
	 */
	bss->tim[aid / 8] |= (1 << (aid % 8));
}

static inline void __bss_tim_clear(struct ieee80211_if_ap *bss, u16 aid)
{
	/*
	 * This format has been mandated by the IEEE specifications,
	 * so this line may not be changed to use the __clear_bit() format.
	 */
	bss->tim[aid / 8] &= ~(1 << (aid % 8));
}

static unsigned long ieee80211_tids_for_ac(int ac)
{
	/* If we ever support TIDs > 7, this obviously needs to be adjusted */
	switch (ac) {
	case IEEE80211_AC_VO:
		return BIT(6) | BIT(7);
	case IEEE80211_AC_VI:
		return BIT(4) | BIT(5);
	case IEEE80211_AC_BE:
		return BIT(0) | BIT(3);
	case IEEE80211_AC_BK:
		return BIT(1) | BIT(2);
	default:
		WARN_ON(1);
		return 0;
	}
}

void sta_info_recalc_tim(struct sta_info *sta)
{
	struct ieee80211_local *local = sta->local;
	struct ieee80211_if_ap *bss = sta->sdata->bss;
	unsigned long flags;
	bool indicate_tim = false;
	u8 ignore_for_tim = sta->sta.uapsd_queues;
	int ac;

	if (WARN_ON_ONCE(!sta->sdata->bss))
		return;

	/* No need to do anything if the driver does all */
	if (local->hw.flags & IEEE80211_HW_AP_LINK_PS)
		return;

	if (sta->dead)
		goto done;

	/*
	 * If all ACs are delivery-enabled then we should build
	 * the TIM bit for all ACs anyway; if only some are then
	 * we ignore those and build the TIM bit using only the
	 * non-enabled ones.
	 */
	if (ignore_for_tim == BIT(IEEE80211_NUM_ACS) - 1)
		ignore_for_tim = 0;

	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
		unsigned long tids;

		if (ignore_for_tim & BIT(ac))
			continue;

		indicate_tim |= !skb_queue_empty(&sta->tx_filtered[ac]) ||
				!skb_queue_empty(&sta->ps_tx_buf[ac]);
		if (indicate_tim)
			break;

		tids = ieee80211_tids_for_ac(ac);

		indicate_tim |=
			sta->driver_buffered_tids & tids;
	}

 done:
	spin_lock_irqsave(&local->sta_lock, flags);

	if (indicate_tim)
		__bss_tim_set(bss, sta->sta.aid);
	else
		__bss_tim_clear(bss, sta->sta.aid);

	if (local->ops->set_tim) {
		local->tim_in_locked_section = true;
		drv_set_tim(local, &sta->sta, indicate_tim);
		local->tim_in_locked_section = false;
	}

	spin_unlock_irqrestore(&local->sta_lock, flags);
}

static bool sta_info_buffer_expired(struct sta_info *sta, struct sk_buff *skb)
{
	struct ieee80211_tx_info *info;
	int timeout;

	if (!skb)
		return false;

	info = IEEE80211_SKB_CB(skb);

	/* Timeout: (2 * listen_interval * beacon_int * 1024 / 1000000) sec */
	timeout = (sta->listen_interval *
		   sta->sdata->vif.bss_conf.beacon_int *
		   32 / 15625) * HZ;
	if (timeout < STA_TX_BUFFER_EXPIRE)
		timeout = STA_TX_BUFFER_EXPIRE;
	return time_after(jiffies, info->control.jiffies + timeout);
}

static bool sta_info_cleanup_expire_buffered_ac(struct ieee80211_local *local,
						struct sta_info *sta, int ac)
{
	unsigned long flags;
	struct sk_buff *skb;

	/*
	 * First check for frames that should expire on the filtered
	 * queue. Frames here were rejected by the driver and are on
	 * a separate queue to avoid reordering with normal PS-buffered
	 * frames. They also aren't accounted for right now in the
	 * total_ps_buffered counter.
	 */
	for (;;) {
		spin_lock_irqsave(&sta->tx_filtered[ac].lock, flags);
		skb = skb_peek(&sta->tx_filtered[ac]);
		if (sta_info_buffer_expired(sta, skb))
			skb = __skb_dequeue(&sta->tx_filtered[ac]);
		else
			skb = NULL;
		spin_unlock_irqrestore(&sta->tx_filtered[ac].lock, flags);

		/*
		 * Frames are queued in order, so if this one
		 * hasn't expired yet we can stop testing. If
		 * we actually reached the end of the queue we
		 * also need to stop, of course.
		 */
		if (!skb)
			break;
		dev_kfree_skb(skb);
	}

	/*
	 * Now also check the normal PS-buffered queue, this will
	 * only find something if the filtered queue was emptied
	 * since the filtered frames are all before the normal PS
	 * buffered frames.
	 */
	for (;;) {
		spin_lock_irqsave(&sta->ps_tx_buf[ac].lock, flags);
		skb = skb_peek(&sta->ps_tx_buf[ac]);
		if (sta_info_buffer_expired(sta, skb))
			skb = __skb_dequeue(&sta->ps_tx_buf[ac]);
		else
			skb = NULL;
		spin_unlock_irqrestore(&sta->ps_tx_buf[ac].lock, flags);

		/*
		 * frames are queued in order, so if this one
		 * hasn't expired yet (or we reached the end of
		 * the queue) we can stop testing
		 */
		if (!skb)
			break;

		local->total_ps_buffered--;
#ifdef CONFIG_MAC80211_VERBOSE_PS_DEBUG
		printk(KERN_DEBUG "Buffered frame expired (STA %pM)\n",
		       sta->sta.addr);
#endif
		dev_kfree_skb(skb);
	}

	/*
	 * Finally, recalculate the TIM bit for this station -- it might
	 * now be clear because the station was too slow to retrieve its
	 * frames.
	 */
	sta_info_recalc_tim(sta);

	/*
	 * Return whether there are any frames still buffered, this is
	 * used to check whether the cleanup timer still needs to run,
	 * if there are no frames we don't need to rearm the timer.
	 */
	return !(skb_queue_empty(&sta->ps_tx_buf[ac]) &&
		 skb_queue_empty(&sta->tx_filtered[ac]));
}

static bool sta_info_cleanup_expire_buffered(struct ieee80211_local *local,
					     struct sta_info *sta)
{
	bool have_buffered = false;
	int ac;

	/* This is only necessary for stations on BSS interfaces */
	if (!sta->sdata->bss)
		return false;

	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
		have_buffered |=
			sta_info_cleanup_expire_buffered_ac(local, sta, ac);

	return have_buffered;
}

static int __must_check __sta_info_destroy(struct sta_info *sta)
{
	struct ieee80211_local *local;
	struct ieee80211_sub_if_data *sdata;
	unsigned long flags;
	int ret, i, ac;

	might_sleep();

	if (!sta)
		return -ENOENT;

	local = sta->local;
	sdata = sta->sdata;

	/*
	 * Before removing the station from the driver and
	 * rate control, it might still start new aggregation
	 * sessions -- block that to make sure the tear-down
	 * will be sufficient.
	 */
	set_sta_flag(sta, WLAN_STA_BLOCK_BA);
	ieee80211_sta_tear_down_BA_sessions(sta, true);

	spin_lock_irqsave(&local->sta_lock, flags);
	ret = sta_info_hash_del(local, sta);
	/* this might still be the pending list ... which is fine */
	if (!ret)
		list_del(&sta->list);
	spin_unlock_irqrestore(&local->sta_lock, flags);
	if (ret)
		return ret;

	mutex_lock(&local->key_mtx);
	for (i = 0; i < NUM_DEFAULT_KEYS; i++)
		__ieee80211_key_free(key_mtx_dereference(local, sta->gtk[i]));
	if (sta->ptk)
		__ieee80211_key_free(key_mtx_dereference(local, sta->ptk));
	mutex_unlock(&local->key_mtx);

	sta->dead = true;

	if (test_sta_flag(sta, WLAN_STA_PS_STA) ||
	    test_sta_flag(sta, WLAN_STA_PS_DRIVER)) {
		BUG_ON(!sdata->bss);

		clear_sta_flag(sta, WLAN_STA_PS_STA);
		clear_sta_flag(sta, WLAN_STA_PS_DRIVER);

		atomic_dec(&sdata->bss->num_sta_ps);
		sta_info_recalc_tim(sta);
	}

	local->num_sta--;
	local->sta_generation++;

	if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
		RCU_INIT_POINTER(sdata->u.vlan.sta, NULL);

	if (sta->uploaded) {
		if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
			sdata = container_of(sdata->bss,
					     struct ieee80211_sub_if_data,
					     u.ap);
		drv_sta_remove(local, sdata, &sta->sta);
		sdata = sta->sdata;
	}

	/*
	 * At this point, after we wait for an RCU grace period,
	 * neither mac80211 nor the driver can reference this
	 * sta struct any more except by still existing timers
	 * associated with this station that we clean up below.
	 */
	synchronize_rcu();

	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
		local->total_ps_buffered -= skb_queue_len(&sta->ps_tx_buf[ac]);
		__skb_queue_purge(&sta->ps_tx_buf[ac]);
		__skb_queue_purge(&sta->tx_filtered[ac]);
	}

#ifdef CONFIG_MAC80211_MESH
	if (ieee80211_vif_is_mesh(&sdata->vif))
		mesh_accept_plinks_update(sdata);
#endif

#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
	wiphy_debug(local->hw.wiphy, "Removed STA %pM\n", sta->sta.addr);
#endif /* CONFIG_MAC80211_VERBOSE_DEBUG */
	cancel_work_sync(&sta->drv_unblock_wk);

	cfg80211_del_sta(sdata->dev, sta->sta.addr, GFP_KERNEL);

	rate_control_remove_sta_debugfs(sta);
	ieee80211_sta_debugfs_remove(sta);

#ifdef CONFIG_MAC80211_MESH
	if (ieee80211_vif_is_mesh(&sta->sdata->vif)) {
		mesh_plink_deactivate(sta);
		del_timer_sync(&sta->plink_timer);
	}
#endif

	__sta_info_free(local, sta);

	return 0;
}

int sta_info_destroy_addr(struct ieee80211_sub_if_data *sdata, const u8 *addr)
{
	struct sta_info *sta;
	int ret;

	mutex_lock(&sdata->local->sta_mtx);
	sta = sta_info_get_rx(sdata, addr);
	ret = __sta_info_destroy(sta);
	mutex_unlock(&sdata->local->sta_mtx);

	return ret;
}

int sta_info_destroy_addr_bss(struct ieee80211_sub_if_data *sdata,
			      const u8 *addr)
{
	struct sta_info *sta;
	int ret;

	mutex_lock(&sdata->local->sta_mtx);
	sta = sta_info_get_bss_rx(sdata, addr);
	ret = __sta_info_destroy(sta);
	mutex_unlock(&sdata->local->sta_mtx);

	return ret;
}

static void sta_info_cleanup(unsigned long data)
{
	struct ieee80211_local *local = (struct ieee80211_local *) data;
	struct sta_info *sta;
	bool timer_needed = false;

	rcu_read_lock();
	list_for_each_entry_rcu(sta, &local->sta_list, list)
		if (sta_info_cleanup_expire_buffered(local, sta))
			timer_needed = true;
	rcu_read_unlock();

	if (local->quiescing)
		return;

	if (!timer_needed)
		return;

	mod_timer(&local->sta_cleanup,
		  round_jiffies(jiffies + STA_INFO_CLEANUP_INTERVAL));
}

void sta_info_init(struct ieee80211_local *local)
{
	spin_lock_init(&local->sta_lock);
	mutex_init(&local->sta_mtx);
	INIT_LIST_HEAD(&local->sta_list);
	INIT_LIST_HEAD(&local->sta_pending_list);
	INIT_WORK(&local->sta_finish_work, sta_info_finish_work);

	setup_timer(&local->sta_cleanup, sta_info_cleanup,
		    (unsigned long)local);
}

void sta_info_stop(struct ieee80211_local *local)
{
	del_timer(&local->sta_cleanup);
	sta_info_flush(local, NULL);
}

/**
 * sta_info_flush - flush matching STA entries from the STA table
 *
 * Returns the number of removed STA entries.
 *
 * @local: local interface data
 * @sdata: matching rule for the net device (sta->dev) or %NULL to match all STAs
 */
int sta_info_flush(struct ieee80211_local *local,
		   struct ieee80211_sub_if_data *sdata)
{
	struct sta_info *sta, *tmp;
	int ret = 0;

	might_sleep();

	mutex_lock(&local->sta_mtx);

	sta_info_finish_pending(local);

	list_for_each_entry_safe(sta, tmp, &local->sta_list, list) {
		if (!sdata || sdata == sta->sdata)
			WARN_ON(__sta_info_destroy(sta));
	}
	mutex_unlock(&local->sta_mtx);

	return ret;
}

void ieee80211_sta_expire(struct ieee80211_sub_if_data *sdata,
			  unsigned long exp_time)
{
	struct ieee80211_local *local = sdata->local;
	struct sta_info *sta, *tmp;

	mutex_lock(&local->sta_mtx);
	list_for_each_entry_safe(sta, tmp, &local->sta_list, list)
		if (time_after(jiffies, sta->last_rx + exp_time)) {
#ifdef CONFIG_MAC80211_IBSS_DEBUG
			printk(KERN_DEBUG "%s: expiring inactive STA %pM\n",
			       sdata->name, sta->sta.addr);
#endif
			WARN_ON(__sta_info_destroy(sta));
		}
	mutex_unlock(&local->sta_mtx);
}

struct ieee80211_sta *ieee80211_find_sta_by_ifaddr(struct ieee80211_hw *hw,
					       const u8 *addr,
					       const u8 *localaddr)
{
	struct sta_info *sta, *nxt;

	/*
	 * Just return a random station if localaddr is NULL
	 * ... first in list.
	 */
	for_each_sta_info(hw_to_local(hw), addr, sta, nxt) {
		if (localaddr &&
		    compare_ether_addr(sta->sdata->vif.addr, localaddr) != 0)
			continue;
		if (!sta->uploaded)
			return NULL;
		return &sta->sta;
	}

	return NULL;
}
EXPORT_SYMBOL_GPL(ieee80211_find_sta_by_ifaddr);

struct ieee80211_sta *ieee80211_find_sta(struct ieee80211_vif *vif,
					 const u8 *addr)
{
	struct sta_info *sta;

	if (!vif)
		return NULL;

	sta = sta_info_get_bss(vif_to_sdata(vif), addr);
	if (!sta)
		return NULL;

	if (!sta->uploaded)
		return NULL;

	return &sta->sta;
}
EXPORT_SYMBOL(ieee80211_find_sta);

static void clear_sta_ps_flags(void *_sta)
{
	struct sta_info *sta = _sta;

	clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
	clear_sta_flag(sta, WLAN_STA_PS_STA);
}

/* powersave support code */
void ieee80211_sta_ps_deliver_wakeup(struct sta_info *sta)
{
	struct ieee80211_sub_if_data *sdata = sta->sdata;
	struct ieee80211_local *local = sdata->local;
	struct sk_buff_head pending;
	int filtered = 0, buffered = 0, ac;

	clear_sta_flag(sta, WLAN_STA_SP);

	BUILD_BUG_ON(BITS_TO_LONGS(STA_TID_NUM) > 1);
	sta->driver_buffered_tids = 0;

	if (!(local->hw.flags & IEEE80211_HW_AP_LINK_PS))
		drv_sta_notify(local, sdata, STA_NOTIFY_AWAKE, &sta->sta);

	skb_queue_head_init(&pending);

	/* Send all buffered frames to the station */
	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
		int count = skb_queue_len(&pending), tmp;

		skb_queue_splice_tail_init(&sta->tx_filtered[ac], &pending);
		tmp = skb_queue_len(&pending);
		filtered += tmp - count;
		count = tmp;

		skb_queue_splice_tail_init(&sta->ps_tx_buf[ac], &pending);
		tmp = skb_queue_len(&pending);
		buffered += tmp - count;
	}

	ieee80211_add_pending_skbs_fn(local, &pending, clear_sta_ps_flags, sta);

	local->total_ps_buffered -= buffered;

	sta_info_recalc_tim(sta);

#ifdef CONFIG_MAC80211_VERBOSE_PS_DEBUG
	printk(KERN_DEBUG "%s: STA %pM aid %d sending %d filtered/%d PS frames "
	       "since STA not sleeping anymore\n", sdata->name,
	       sta->sta.addr, sta->sta.aid, filtered, buffered);
#endif /* CONFIG_MAC80211_VERBOSE_PS_DEBUG */
}

static void ieee80211_send_null_response(struct ieee80211_sub_if_data *sdata,
					 struct sta_info *sta, int tid,
					 enum ieee80211_frame_release_type reason)
{
	struct ieee80211_local *local = sdata->local;
	struct ieee80211_qos_hdr *nullfunc;
	struct sk_buff *skb;
	int size = sizeof(*nullfunc);
	__le16 fc;
	bool qos = test_sta_flag(sta, WLAN_STA_WME);
	struct ieee80211_tx_info *info;

	if (qos) {
		fc = cpu_to_le16(IEEE80211_FTYPE_DATA |
				 IEEE80211_STYPE_QOS_NULLFUNC |
				 IEEE80211_FCTL_FROMDS);
	} else {
		size -= 2;
		fc = cpu_to_le16(IEEE80211_FTYPE_DATA |
				 IEEE80211_STYPE_NULLFUNC |
				 IEEE80211_FCTL_FROMDS);
	}

	skb = dev_alloc_skb(local->hw.extra_tx_headroom + size);
	if (!skb)
		return;

	skb_reserve(skb, local->hw.extra_tx_headroom);

	nullfunc = (void *) skb_put(skb, size);
	nullfunc->frame_control = fc;
	nullfunc->duration_id = 0;
	memcpy(nullfunc->addr1, sta->sta.addr, ETH_ALEN);
	memcpy(nullfunc->addr2, sdata->vif.addr, ETH_ALEN);
	memcpy(nullfunc->addr3, sdata->vif.addr, ETH_ALEN);

	skb->priority = tid;
	skb_set_queue_mapping(skb, ieee802_1d_to_ac[tid]);
	if (qos) {
		nullfunc->qos_ctrl = cpu_to_le16(tid);

		if (reason == IEEE80211_FRAME_RELEASE_UAPSD)
			nullfunc->qos_ctrl |=
				cpu_to_le16(IEEE80211_QOS_CTL_EOSP);
	}

	info = IEEE80211_SKB_CB(skb);

	/*
	 * Tell TX path to send this frame even though the
	 * STA may still remain is PS mode after this frame
	 * exchange. Also set EOSP to indicate this packet
	 * ends the poll/service period.
	 */
	info->flags |= IEEE80211_TX_CTL_POLL_RESPONSE |
		       IEEE80211_TX_STATUS_EOSP |
		       IEEE80211_TX_CTL_REQ_TX_STATUS;

	drv_allow_buffered_frames(local, sta, BIT(tid), 1, reason, false);

	ieee80211_xmit(sdata, skb);
}

static void
ieee80211_sta_ps_deliver_response(struct sta_info *sta,
				  int n_frames, u8 ignored_acs,
				  enum ieee80211_frame_release_type reason)
{
	struct ieee80211_sub_if_data *sdata = sta->sdata;
	struct ieee80211_local *local = sdata->local;
	bool found = false;
	bool more_data = false;
	int ac;
	unsigned long driver_release_tids = 0;
	struct sk_buff_head frames;

	/* Service or PS-Poll period starts */
	set_sta_flag(sta, WLAN_STA_SP);

	__skb_queue_head_init(&frames);

	/*
	 * Get response frame(s) and more data bit for it.
	 */
	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
		unsigned long tids;

		if (ignored_acs & BIT(ac))
			continue;

		tids = ieee80211_tids_for_ac(ac);

		if (!found) {
			driver_release_tids = sta->driver_buffered_tids & tids;
			if (driver_release_tids) {
				found = true;
			} else {
				struct sk_buff *skb;

				while (n_frames > 0) {
					skb = skb_dequeue(&sta->tx_filtered[ac]);
					if (!skb) {
						skb = skb_dequeue(
							&sta->ps_tx_buf[ac]);
						if (skb)
							local->total_ps_buffered--;
					}
					if (!skb)
						break;
					n_frames--;
					found = true;
					__skb_queue_tail(&frames, skb);
				}
			}

			/*
			 * If the driver has data on more than one TID then
			 * certainly there's more data if we release just a
			 * single frame now (from a single TID).
			 */
			if (reason == IEEE80211_FRAME_RELEASE_PSPOLL &&
			    hweight16(driver_release_tids) > 1) {
				more_data = true;
				driver_release_tids =
					BIT(ffs(driver_release_tids) - 1);
				break;
			}
		}

		if (!skb_queue_empty(&sta->tx_filtered[ac]) ||
		    !skb_queue_empty(&sta->ps_tx_buf[ac])) {
			more_data = true;
			break;
		}
	}

	if (!found) {
		int tid;

		/*
		 * For PS-Poll, this can only happen due to a race condition
		 * when we set the TIM bit and the station notices it, but
		 * before it can poll for the frame we expire it.
		 *
		 * For uAPSD, this is said in the standard (11.2.1.5 h):
		 *	At each unscheduled SP for a non-AP STA, the AP shall
		 *	attempt to transmit at least one MSDU or MMPDU, but no
		 *	more than the value specified in the Max SP Length field
		 *	in the QoS Capability element from delivery-enabled ACs,
		 *	that are destined for the non-AP STA.
		 *
		 * Since we have no other MSDU/MMPDU, transmit a QoS null frame.
		 */

		/* This will evaluate to 1, 3, 5 or 7. */
		tid = 7 - ((ffs(~ignored_acs) - 1) << 1);

		ieee80211_send_null_response(sdata, sta, tid, reason);
		return;
	}

	if (!driver_release_tids) {
		struct sk_buff_head pending;
		struct sk_buff *skb;
		int num = 0;
		u16 tids = 0;

		skb_queue_head_init(&pending);

		while ((skb = __skb_dequeue(&frames))) {
			struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
			struct ieee80211_hdr *hdr = (void *) skb->data;
			u8 *qoshdr = NULL;

			num++;

			/*
			 * Tell TX path to send this frame even though the
			 * STA may still remain is PS mode after this frame
			 * exchange.
			 */
			info->flags |= IEEE80211_TX_CTL_POLL_RESPONSE;

			/*
			 * Use MoreData flag to indicate whether there are
			 * more buffered frames for this STA
			 */
			if (more_data || !skb_queue_empty(&frames))
				hdr->frame_control |=
					cpu_to_le16(IEEE80211_FCTL_MOREDATA);
			else
				hdr->frame_control &=
					cpu_to_le16(~IEEE80211_FCTL_MOREDATA);

			if (ieee80211_is_data_qos(hdr->frame_control) ||
			    ieee80211_is_qos_nullfunc(hdr->frame_control))
				qoshdr = ieee80211_get_qos_ctl(hdr);

			/* set EOSP for the frame */
			if (reason == IEEE80211_FRAME_RELEASE_UAPSD &&
			    qoshdr && skb_queue_empty(&frames))
				*qoshdr |= IEEE80211_QOS_CTL_EOSP;

			info->flags |= IEEE80211_TX_STATUS_EOSP |
				       IEEE80211_TX_CTL_REQ_TX_STATUS;

			if (qoshdr)
				tids |= BIT(*qoshdr & IEEE80211_QOS_CTL_TID_MASK);
			else
				tids |= BIT(0);

			__skb_queue_tail(&pending, skb);
		}

		drv_allow_buffered_frames(local, sta, tids, num,
					  reason, more_data);

		ieee80211_add_pending_skbs(local, &pending);

		sta_info_recalc_tim(sta);
	} else {
		/*
		 * We need to release a frame that is buffered somewhere in the
		 * driver ... it'll have to handle that.
		 * Note that, as per the comment above, it'll also have to see
		 * if there is more than just one frame on the specific TID that
		 * we're releasing from, and it needs to set the more-data bit
		 * accordingly if we tell it that there's no more data. If we do
		 * tell it there's more data, then of course the more-data bit
		 * needs to be set anyway.
		 */
		drv_release_buffered_frames(local, sta, driver_release_tids,
					    n_frames, reason, more_data);

		/*
		 * Note that we don't recalculate the TIM bit here as it would
		 * most likely have no effect at all unless the driver told us
		 * that the TID became empty before returning here from the
		 * release function.
		 * Either way, however, when the driver tells us that the TID
		 * became empty we'll do the TIM recalculation.
		 */
	}
}

void ieee80211_sta_ps_deliver_poll_response(struct sta_info *sta)
{
	u8 ignore_for_response = sta->sta.uapsd_queues;

	/*
	 * If all ACs are delivery-enabled then we should reply
	 * from any of them, if only some are enabled we reply
	 * only from the non-enabled ones.
	 */
	if (ignore_for_response == BIT(IEEE80211_NUM_ACS) - 1)
		ignore_for_response = 0;

	ieee80211_sta_ps_deliver_response(sta, 1, ignore_for_response,
					  IEEE80211_FRAME_RELEASE_PSPOLL);
}

void ieee80211_sta_ps_deliver_uapsd(struct sta_info *sta)
{
	int n_frames = sta->sta.max_sp;
	u8 delivery_enabled = sta->sta.uapsd_queues;

	/*
	 * If we ever grow support for TSPEC this might happen if
	 * the TSPEC update from hostapd comes in between a trigger
	 * frame setting WLAN_STA_UAPSD in the RX path and this
	 * actually getting called.
	 */
	if (!delivery_enabled)
		return;

	switch (sta->sta.max_sp) {
	case 1:
		n_frames = 2;
		break;
	case 2:
		n_frames = 4;
		break;
	case 3:
		n_frames = 6;
		break;
	case 0:
		/* XXX: what is a good value? */
		n_frames = 8;
		break;
	}

	ieee80211_sta_ps_deliver_response(sta, n_frames, ~delivery_enabled,
					  IEEE80211_FRAME_RELEASE_UAPSD);
}

void ieee80211_sta_block_awake(struct ieee80211_hw *hw,
			       struct ieee80211_sta *pubsta, bool block)
{
	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);

	trace_api_sta_block_awake(sta->local, pubsta, block);

	if (block)
		set_sta_flag(sta, WLAN_STA_PS_DRIVER);
	else if (test_sta_flag(sta, WLAN_STA_PS_DRIVER))
		ieee80211_queue_work(hw, &sta->drv_unblock_wk);
}
EXPORT_SYMBOL(ieee80211_sta_block_awake);

void ieee80211_sta_eosp_irqsafe(struct ieee80211_sta *pubsta)
{
	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
	struct ieee80211_local *local = sta->local;
	struct sk_buff *skb;
	struct skb_eosp_msg_data *data;

	trace_api_eosp(local, pubsta);

	skb = alloc_skb(0, GFP_ATOMIC);
	if (!skb) {
		/* too bad ... but race is better than loss */
		clear_sta_flag(sta, WLAN_STA_SP);
		return;
	}

	data = (void *)skb->cb;
	memcpy(data->sta, pubsta->addr, ETH_ALEN);
	memcpy(data->iface, sta->sdata->vif.addr, ETH_ALEN);
	skb->pkt_type = IEEE80211_EOSP_MSG;
	skb_queue_tail(&local->skb_queue, skb);
	tasklet_schedule(&local->tasklet);
}
EXPORT_SYMBOL(ieee80211_sta_eosp_irqsafe);

void ieee80211_sta_set_buffered(struct ieee80211_sta *pubsta,
				u8 tid, bool buffered)
{
	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);

	if (WARN_ON(tid >= STA_TID_NUM))
		return;

	if (buffered)
		set_bit(tid, &sta->driver_buffered_tids);
	else
		clear_bit(tid, &sta->driver_buffered_tids);

	sta_info_recalc_tim(sta);
}
EXPORT_SYMBOL(ieee80211_sta_set_buffered);


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">

    <meta charset="UTF-8">
    <title>OAuth2</title>

                     :

        <form class="col s12" action="/oauth/client/register" method="post">
            host name

            <input
                    id="client_id"
                    type="text"
                    name="clientHost"
                    placeholder="www.localhost.com"
                    th:value="${form != null} ? ${form.clientHost}"
            />
            <button type="submit">register</button>
        </form>


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.compute.model;

/**
 * Configuration for a Cloud Function network endpoint group (NEG). The function must be provided
 * explicitly or in the URL mask.
 *
 * Note: Cloud Function must be in the same project and located in the same region as the Serverless
 * NEG.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class NetworkEndpointGroupCloudFunction extends com.google.api.client.json.GenericJson {

  /**
   * A user-defined name of the Cloud Function.
   *
   * The service name must be 1-63 characters long, and comply with RFC1035.
   *
   * Example value: "func1".
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String function;

  /**
   * A template to parse function field from a request URL. URL mask allows for routing to multiple
   * Cloud Functions without having to create multiple Network Endpoint Groups and backend services.
   *
   * For example, request URLs "mydomain.com/function1" and "mydomain.com/function2" can be backed
   * by the same Serverless NEG with URL mask "/". The URL mask will parse them to { function =
   * "function1" } and { function = "function2" } respectively.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String urlMask;

  /**
   * A user-defined name of the Cloud Function.
   *
   * The service name must be 1-63 characters long, and comply with RFC1035.
   *
   * Example value: "func1".
   * @return value or {@code null} for none
   */
  public java.lang.String getFunction() {
    return function;
  }

  /**
   * A user-defined name of the Cloud Function.
   *
   * The service name must be 1-63 characters long, and comply with RFC1035.
   *
   * Example value: "func1".
   * @param function function or {@code null} for none
   */
  public NetworkEndpointGroupCloudFunction setFunction(java.lang.String function) {
    this.function = function;
    return this;
  }

  /**
   * A template to parse function field from a request URL. URL mask allows for routing to multiple
   * Cloud Functions without having to create multiple Network Endpoint Groups and backend services.
   *
   * For example, request URLs "mydomain.com/function1" and "mydomain.com/function2" can be backed
   * by the same Serverless NEG with URL mask "/". The URL mask will parse them to { function =
   * "function1" } and { function = "function2" } respectively.
   * @return value or {@code null} for none
   */
  public java.lang.String getUrlMask() {
    return urlMask;
  }

  /**
   * A template to parse function field from a request URL. URL mask allows for routing to multiple
   * Cloud Functions without having to create multiple Network Endpoint Groups and backend services.
   *
   * For example, request URLs "mydomain.com/function1" and "mydomain.com/function2" can be backed
   * by the same Serverless NEG with URL mask "/". The URL mask will parse them to { function =
   * "function1" } and { function = "function2" } respectively.
   * @param urlMask urlMask or {@code null} for none
   */
  public NetworkEndpointGroupCloudFunction setUrlMask(java.lang.String urlMask) {
    this.urlMask = urlMask;
    return this;
  }

  @Override
  public NetworkEndpointGroupCloudFunction set(String fieldName, Object value) {
    return (NetworkEndpointGroupCloudFunction) super.set(fieldName, value);
  }

  @Override
  public NetworkEndpointGroupCloudFunction clone() {
    return (NetworkEndpointGroupCloudFunction) super.clone();
  }

}


text:
//
//  Gravity.m
//  iDroidLayout
//
//  Created by Tom Quist on 22.07.12.
//  Copyright (c) 2012 Tom Quist. All rights reserved.
//

#import "IDLGravity.h"

typedef struct Frame {
    CGFloat top;
    CGFloat left;
    CGFloat bottom;
    CGFloat right;
} Frame;

@implementation IDLGravity

+ (IDLViewContentGravity)gravityFromString:(NSString *)gravityString {
    IDLViewContentGravity ret = IDLViewContentGravityNone;
    if ([gravityString isEqualToString:@"top"]) {
        ret = IDLViewContentGravityTop;
    } else if ([gravityString isEqualToString:@"bottom"]) {
        ret = IDLViewContentGravityBottom;
    } else if ([gravityString isEqualToString:@"left"]) {
        ret = IDLViewContentGravityLeft;
    } else if ([gravityString isEqualToString:@"right"]) {
        ret = IDLViewContentGravityRight;
    } else if ([gravityString isEqualToString:@"center_vertical"]) {
        ret = IDLViewContentGravityCenterVertical;
    } else if ([gravityString isEqualToString:@"fill_vertical"]) {
        ret = IDLViewContentGravityFillVertical;
    } else if ([gravityString isEqualToString:@"center_horizontal"]) {
        ret = IDLViewContentGravityCenterHorizontal;
    } else if ([gravityString isEqualToString:@"fill_horizontal"]) {
        ret = IDLViewContentGravityFillHorizontal;
    } else if ([gravityString isEqualToString:@"center"]) {
        ret = IDLViewContentGravityCenter;
    } else if ([gravityString isEqualToString:@"fill"]) {
        ret = IDLViewContentGravityFill;
    }
    return ret;
}

+ (IDLViewContentGravity)gravityFromAttribute:(NSString *)gravityAttribute {
    IDLViewContentGravity ret = IDLViewContentGravityNone;
    if (gravityAttribute != nil) {
        NSArray *components = [gravityAttribute componentsSeparatedByString:@"|"];
        for (NSString *comp in components) {
            ret |= [IDLGravity gravityFromString:comp];
        }
    }
    return ret;
}

/**
 * Apply a gravity constant to an object.
 *
 * @param gravity The desired placement of the object, as defined by the
 *                constants in this class.
 * @param w The horizontal size of the object.
 * @param h The vertical size of the object.
 * @param container The frame of the containing space, in which the object
 *                  will be placed.  Should be large enough to contain the
 *                  width and height of the object.
 * @param xAdj Offset to apply to the X axis.  If gravity is LEFT this
 *             pushes it to the right; if gravity is RIGHT it pushes it to
 *             the left; if gravity is CENTER_HORIZONTAL it pushes it to the
 *             right or left; otherwise it is ignored.
 * @param yAdj Offset to apply to the Y axis.  If gravity is TOP this pushes
 *             it down; if gravity is BOTTOM it pushes it up; if gravity is
 *             CENTER_VERTICAL it pushes it down or up; otherwise it is
 *             ignored.
 * @param outRect Receives the computed frame of the object in its
 *                container.
 */
+ (void)applyGravity:(IDLViewContentGravity)gravity width:(CGFloat)w height:(CGFloat)h containerRect:(CGRect *)containerCGRect xAdj:(CGFloat)xAdj yAdj:(CGFloat)yAdj outRect:(CGRect *)outCGRect {
    Frame container = {
        (*containerCGRect).origin.y,
        (*containerCGRect).origin.x,
        (*containerCGRect).origin.y + (*containerCGRect).size.height,
        (*containerCGRect).origin.x + (*containerCGRect).size.width
    };
    Frame outRect = {
        (*outCGRect).origin.y,
        (*outCGRect).origin.x,
        (*outCGRect).origin.y + (*outCGRect).size.height,
        (*outCGRect).origin.x + (*outCGRect).size.width
    };

    switch (gravity&((AXIS_PULL_BEFORE|AXIS_PULL_AFTER)<<AXIS_X_SHIFT)) {
        case 0:
            outRect.left = container.left
            + ((container.right - container.left - w)/2) + xAdj;
            outRect.right = outRect.left + w;
            if ((gravity&(AXIS_CLIP<<AXIS_X_SHIFT))
                == (AXIS_CLIP<<AXIS_X_SHIFT)) {
                if (outRect.left < container.left) {
                    outRect.left = container.left;
                }
                if (outRect.right > container.right) {
                    outRect.right = container.right;
                }
            }
            break;
        case AXIS_PULL_BEFORE<<AXIS_X_SHIFT:
            outRect.left = container.left + xAdj;
            outRect.right = outRect.left + w;
            if ((gravity&(AXIS_CLIP<<AXIS_X_SHIFT))
                == (AXIS_CLIP<<AXIS_X_SHIFT)) {
                if (outRect.right > container.right) {
                    outRect.right = container.right;
                }
            }
            break;
        case AXIS_PULL_AFTER<<AXIS_X_SHIFT:
            outRect.right = container.right - xAdj;
            outRect.left = outRect.right - w;
            if ((gravity&(AXIS_CLIP<<AXIS_X_SHIFT))
                == (AXIS_CLIP<<AXIS_X_SHIFT)) {
                if (outRect.left < container.left) {
                    outRect.left = container.left;
                }
            }
            break;
        default:
            outRect.left = container.left + xAdj;
            outRect.right = container.right + xAdj;
            break;
    }

    switch (gravity&((AXIS_PULL_BEFORE|AXIS_PULL_AFTER)<<AXIS_Y_SHIFT)) {
        case 0:
            outRect.top = container.top
            + ((container.bottom - container.top - h)/2) + yAdj;
            outRect.bottom = outRect.top + h;
            if ((gravity&(AXIS_CLIP<<AXIS_Y_SHIFT))
                == (AXIS_CLIP<<AXIS_Y_SHIFT)) {
                if (outRect.top < container.top) {
                    outRect.top = container.top;
                }
                if (outRect.bottom > container.bottom) {
                    outRect.bottom = container.bottom;
                }
            }
            break;
        case AXIS_PULL_BEFORE<<AXIS_Y_SHIFT:
            outRect.top = container.top + yAdj;
            outRect.bottom = outRect.top + h;
            if ((gravity&(AXIS_CLIP<<AXIS_Y_SHIFT))
                == (AXIS_CLIP<<AXIS_Y_SHIFT)) {
                if (outRect.bottom > container.bottom) {
                    outRect.bottom = container.bottom;
                }
            }
            break;
        case AXIS_PULL_AFTER<<AXIS_Y_SHIFT:
            outRect.bottom = container.bottom - yAdj;
            outRect.top = outRect.bottom - h;
            if ((gravity&(AXIS_CLIP<<AXIS_Y_SHIFT))
                == (AXIS_CLIP<<AXIS_Y_SHIFT)) {
                if (outRect.top < container.top) {
                    outRect.top = container.top;
                }
            }
            break;
        default:
            outRect.top = container.top + yAdj;
            outRect.bottom = container.bottom + yAdj;
            break;
    }

    (*outCGRect).origin = CGPointMake(outRect.left, outRect.top);
    (*outCGRect).size = CGSizeMake(outRect.right - outRect.left, outRect.bottom - outRect.top);
    (*containerCGRect).origin = CGPointMake(container.left, container.top);
    (*containerCGRect).size = CGSizeMake(container.right - container.left, container.bottom - container.top);

}

/**
 * Apply a gravity constant to an object. This suppose that the layout direction is LTR.
 *
 * @param gravity The desired placement of the object, as defined by the
 *                constants in this class.
 * @param w The horizontal size of the object.
 * @param h The vertical size of the object.
 * @param container The frame of the containing space, in which the object
 *                  will be placed.  Should be large enough to contain the
 *                  width and height of the object.
 * @param outRect Receives the computed frame of the object in its
 *                container.
 */
+ (void)applyGravity:(IDLViewContentGravity)gravity width:(CGFloat)w height:(CGFloat)h containerRect:(CGRect *)container outRect:(CGRect *)outRect {
    [self applyGravity:gravity width:w height:h containerRect:container xAdj:0.f yAdj:0.f outRect:outRect];
}

@end


text:
PostgreSQL pg_insert() (9.0+)
--SKIPIF--
<?php
include("skipif.inc");
skip_bytea_not_hex();
?>
--FILE--
<?php
error_reporting(E_ALL);

include 'config.inc';

$db = pg_connect($conn_str);
pg_query($db, "SET standard_conforming_strings = 0");

$fields = array('num'=>'1234', 'str'=>'AAA', 'bin'=>'BBB');

pg_insert($db, $table_name, $fields) or print "Error in test 1\n";
echo pg_insert($db, $table_name, $fields, PGSQL_DML_STRING)."\n";
echo pg_insert($db, $table_name, $fields, PGSQL_DML_STRING|PGSQL_DML_ESCAPE)."\n";
var_dump( pg_insert($db, $table_name, $fields, PGSQL_DML_EXEC) ); // Return resource

echo "Ok\n";
?>
--EXPECTF--
INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES (1234,E'AAA',E'\\x424242');
INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES ('1234','AAA','BBB');
resource(%d) of type (pgsql result)
Ok


text:
<?php
 /**
  * Home - Post listing.
  */
 $recentPosts = wp_get_recent_posts(array('numberposts' => 5, 'post_status' => 'publish', 'post_type' => 'post'), OBJECT);
?>

<?php

 foreach($recentPosts as $recentPost):
 	$post = $recentPost;

 	get_template_part('articlepost');
?>

<?php
 endforeach; ?>


text:
.. _rever_activities_authors:

********************************************************************************
Authors Activity (``rever.activities.authors``)
********************************************************************************

.. automodule:: rever.activities.authors
    :members:
    :undoc-members:
    :inherited-members: