text:
/*!
    \class QGraphicsGridLayout
    \brief The QGraphicsGridLayout class provides a grid layout for managing
    widgets in Graphics View.
    \since 4.4

    \ingroup graphicsview-api

    The most common way to use QGraphicsGridLayout is to construct an object
    on the heap with no parent, add widgets and layouts by calling addItem(),
    and finally assign the layout to a widget by calling
    QGraphicsWidget::setLayout(). QGraphicsGridLayout automatically computes
    the dimensions of the grid as you add items.

    \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp 0

    The layout takes ownership of the items. In some cases when the layout
    item also inherits from QGraphicsItem (such as QGraphicsWidget) there will be a
    ambiguity in ownership because the layout item belongs to two ownership hierarchies.
    See the documentation of QGraphicsLayoutItem::setOwnedByLayout() how to handle
    this.
    You can access each item in the layout by calling count() and itemAt(). Calling
    removeAt() will remove an item from the layout, without
    destroying it.

    \section1 Size Hints and Size Policies in QGraphicsGridLayout

    QGraphicsGridLayout respects each item's size hints and size policies,
    and when a cell in the grid has more space than the items can fill, each item
    is arranged according to the layout's alignment for that item. You can set
    an alignment for each item by calling setAlignment(), and check the
    alignment for any item by calling alignment(). You can also set the alignment
    for an entire row or column by calling setRowAlignment() and setColumnAlignment()
    respectively.  By default, items are aligned to the top left.

    \sa QGraphicsLinearLayout, QGraphicsWidget
*/

#include "qglobal.h"

#ifndef QT_NO_GRAPHICSVIEW

#include "qapplication.h"
#include "qwidget.h"
#include "qgraphicslayout_p.h"
#include "qgraphicslayoutitem.h"
#include "qgraphicsgridlayout.h"
#include "qgraphicswidget.h"
#include "qgridlayoutengine_p.h"
#include <QtCore/qdebug.h>

QT_BEGIN_NAMESPACE

class QGraphicsGridLayoutPrivate : public QGraphicsLayoutPrivate
{
public:
    QGraphicsGridLayoutPrivate() { }
    QLayoutStyleInfo styleInfo() const;

    QGridLayoutEngine engine;
#ifdef QT_DEBUG
    void dump(int indent) const;
#endif
};

Q_GLOBAL_STATIC(QWidget, globalStyleInfoWidget);

QLayoutStyleInfo QGraphicsGridLayoutPrivate::styleInfo() const
{
    QGraphicsItem *item = parentItem();
    QStyle *style = (item && item->isWidget()) ? static_cast<QGraphicsWidget*>(item)->style() : QApplication::style();
    return QLayoutStyleInfo(style, globalStyleInfoWidget());
}

/*!
    Constructs a QGraphicsGridLayout instance.  \a parent is passed to
    QGraphicsLayout's constructor.
*/
QGraphicsGridLayout::QGraphicsGridLayout(QGraphicsLayoutItem *parent)
    : QGraphicsLayout(*new QGraphicsGridLayoutPrivate(), parent)
{
}

/*!
    Destroys the QGraphicsGridLayout object.
*/
QGraphicsGridLayout::~QGraphicsGridLayout()
{
    for (int i = count() - 1; i >= 0; --i) {
        QGraphicsLayoutItem *item = itemAt(i);
        // The following lines can be removed, but this removes the item
        // from the layout more efficiently than the implementation of
        // ~QGraphicsLayoutItem.
        removeAt(i);
        if (item) {
            item->setParentLayoutItem(0);
            if (item->ownedByLayout())
                delete item;
        }
    }
}

/*!
    Adds \a item to the grid on \a row and \a column. You can specify a
    \a rowSpan and \a columnSpan and an optional \a alignment.
*/
void QGraphicsGridLayout::addItem(QGraphicsLayoutItem *item, int row, int column,
                                  int rowSpan, int columnSpan, Qt::Alignment alignment)
{
    Q_D(QGraphicsGridLayout);
    if (row < 0 || column < 0) {
        qWarning("QGraphicsGridLayout::addItem: invalid row/column: %d",
                 row < 0 ? row : column);
        return;
    }
    if (columnSpan < 1 || rowSpan < 1) {
        qWarning("QGraphicsGridLayout::addItem: invalid row span/column span: %d",
                 rowSpan < 1 ? rowSpan : columnSpan);
        return;
    }
    if (!item) {
        qWarning("QGraphicsGridLayout::addItem: cannot add null item");
        return;
    }
    if (item == this) {
        qWarning("QGraphicsGridLayout::addItem: cannot insert itself");
        return;
    }

    d->addChildLayoutItem(item);

    new QGridLayoutItem(&d->engine, item, row, column, rowSpan, columnSpan, alignment);
    invalidate();
}

/*!
    \fn QGraphicsGridLayout::addItem(QGraphicsLayoutItem *item, int row, int column, Qt::Alignment alignment = 0)

    Adds \a item to the grid on \a row and \a column. You can specify
    an optional \a alignment for \a item.
*/

/*!
    Sets the default horizontal spacing for the grid layout to \a spacing.
*/
void QGraphicsGridLayout::setHorizontalSpacing(qreal spacing)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setSpacing(spacing, Qt::Horizontal);
    invalidate();
}

/*!
    Returns the default horizontal spacing for the grid layout.
*/
qreal QGraphicsGridLayout::horizontalSpacing() const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.spacing(d->styleInfo(), Qt::Horizontal);
}

/*!
    Sets the default vertical spacing for the grid layout to \a spacing.
*/
void QGraphicsGridLayout::setVerticalSpacing(qreal spacing)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setSpacing(spacing, Qt::Vertical);
    invalidate();
}

/*!
    Returns the default vertical spacing for the grid layout.
*/
qreal QGraphicsGridLayout::verticalSpacing() const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.spacing(d->styleInfo(), Qt::Vertical);
}

/*!
    Sets the grid layout's default spacing, both vertical and
    horizontal, to \a spacing.

    \sa rowSpacing(), columnSpacing()
*/
void QGraphicsGridLayout::setSpacing(qreal spacing)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
    invalidate();
}

/*!
    Sets the spacing for \a row to \a spacing.
*/
void QGraphicsGridLayout::setRowSpacing(int row, qreal spacing)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSpacing(row, spacing, Qt::Vertical);
    invalidate();
}

/*!
    Returns the row spacing for \a row.
*/
qreal QGraphicsGridLayout::rowSpacing(int row) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowSpacing(row, Qt::Vertical);
}

/*!
    Sets the spacing for \a column to \a spacing.
*/
void QGraphicsGridLayout::setColumnSpacing(int column, qreal spacing)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSpacing(column, spacing, Qt::Horizontal);
    invalidate();
}

/*!
    Returns the column spacing for \a column.
*/
qreal QGraphicsGridLayout::columnSpacing(int column) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowSpacing(column, Qt::Horizontal);
}

/*!
    Sets the stretch factor for \a row to \a stretch.
*/
void QGraphicsGridLayout::setRowStretchFactor(int row, int stretch)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowStretchFactor(row, stretch, Qt::Vertical);
    invalidate();
}

/*!
    Returns the stretch factor for \a row.
*/
int QGraphicsGridLayout::rowStretchFactor(int row) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowStretchFactor(row, Qt::Vertical);
}

/*!
    Sets the stretch factor for \a column to \a stretch.
*/
void QGraphicsGridLayout::setColumnStretchFactor(int column, int stretch)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowStretchFactor(column, stretch, Qt::Horizontal);
    invalidate();
}

/*!
    Returns the stretch factor for \a column.
*/
int QGraphicsGridLayout::columnStretchFactor(int column) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowStretchFactor(column, Qt::Horizontal);
}

/*!
    Sets the minimum height for row, \a row, to \a height.
*/
void QGraphicsGridLayout::setRowMinimumHeight(int row, qreal height)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSizeHint(Qt::MinimumSize, row, height, Qt::Vertical);
    invalidate();
}

/*!
    Returns the minimum height for row, \a row.
*/
qreal QGraphicsGridLayout::rowMinimumHeight(int row) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowSizeHint(Qt::MinimumSize, row, Qt::Vertical);
}

/*!
    Sets the preferred height for row, \a row, to \a height.
*/
void QGraphicsGridLayout::setRowPreferredHeight(int row, qreal height)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSizeHint(Qt::PreferredSize, row, height, Qt::Vertical);
    invalidate();
}

/*!
    Returns the preferred height for row, \a row.
*/
qreal QGraphicsGridLayout::rowPreferredHeight(int row) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowSizeHint(Qt::PreferredSize, row, Qt::Vertical);
}

/*!
    Sets the maximum height for row, \a row, to \a height.
*/
void QGraphicsGridLayout::setRowMaximumHeight(int row, qreal height)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSizeHint(Qt::MaximumSize, row, height, Qt::Vertical);
    invalidate();
}

/*!
    Returns the maximum height for row, \a row.
*/
qreal QGraphicsGridLayout::rowMaximumHeight(int row) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowSizeHint(Qt::MaximumSize, row, Qt::Vertical);
}

/*!
    Sets the fixed height for row, \a row, to \a height.
*/
void QGraphicsGridLayout::setRowFixedHeight(int row, qreal height)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSizeHint(Qt::MinimumSize, row, height, Qt::Vertical);
    d->engine.setRowSizeHint(Qt::MaximumSize, row, height, Qt::Vertical);
    invalidate();
}

/*!
    Sets the minimum width for \a column to \a width.
*/
void QGraphicsGridLayout::setColumnMinimumWidth(int column, qreal width)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSizeHint(Qt::MinimumSize, column, width, Qt::Horizontal);
    invalidate();
}

/*!
    Returns the minimum width for \a column.
*/
qreal QGraphicsGridLayout::columnMinimumWidth(int column) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowSizeHint(Qt::MinimumSize, column, Qt::Horizontal);
}

/*!
    Sets the preferred width for \a column to \a width.
*/
void QGraphicsGridLayout::setColumnPreferredWidth(int column, qreal width)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSizeHint(Qt::PreferredSize, column, width, Qt::Horizontal);
    invalidate();
}

/*!
    Returns the preferred width for \a column.
*/
qreal QGraphicsGridLayout::columnPreferredWidth(int column) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowSizeHint(Qt::PreferredSize, column, Qt::Horizontal);
}

/*!
    Sets the maximum width of \a column to \a width.
*/
void QGraphicsGridLayout::setColumnMaximumWidth(int column, qreal width)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSizeHint(Qt::MaximumSize, column, width, Qt::Horizontal);
    invalidate();
}

/*!
    Returns the maximum width for \a column.
*/
qreal QGraphicsGridLayout::columnMaximumWidth(int column) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowSizeHint(Qt::MaximumSize, column, Qt::Horizontal);
}

/*!
    Sets the fixed width of \a column to \a width.
*/
void QGraphicsGridLayout::setColumnFixedWidth(int column, qreal width)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowSizeHint(Qt::MinimumSize, column, width, Qt::Horizontal);
    d->engine.setRowSizeHint(Qt::MaximumSize, column, width, Qt::Horizontal);
    invalidate();
}

/*!
    Sets the alignment of \a row to \a alignment.
*/
void QGraphicsGridLayout::setRowAlignment(int row, Qt::Alignment alignment)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowAlignment(row, alignment, Qt::Vertical);
    invalidate();
}

/*!
    Returns the alignment of \a row.
*/
Qt::Alignment QGraphicsGridLayout::rowAlignment(int row) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowAlignment(row, Qt::Vertical);
}

/*!
    Sets the alignment for \a column to \a alignment.
*/
void QGraphicsGridLayout::setColumnAlignment(int column, Qt::Alignment alignment)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setRowAlignment(column, alignment, Qt::Horizontal);
    invalidate();
}

/*!
    Returns the alignment for \a column.
*/
Qt::Alignment QGraphicsGridLayout::columnAlignment(int column) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.rowAlignment(column, Qt::Horizontal);
}

/*!
    Sets the alignment for \a item to \a alignment.
*/
void QGraphicsGridLayout::setAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment)
{
    Q_D(QGraphicsGridLayout);
    d->engine.setAlignment(item, alignment);
    invalidate();
}

/*!
    Returns the alignment for \a item.
*/
Qt::Alignment QGraphicsGridLayout::alignment(QGraphicsLayoutItem *item) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.alignment(item);
}

/*!
    Returns the number of rows in the grid layout. This is always one more
    than the index of the last row that is occupied by a layout item (empty
    rows are counted except for those at the end).
*/
int QGraphicsGridLayout::rowCount() const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.effectiveLastRow(Qt::Vertical) + 1;
}

/*!
    Returns the number of columns in the grid layout. This is always one more
    than the index of  the last column that is occupied by a layout item (empty
    columns are counted except for those at the end).
*/
int QGraphicsGridLayout::columnCount() const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.effectiveLastRow(Qt::Horizontal) + 1;
}

/*!
    Returns a pointer to the layout item at (\a row, \a column).
*/
QGraphicsLayoutItem *QGraphicsGridLayout::itemAt(int row, int column) const
{
    Q_D(const QGraphicsGridLayout);
    if (row < 0 || row >= rowCount() || column < 0 || column >= columnCount()) {
        qWarning("QGraphicsGridLayout::itemAt: invalid row, column %d, %d", row, column);
        return 0;
    }
    if (QGridLayoutItem *item = d->engine.itemAt(row, column))
        return item->layoutItem();
    return 0;
}

/*!
    Returns the number of layout items in this grid layout.
*/
int QGraphicsGridLayout::count() const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.itemCount();
}

/*!
    Returns the layout item at \a index, or 0 if there is no layout item at
    this index.
*/
QGraphicsLayoutItem *QGraphicsGridLayout::itemAt(int index) const
{
    Q_D(const QGraphicsGridLayout);
    if (index < 0 || index >= d->engine.itemCount()) {
        qWarning("QGraphicsGridLayout::itemAt: invalid index %d", index);
        return 0;
    }
    QGraphicsLayoutItem *item = 0;
    if (QGridLayoutItem *gridItem = d->engine.itemAt(index))
        item = gridItem->layoutItem();
    return item;
}

/*!
    Removes the layout item at \a index without destroying it. Ownership of
    the item is transferred to the caller.

    \sa addItem()
*/
void QGraphicsGridLayout::removeAt(int index)
{
    Q_D(QGraphicsGridLayout);
    if (index < 0 || index >= d->engine.itemCount()) {
        qWarning("QGraphicsGridLayout::removeAt: invalid index %d", index);
        return;
    }
    if (QGridLayoutItem *gridItem = d->engine.itemAt(index)) {
        if (QGraphicsLayoutItem *layoutItem = gridItem->layoutItem())
            layoutItem->setParentLayoutItem(0);
        d->engine.removeItem(gridItem);

        // recalculate rowInfo.count if we remove an item that is on the right/bottommost row
        for (int j = 0; j < NOrientations; ++j) {
            // 0: Hor, 1: Ver
            const Qt::Orientation orient = (j == 0 ? Qt::Horizontal : Qt::Vertical);
            const int oldCount = d->engine.rowCount(orient);
            if (gridItem->lastRow(orient) == oldCount - 1) {
                const int newCount = d->engine.effectiveLastRow(orient) + 1;
                d->engine.removeRows(newCount, oldCount - newCount, orient);
            }
        }

        delete gridItem;
        invalidate();
    }
}

/*!
    \since 4.8

    Removes the layout item \a item without destroying it.
    Ownership of the item is transferred to the caller.

    \sa addItem()
*/
void QGraphicsGridLayout::removeItem(QGraphicsLayoutItem *item)
{
    Q_D(QGraphicsGridLayout);
    int index = d->engine.indexOf(item);
    removeAt(index);
}
/*!
    \reimp
*/
void QGraphicsGridLayout::invalidate()
{
    Q_D(QGraphicsGridLayout);
    d->engine.invalidate();
    QGraphicsLayout::invalidate();
}

#ifdef QT_DEBUG
void QGraphicsGridLayoutPrivate::dump(int indent) const
{
    if (qt_graphicsLayoutDebug()) {
        engine.dump(indent + 1);
    }
}
#endif

/*!
    Sets the bounding geometry of the grid layout to \a rect.
*/
void QGraphicsGridLayout::setGeometry(const QRectF &rect)
{
    Q_D(QGraphicsGridLayout);
    QGraphicsLayout::setGeometry(rect);
    QRectF effectiveRect = geometry();
    qreal left, top, right, bottom;
    getContentsMargins(&left, &top, &right, &bottom);
    Qt::LayoutDirection visualDir = d->visualDirection();
    d->engine.setVisualDirection(visualDir);
    if (visualDir == Qt::RightToLeft)
        qSwap(left, right);
    effectiveRect.adjust(+left, +top, -right, -bottom);
    d->engine.setGeometries(d->styleInfo(), effectiveRect);
#ifdef QT_DEBUG
    if (qt_graphicsLayoutDebug()) {
        static int counter = 0;
        qDebug("==== BEGIN DUMP OF QGraphicsGridLayout (%d)====", counter++);
        d->dump(1);
        qDebug("==== END DUMP OF QGraphicsGridLayout ====");
    }
#endif
}

/*!
    \reimp
*/
QSizeF QGraphicsGridLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
    Q_D(const QGraphicsGridLayout);
    qreal left, top, right, bottom;
    getContentsMargins(&left, &top, &right, &bottom);
    const QSizeF extraMargins(left + right, top + bottom);
    return d->engine.sizeHint(d->styleInfo(), which , constraint - extraMargins) + extraMargins;
}

#if 0
// ### kill? (implement and kill?)
QRect QGraphicsGridLayout::cellRect(int row, int column, int rowSpan, int columnSpan) const
{
    Q_D(const QGraphicsGridLayout);
    return QRect();
//    return d->engine.cellRect(parentLayoutable(), contentsGeometry(), row, column, rowSpan, columnSpan);
}

QSizePolicy::ControlTypes QGraphicsGridLayout::controlTypes(LayoutSide side) const
{
    Q_D(const QGraphicsGridLayout);
    return d->engine.controlTypes(side);
}
#endif

QT_END_NAMESPACE

#endif //QT_NO_GRAPHICSVIEW


text:
package com.github.kostyasha.yad;

import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.remoting.Channel;
import hudson.slaves.AbstractCloudComputer;
import org.jenkinsci.plugins.cloudstats.ProvisioningActivity;
import org.jenkinsci.plugins.cloudstats.TrackedItem;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import static java.util.Objects.nonNull;

/**
 * @author Kanstantsin Shautsou
 */
public class DockerComputerSingle extends AbstractCloudComputer<DockerSlaveSingle> implements TrackedItem {
    private final ProvisioningActivity.Id activityId;
    private transient TaskListener listener;
    private transient Run run;

    public DockerComputerSingle(@Nonnull DockerSlaveSingle slave, @Nonnull ProvisioningActivity.Id activityId) {
        super(slave);
        this.activityId = activityId;
    }

    @Override
    public TaskListener getListener() {
        return nonNull(listener) ? listener : super.getListener();
    }

    public void setListener(TaskListener listener) {
        this.listener = listener;
    }

    public Run getRun() {
        return run;
    }

    public void setRun(Run run) {
        this.run = run;
    }

    @Override
    public void setChannel(Channel channel, OutputStream launchLog, Channel.Listener listener)
            throws IOException, InterruptedException {
        super.setChannel(channel, launchLog, listener);
    }

    public boolean isReallyOffline() {
        return super.isOffline();
    }

    @Override
    public boolean isOffline() {
        // create executors to pick tasks
        return false;
    }

    @Override
    public Charset getDefaultCharset() {
        // either fails
        // java.lang.NullPointerException
        // at hudson.model.Run.execute(Run.java:1702)
        // at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
        // at hudson.model.ResourceController.execute(ResourceController.java:98)
        // at hudson.model.Executor.run(Executor.java:404)
        return Charset.forName("UTF-8");
    }

    @Nullable
    @Override
    public ProvisioningActivity.Id getId() {
        return activityId;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Python based PSSH header dumper for MP4 / MP4 ISO Base Media File Format / DASH Fragments

## Usage

### Script

    pywvpsshdump myfile.mp4

Output:

    Filename: myfile.mp4
     algorith: AESCTR
     key_id: ffffff
     provider: myprovider
     content_id: 1234567890
     track_type:
     policy:
     crypto_period_index: 1198817
     grouped_license:

## Programmatically

    >>> import pywvpssh
    >>> pssh = WvPsshExtractor.extract(mp4_file=filename)
    >>> type(pssh)
    widevine_pssh_pb2.WidevinePsshData

    >>> pssh.content_id
    1234567890

## Installation

## Quick

Pip install with dependencies:

    pip install https://github.com/use-sparingly/pymp4parse/zipball/master \
                https://github.com/use-sparingly/pywvpssh/zipball/master

### Requirements

- pymp4parse: https://github.com/use-sparingly/pymp4parse
- Protobuf: https://pypi.python.org/pypi/protobuf


text:
<?php
/*
  current_temp.php
  Created by: Kytis
  Date Created: 16 April 2017
*/
function CreateTable($result)
{
    // Echoing HTML
    //Head Tag
    echo "";
    echo "<link rel="stylesheet" type="text/css" href="SmartBox.css"";
    echo "";
    //Table Tag
    echo "
";
    echo "<col width='130'>";
    echo "
";
    echo "Temp Date";
    echo "	";
    echo "";
    echo "Compartment";
    echo "	";
    echo "&nbsp";
    echo "";
    echo "Temperature";
    echo "
";
    while ($row = $result->fetchArray()) {
        $dateOfTemp = $row["DateofTemp"];
        $Compartments = $row["Compartments"];
        $Temperatures = $row["Temperature"];
        echo "
";
        echo "$dateOfTemp	";
        echo "$Compartments	";
        echo "$Temperatures	";
        echo "
";
    }
    echo "
";
}

$db_path = '/home/pi/var/www/html/request.db';
$db = new SQLite3($db_path);

// Selecting Data From Database
$results = $db->query('SELECT DateofTemp, Compartments, Temperature FROM tbTemperatures');

CreateTable($results);

?>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Sean's Portfolio</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Sean Crowl

                        Resume

                        Portfolio

                        About

                        Contact

                        Sean Crowl

                        iOS Developer - Web Developer

Portfolio

About

I am an app and web developer experienced in Swift, HTML, CSS, SQL, and Javascript languages,
                        as well as having experience in Adobe Creative Suite. I am a hard-working individual who loves learning and new challenges. I am looking for an entry level development job where my dedication and problems solving skills will have immediate positive impact on product development.

Contact Me

E-Mail:
seankcrowl@gmail.com

Telephone:
(330)605-0354

Location

25 Hummingbird Ln.

Nippa, KY 41240

Around the Web

Github

Find Sean's work on Github.

 Sean on Github

                        Copyright © Sean Crowl 2017

Gift.It

Gift.It is a mobile app designed and catered to businesses to allow a quick and easy solution to anonymous gift giving, donation, and need fulfillment services.

Client:
                                    Interapt

Date:
                                    November 2016

Service:
                                    App Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Scribblit

A fully customizeable, completely secure, HIPAA compliant messaging app.

Client:
                                    Interapt

Date:
                                    January 2017

Service:
                                    App Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Fantasy Football Fix

Fantasy Football Fix is an app designed as a companion app for Fantasy Football fans to quickly and easily look up weekly player stats, comparisons, and keep track of their own team.

Client:
                                    TEKY

Date:
                                    November 2016

Service:
                                    App Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Weatherly

A quick an easy to use web weather app that can track and compare weather for multiple locations.

Client:
                                    TEKY

Date:
                                    September 2016

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Maply

A quick and easy to use map web app.

Client:
                                    TEKY

Date:
                                    September 2016

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Tic-Tac-Toe

An easy to play web tic-tac-toe game. Keeps track of score and player order.

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
<?php
include_once('header-nologin.php');
$error = '';
if ((isset($_GET[0])) && ($_GET[1] == 0))
	$error	= '
Un usuario ya ha sido registrado con estos datos.×
';
if ((isset($_GET[0])) && ($_GET[1] == 0))
	$error	= '
Hay un error en los datos suministrados.×
';

?>

Login

Register

                    <?php echo $error;?>
					<form action="<?php echo APPLICATION_URL?>user.controller/login.html"  method="post" class="nice">

					    	<legend>Login</legend>

					    		Email
					        	<input type="text" class="expand input-text email" name="user_email" title="Email" required="required">

					    		Password
					    		<input type="password" class="expand input-text" name="user_password" title="Password">

					    		<input type="submit" class="button round" title="Login" value="Login">
					    		<a href="<?php echo APPLICATION_URL?>login-recuperar-contrasena-0110.html" title="Forgot your password?">Forgot your password?

					</form>

					<form  action="<?php echo APPLICATION_URL?>user.controller/create.html"  method="post" class="nice" id="validable">

					    	<legend>Sign In</legend>

					    		Email
					        	<input type="mail" name="user_email" class="expand input-text email" title="Email" required="required">

					    		Confirm Email
					        	<input type="mail" name="user_email_confirm" class="expand input-text retype" alt="email" title="Email" required="required">

					    		Password
					    		<input type="password" name="user_password" class="expand input-text" title="Password" required="required">

					    		Confirm password
					    		<input type="password" name="user_password_confirm" class="expand input-text retype" alt="password" title="Confirm Password" required="required">

					    		<input type="submit" class="button round" value="Register" title="Register" onClick="javascript:void(0);">

					</form>

<?php include_once('footer.php'); ?>


text:
class SessionsController < BaseController
  if AppConfig.closed_beta_mode
    skip_before_filter :beta_login_required
  end

  def index
    redirect_to :action => "new"
  end

  def new
    redirect_to user_path(current_user) and return if current_user
    @user_session = UserSession.new
    render :layout => 'beta' if AppConfig.closed_beta_mode
  end

  def create
    @user_session = UserSession.new(:login => params[:login], :password => params[:password], :remember_me => params[:remember_me])

    if @user_session.save

      current_user = @user_session.record #if current_user has been called before this, it will ne nil, so we have to make to reset it

      flash[:notice] = :thanks_youre_now_logged_in.l
      redirect_back_or_default(dashboard_user_path(current_user))
    else
      flash[:notice] = :uh_oh_we_couldnt_log_you_in_with_the_username_and_password_you_entered_try_again.l
      redirect_to teaser_path and return if AppConfig.closed_beta_mode
      render :action => :new
    end
  end

  def destroy
    current_user_session.destroy
    flash[:notice] = :youve_been_logged_out_hope_you_come_back_soon.l
    redirect_to new_session_path
  end

end


text:
      <!DOCTYPE html>
      <html>
      <head>
      <link rel="canonical" href="/This-Blog-Now-With-HTML5.html"/>
      <meta http-equiv="content-type" content="text/html; charset=utf-8" />
      <meta http-equiv="refresh" content="0;url=/This-Blog-Now-With-HTML5.html" />
      </head>
      </html>


text:
<?php

namespace kalibao\frontend\components\web;

use kalibao\common\components\web\AssetBundle;

/**
 * Class BootstrapAsset provide an asset bundle containing bootstrap resources
 *
 * @package kalibao\frontend\components\web
 * @version 1.0
 * @author Kevin Walter <walkev13@gmail.com>
 */
class BootstrapAsset extends AssetBundle
{
    /**
     * @inheritdoc
     */
    public $publishOptions = [
        //'forceCopy' => YII_ENV_DEV
    ];

    /**
     * @inheritdoc
     */
    public $depends = [
        'yii\web\JqueryAsset',
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'yii\bootstrap\BootstrapPluginAsset',
        'yii\widgets\ActiveFormAsset',
        'yii\validators\ValidationAsset',
        'yii\captcha\CaptchaAsset',
        'kalibao\frontend\components\web\AppAsset',
    ];
}


text:
# Require Guarding for-in (guard-for-in)

Looping over objects with a `for in` loop will include properties that are inherited through the prototype chain. This behavior can lead to unexpected items in your for loop.

```js
for (key in foo) {
    doSomething(key);
}
```

Note that simply checking `foo.hasOwnProperty(key)` is likely to cause an error in some cases; see [no-prototype-builtins](no-prototype-builtins.md).

## Rule Details

This rule is aimed at preventing unexpected behavior that could arise from using a `for in` loop without filtering the results in the loop. As such, it will warn when `for in` loops do not filter their results with an `if` statement.

Examples of **incorrect** code for this rule:

```js
/*eslint guard-for-in: "error"*/

for (key in foo) {
    doSomething(key);
}
```

Examples of **correct** code for this rule:

```js
/*eslint guard-for-in: "error"*/

for (key in foo) {
    if (Object.prototype.hasOwnProperty.call(foo, key)) {
        doSomething(key);
    }
    if ({}.hasOwnProperty.call(foo, key)) {
        doSomething(key);
    }
}
```

## Related Rules

* [no-prototype-builtins](no-prototype-builtins.md)

## Further Reading

* [Exploring JavaScript for-in loops](http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/)
* [The pitfalls of using objects as maps in JavaScript](http://www.2ality.com/2012/01/objects-as-maps.html)


text:
class EventHandler
{
    private _eventListeners: { [id: string]: Array<((data?: any) => void)> } = {};

    public On(event: string, handler: (data?: any) => void): void
    {
        this.Off(event, handler);

        if (this._eventListeners[event] === undefined || this._eventListeners[event] == null) {
            this._eventListeners[event] = [];
        }

        this._eventListeners[event].push(handler);
    }

    public Off(event: string, handler: (data?: any) => void): void
    {
        if (this._eventListeners[event] != undefined && this._eventListeners[event] != null) {
            this._eventListeners[event] = this._eventListeners[event].filter(e => e !== handler);
        }
    }

    public Trigger(event: string, data?: any): void
    {
        if (this._eventListeners[event] !== undefined || this._eventListeners[event] != null && this._eventListeners[event].length > 0) {
            for (var handler of this._eventListeners[event]) {
                handler(data);
            }
        }
    }
}


text:
    <link rel="stylesheet"
          href="https://du11hjcvx0uqb.cloudfront.net/dist/brandable_css/289606ed00d3518a0ed0dc2afd44d6f0/new_styles_normal_contrast/bundles/common-bc0cf2950d.css"/>
    <link rel="stylesheet"
          href="https://du11hjcvx0uqb.cloudfront.net/dist/brandable_css/289606ed00d3518a0ed0dc2afd44d6f0/new_styles_normal_contrast/bundles/dashboard-c42271f6c4.css"/>
    <link rel="stylesheet"
          href="https://du11hjcvx0uqb.cloudfront.net/dist/brandable_css/289606ed00d3518a0ed0dc2afd44d6f0/new_styles_normal_contrast/bundles/dashboard_card-ef8fe1913e.css"/>
    <link rel="stylesheet"
          href="https://instructure-uploads.s3.amazonaws.com/account_190000000088968/attachments/71158649/new_ui_override.css?AWSAccessKeyId=AKIAJFNFXH2V2O7RPCAA&Expires=1945583226&Signature=CWzLFjL0BA2oRCgkWNfKoQSeVJ8%3D&response-cache-control=Cache-Control%3Amax-age%3D473364000.0%2C%20public&response-expires=473364000.0"/>
    <link rel="stylesheet"
          href="https://du11hjcvx0uqb.cloudfront.net/dist/brandable_css/289606ed00d3518a0ed0dc2afd44d6f0/new_styles_normal_contrast/bundles/common-bc0cf2950d.css"/>
    <link rel="stylesheet"
          href="https://du11hjcvx0uqb.cloudfront.net/dist/brandable_css/no_variables/jst/tinymce/InsertUpdateImageView-576a8e7d68.css"/>
    <link rel="stylesheet"
          href="https://du11hjcvx0uqb.cloudfront.net/dist/brandable_css/289606ed00d3518a0ed0dc2afd44d6f0/new_styles_normal_contrast/jst/TreeBrowser-4d31810d2d.css"/>
    <link rel="stylesheet"
          href="https://du11hjcvx0uqb.cloudfront.net/dist/brandable_css/289606ed00d3518a0ed0dc2afd44d6f0/new_styles_normal_contrast/jst/FindFlickrImageView-3605dd74b1.css"/>

    <link rel="stylesheet" href="InstructureIcons-Line.css"/>

Please Read!

First time setup

We need to know how your school talks to Canvas.

We also need your permission to talk to Canvas.

On the next page please check 'Stay signed in'!

After you see your grades start to load
 please close and reopen this window.

Please enter your school's Canvas url:

TCNJ's is provided as an example...

    <form>
        <input id="url" type="text" value="tcnj.instructure.com">

        <button id="login-submit">Submit</button>
    </form>

Thanks, loading Canvas...


text:
<!doctype html>

<meta charset="utf-8">
<link href="layout.css" charset="utf-8" type="text/css" rel="stylesheet"></link>
<title>SDL_RenderTargetSupported</title>

SDL_RenderTargetSupported

Use this function to determine whether a window supports the use of render targets.

Syntax

SDL_bool SDL_RenderTargetSupported(SDL_Renderer* renderer)

Function Parameters

renderer	the renderer that will be checked

Return Value

Returns SDL_TRUE if supported or SDL_FALSE if not.

Code Examples

Remarks

Version

This function is available since SDL 2.0.0.

Related Functions

SDL_SetRenderTarget


text:
[Загрузите](https://github.com/gameisch/hextobase64/blob/master/app/scripts/htob64.min.js) или скопируйте этот репозиторий в свое приложение.
Копипаст в <html> <script src="https://github.com/gameisch/hextobase64/blob/master/app/scripts/htob64.min.js"></script>

- https://github.com/gameisch/hextobase64/blob/master/app/scripts/htob64.min.js
- не минимизированная версия https://github.com/gameisch/hextobase64/blob/master/app/scripts/HToB64.js

Либа позволяет кодировать и декодировать различные системы счисления в Base64 и обратно.
Демонстрацию можно посмотреть здесь:
[htob64 demo](http://htob64.gameisch.lclients.ru/app/index.html)

фронтэнд создан с помощью web starter kit, далее документация о нем.

### [![Web Starter Kit](https://cloud.githubusercontent.com/assets/110953/11445049/f05512ba-9520-11e5-8fdb-8c8eb5f690d0.jpg)](https://github.com/google/web-starter-kit/releases/latest)

## Overview

[Web Starter Kit](https://developers.google.com/web/starter-kit) is an opinionated boilerplate for web development. Tools for building a great experience across many devices and [performance oriented](#web-performance). Helping you to stay productive following the best practices outlined in Google's [Web Fundamentals](https://developers.google.com/web/fundamentals). A solid starting point for both professionals and newcomers to the industry.

### Features

| Feature                                | Summary                                                                                |
|----------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Responsive boilerplate | A responsive boilerplate optimized for the multi-screen web. Powered by [Material Design Lite](http://getmdl.io).  You're free to use either this or a completely clean-slate  via [basic.html](https://github.com/google/web-starter-kit/blob/master/app/basic.html).                          |
| Sass support                           | Compile [Sass](http://sass-lang.com/) into CSS with ease, bringing support for variables, mixins and more. (Run `gulp serve` or `gulp` for production)                                                                                |
| Performance optimization               | Minify and concatenate JavaScript, CSS, HTML and images to help keep your pages lean. (Run `gulp` to create an optimised version of your project to `/dist`)                                                                                |
| Code Linting               | JavaScript code linting is done using [ESLint](http://eslint.org) - a pluggable linter tool for identifying and reporting on patterns in JavaScript. Web Starter Kit uses ESLint with [eslint-config-google](https://github.com/google/eslint-config-google), which tries to follow the Google JavaScript style guide.                                                                                |
| ES2015 via Babel 6.0                   | Optional ES2015 support using [Babel](https://babeljs.io/). To enable ES2015 support remove the line `"only": "gulpfile.babel.js",` in the [.babelrc](.babelrc) file. ES2015 source code will be automatically transpiled to ES5 for wide browser support.  |
| Built-in HTTP Server                   | A built-in server for previewing your site locally while you develop and iterate                                                                                |
| Live Browser Reloading                 | Reload the browser in real-time anytime an edit is made without the need for an extension. (Run `gulp serve` and edit your files)                                                                                |
| Cross-device Synchronization           | Synchronize clicks, scrolls, forms and live-reload across multiple devices as you edit your project. Powered by [BrowserSync](http://browsersync.io). (Run `gulp serve` and open up the IP provided on other devices on your network)                       |
| Offline support                     | Thanks to our baked in [Service Worker](http://www.html5rocks.com/en/tutorials/service-worker/introduction/) [pre-caching](https://github.com/google/web-starter-kit/blob/master/gulpfile.babel.js#L226), sites deploying `dist` to a HTTPS domain will enjoy offline support. This is made possible by [sw-precache](https://github.com/GoogleChrome/sw-precache/).                                                                                |
| PageSpeed Insights                     | Web performance metrics showing how well your site performs on mobile and desktop (Run `gulp pagespeed`)                                                                                |

## Quickstart

[Download](https://github.com/google/web-starter-kit/releases/latest) the kit or clone this repository and build on what is included in the `app` directory.

There are two HTML starting points, from which you can choose:

- `index.html` - the default starting point, containing Material Design layout.
- `basic.html` - no layout, but still includes our minimal mobile best-practices

Be sure to look over the [installation docs](docs/install.md) to verify your environment is prepared to run WSK.
Once you have verified that your system can run WSK, check out the [commands](docs/commands.md) available to get started.

## Web Performance

Web Starter Kit strives to give you a high performance starting point out of the box. Our median Web Page Test [scores](http://www.webpagetest.org/result/151201_VW_XYC/) for the default template have a [Speed Index](https://sites.google.com/a/webpagetest.org/docs/using-webpagetest/metrics/speed-index) of ~1100 (1000 is ideal) and a repeat-visit Speed Index of ~550 thanks to Service Worker precaching.

## Browser Support

At present, we officially aim to support the last two versions of the following browsers:

* Chrome
* Edge
* Firefox
* Safari
* Opera
* Internet Explorer 9+

This is not to say that Web Starter Kit cannot be used in browsers older than those reflected, but merely that our focus will be on ensuring our layouts work great in the above.

## Troubleshooting

If you find yourself running into issues during installation or running the tools, please check our [Troubleshooting](https://github.com/google/web-starter-kit/wiki/Troubleshooting) guide and then open an [issue](https://github.com/google/web-starter-kit/issues). We would be happy to discuss how they can be solved.

## A Boilerplate-only Option

If you would prefer not to use any of our tooling, delete the following files from the project: `package.json`, `gulpfile.babel.js`, `.jshintrc` and `.travis.yml`. You can now safely use the boilerplate with an alternative build-system or no build-system at all if you choose.

## Docs and Recipes

* [File Appendix](https://github.com/google/web-starter-kit/blob/master/docs/file-appendix.md) - What do the different files here do?
* [Using Material Design Lite's Sass](https://github.com/google/web-starter-kit/blob/master/docs/mdl-sass.md) - how to get MDL's Sass working with WSK
* [Deployment guides](https://github.com/google/web-starter-kit/blob/master/docs/deploy.md) - available for Firebase, Google App Engine and other services.
* [Gulp recipes](https://github.com/gulpjs/gulp/tree/master/docs/recipes) - the official Gulp recipes directory includes a comprehensive list of guides for different workflows you can add to your project.

## Inspiration

Web Starter Kit is inspired by [Mobile HTML5 Boilerplate](http://html5boilerplate.com/mobile/) and Yeoman's [generator-gulp-webapp](https://github.com/yeoman/generator-gulp-webapp), having taken input from contributors to both projects during development. Our [FAQs](https://github.com/google/web-starter-kit/wiki/FAQ) attempt to answer commonly asked questions about the project.

## Contributing

Contributions, questions and comments are all welcome and encouraged. For code contributions to Web Starter Kit, please see our [Contribution guide](CONTRIBUTING.md) before submitting a pull request. [Website](https://developers.google.com/web/starter-kit/) related issues should be filed on the [Web Fundamentals](https://github.com/google/WebFundamentals/issues/new) issue tracker.

## License

Apache 2.0
Copyright 2015 Google Inc
# hextobase64


text:
.. _vSphere API 4.0: ../../vim/version.rst#vimversionversion5

.. _vim.event.HostEvent: ../../vim/event/HostEvent.rst

vim.event.HostUserWorldSwapNotEnabledEvent
==========================================
  This event records that the userworld swap is not enabled on the host. HA needs userworld swap to be configured on embedded ESX hosts to function.
:extends: vim.event.HostEvent_
:since: `vSphere API 4.0`_
**deprecated**

Attributes:


text:
module CloudModel
  module Workers
    class FirewallWorker < BaseWorker
      def initialize(host)
        @host = host

        host_services = {
          'ssh' => {
            'port' => 22
          },
          'tinc-tcp' => {
            'port' => 655,
            'proto' => 'tcp'
          },
          'tinc-udp' => {
            'port' => 655,
            'proto' => 'udp'
          }
        }

        rules = {
          @host.primary_address.ip  => {
            'interface' => 'eth0',
            'services' => host_services
          }
        }

        @host.addresses.each do |address|
          if address.ip_version == 6
            rules["#{address.ip}2"] = {
              'interface' => 'eth0',
              'services' => host_services
            }
          else
            address.list_ips.each do |ip|
              rules[ip] = {
                'interface' => 'eth0',
                'services' => {}
              }

              if guest = @host.guests.where(external_address: ip).first
                rules[ip]['nat'] = guest.private_address

                services = guest.services.where(public_service: true).to_a
                services.each do |service|
                  rules[ip]['services']["#{service.kind}"] ||= {}
                  rules[ip]['services']["#{service.kind}"]['port'] ||= []
                  rules[ip]['services']["#{service.kind}"]['port'] << service.port

                  if service.try :ssl_port and service.try :ssl_supported
                    rules[ip]['services']["#{service.kind}s"] ||= {}
                    rules[ip]['services']["#{service.kind}s"]['port'] ||= []
                    rules[ip]['services']["#{service.kind}s"]['port'] << service.ssl_port
                  end
                end
              end
            end
          end
        end
        @rules = rules
      end

      def ssh_deep_inspect?
        false
      end

      def parse_ports(ports)
        if ports.class == Integer
          [ports]
        elsif ports.class == String
          ports.split(' ')#.map{|p| p.to_i}
        else
          ports
        end
      end

      def ip4tables_bin
        '/sbin/iptables'
      end

      def ip6tables_bin
        '/sbin/ip6tables'
      end

      def iptables_bin(host)
        if host.match /^\d+\.\d+\.\d+\.\d+$/
          ip4tables_bin
        else
          ip6tables_bin
        end
      end

      def iptables_bins
        [ip4tables_bin, ip6tables_bin]
      end

      def handle_ssh(host, options)
        commands = []
        ports = options[:port]
        iptables = iptables_bin(host)
        interface = options[:interface] || 'eth0'

        if !ssh_deep_inspect?
          unless @ssh_init_done ||= [] and @ssh_init_done.include? iptables
            commands << "#{iptables} -N SSH_ATTACKED"
            commands << "#{iptables} -A SSH_ATTACKED -m recent --name SSH_brutes --set -j LOG --log-level 4 --log-prefix 'SSH attack: '"
            commands << "#{iptables} -A SSH_ATTACKED -j REJECT"
            @ssh_init_done << iptables
          end
        end

        ports.each do |port|
          if(options[:trust])
            parse_ports(options[:trust]).each do |s|
              #commands << "#{iptables} -A INPUT -i #{interface} -m conntrack --ctstate NEW -p tcp -s #{s} -d #{host} --dport #{port} -j ACCEPT"
              commands << "#{iptables} -A INPUT -m conntrack --ctstate NEW -p tcp -s #{s} -d #{host} --dport #{port} -j ACCEPT"
            end
          end

          if ssh_deep_inspect?
            # Capture SSH connections
            commands << "#{iptables} -A INPUT -i #{interface} -m conntrack --ctstate NEW -p tcp -d #{host} --dport #{port} -j SSH_CHECK"
          else
            commands << "#{iptables} -A INPUT -i #{interface} -p tcp -d #{host} --dport #{port} ! --syn -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT"
            commands << "#{iptables} -A INPUT -i #{interface} -p tcp -d #{host} --dport #{port} --syn -m recent --name SSH_brutes --update --seconds 20 -j REJECT"
            commands << "#{iptables} -A INPUT -i #{interface} -p tcp -d #{host} --dport #{port} --syn -m recent --name sshconn --update --seconds 60 --hitcount 6 -j SSH_ATTACKED"
            commands << "#{iptables} -A INPUT -i #{interface} -p tcp -d #{host} --dport #{port} --syn -m recent --name sshconn --set"
            commands << "#{iptables} -A INPUT -i #{interface} -p tcp -d #{host} --dport #{port} --syn -j ACCEPT"
          end

          if(options[:nat])
             commands += nat(host, interface, port, 'tcp', options[:nat])
          end
        end

        commands
      end

      def masq_private(options)
        commands = []

        @host.addresses.each do |address|
          commands << "#{ip4tables_bin} -I FORWARD -o lxdbr0 -d #{address.to_s} -j ACCEPT"
        end

        @host.guests.where(:external_address.exists => true).each do |guest|
          unless guest.external_address.blank?
            #commands << "#{ip4tables_bin} -t nat -A POSTROUTING -s #{guest.private_address} ! -d #{tinc_network} -j SNAT --to-source #{guest.external_address}"
            #commands << "#{ip4tables_bin} -t nat -A POSTROUTING -o eth0 -s #{guest.private_address} -j SNAT --to-source #{guest.external_address}"
            #commands << "#{ip4tables_bin} -t nat -A POSTROUTING -d #{guest.private_address} -j SNAT --to-source #{guest.external_address}"

            commands << "#{ip4tables_bin} -t nat -A POSTROUTING -o eth0 -s #{guest.private_address} -j SNAT --to #{guest.external_address}"
            commands << "#{ip4tables_bin} -t nat -A POSTROUTING -o lxdbr0 -s #{guest.private_address} -j SNAT --to #{guest.external_address}"
          end
        end

        # Handle multicast
        commands << "#{ip4tables_bin} -t nat -A POSTROUTING -s #{@host.private_network} -d 224.0.0.0/24 -j RETURN"
        # Handle broadcast
        commands << "#{ip4tables_bin} -t nat -A POSTROUTING -s #{@host.private_network} -d 255.255.255.255/32 -j RETURN"
        # Masquerading
        commands << "#{ip4tables_bin} -t nat -A POSTROUTING -s #{@host.private_network} ! -d #{@host.private_network.tinc_network}/#{@host.private_network.tinc_subnet} -p tcp -j MASQUERADE --to-ports 1024-65535"
        commands << "#{ip4tables_bin} -t nat -A POSTROUTING -s #{@host.private_network} ! -d #{@host.private_network.tinc_network}/#{@host.private_network.tinc_subnet} -p udp -j MASQUERADE --to-ports 1024-65535"
        commands << "#{ip4tables_bin} -t nat -A POSTROUTING -s #{@host.private_network} ! -d #{@host.private_network.tinc_network}/#{@host.private_network.tinc_subnet} -j MASQUERADE"
        # # Local forward
        # commands << "#{ip4tables_bin} -A FORWARD -o lxdbr0 -m state --state RELATED,ESTABLISHED -j ACCEPT"
        # commands << "#{ip4tables_bin} -A FORWARD -i lxdbr0 -o eth0 -j ACCEPT"
        # commands << "#{ip4tables_bin} -A FORWARD -i lxdbr0 -o lo -j ACCEPT"
      end

      def nat(host, interface, port, proto, nat_host)
        iptables = iptables_bin(host)

        commands = []

        # nat external request
        commands << "#{iptables} -t nat -A PREROUTING -p #{proto} -d #{host} --dport #{port} -j DNAT --to-destination #{nat_host}:#{port}"
        # nat request from host
        commands << "#{iptables} -t nat -A OUTPUT -p #{proto} -o lo -d #{host} --dport #{port} -j DNAT --to #{nat_host}:#{port}"
        # nat request from bridge
        commands << "#{iptables} -t nat -A OUTPUT -p #{proto} -o lxdbr0 -d #{host} --dport #{port} -j DNAT --to #{nat_host}:#{port}"
        # postrouting
        #commands << "#{iptables} -t nat -A POSTROUTING -p #{proto} -s #{host} --sport #{port} -j MASQUERADE"
        #commands << "#{iptables} -t nat -A POSTROUTING -s #{nat_host} -j SNAT --to #{host}"

        commands
      end

      def build_commands(host, host_options, protocol, rule_options)
        options = host_options.merge rule_options

        if protocol == :ssh
          commands = handle_ssh(host, options)
        else
          iptables = iptables_bin(host)
          interface = options[:interface] || 'eth0'
          proto = options[:proto] || 'tcp'

          commands = ["#{iptables} -A INPUT -i #{interface} -m conntrack --ctstate NEW -p #{proto}"]
          #commands = ["#{iptables} -A INPUT -m conntrack --ctstate NEW -p #{proto}"]

          if options[:shost] and options[:shost] != 'any'
            cmds = []
            commands.each do |c|
              cmds << "#{c} -s #{options[:shost]}"
            end
            commands = cmds
          end

          if options[:sport] and options[:sport] != 'any'
            cmds = []
            commands.each do |c|
              cmds << "#{c} --sport #{options[:sport]}"
            end
            commands = cmds
          end

          cmds = []
          commands.each do |c|
            cmds << "#{c} -d #{host}"
          end
          commands = cmds

          if options[:port] and options[:port] != 'any'
            cmds = []
            commands.each do |c|
              options[:port].each do |p|
                cmds << "#{c} --dport #{p}"
              end
            end
            commands = cmds
          end

          commands.map!{|c| "#{c} -j ACCEPT"}

          if options[:port] and options[:nat]
            options[:port].each do |port|
              commands += nat(host, interface, port, proto, options[:nat])
            end
          end
        end

        commands
      end

      def shebang
        "#!/bin/sh\n"
      end

      def stop_script(options = {})
        commands = []
        iptables_bins.each do |iptables|
          # ['-F', '-t nat -F'].each do |attrs|
          ['-F', '-t nat -F'].each do |attrs|
            commands << "#{iptables} #{attrs} || echo 'Warning: Cannot succeed #{iptables} #{attrs}'"
          end

          if ssh_deep_inspect?
            ['-X SSH_ATTACKED', '-X SSH_CHECK'].each do |attrs|
              commands << "#{iptables} #{attrs} || echo 'Failed to run: #{iptables} #{attrs}'"
            end
          else
            commands << "#{iptables} -X SSH_ATTACKED || echo 'Warning: Cannot undefine SSH_ATTACKED for #{iptables}'"
          end
        end
        commands * "\n"
      end

      def list_script(options = {})
        commands = []
        iptables_bins.each do |iptables|
          commands << "echo"
          commands << "echo 'List rules for #{iptables}'"
          commands << "echo"

          commands << "#{iptables} -L"
          commands << "#{iptables} -t nat -L"
        end
        commands * "\n"
      end

      def start_script(options = {})
        commands = []
        interfaces = []

        commands << "#{ip4tables_bin} -A FORWARD -i lxdbr0 -j ACCEPT"
        commands << "#{ip4tables_bin} -A FORWARD -o lxdbr0 -j ACCEPT"

        if ssh_deep_inspect?
          # Create SSH attack chains
          iptables_bins.each do |iptables|
            commands << "#{iptables} -N SSH_CHECK"
            commands << "#{iptables} -N SSH_ATTACKED"
          end
        end

        # Implement rules
        @rules.each do |host, host_options|
          host_options = host_options.clone
          host_options.keys.each do |key|
            host_options[(key.to_sym rescue key) || key] = host_options.delete(key)
          end

          interfaces << host_options[:interface] || 'eth0'

          if services = host_options.delete(:services)
            services.each do |protocol, config|
              parsed = if [Integer, String].include? config.class
                {port: parse_ports(config)}
              else
                config.keys.each do |key|
                  config[(key.to_sym rescue key) || key] = config.delete(key)
                end
                config[:port] = parse_ports config[:port]
                config
              end

              commands += build_commands(host, host_options, protocol.to_sym, parsed)
            end
          end
        end

        @host.firewall_rules.each do |rule|
          commands += nat(rule.source_ip, '', rule.source_port, rule.protocol, rule.target_ip)
        end

        if ssh_deep_inspect?
          iptables_bins.each do |iptables|
            # Define SSH_CHECK chain
            commands << "#{iptables} -A SSH_CHECK -m recent --set --name SSH"
            commands << "#{iptables} -A SSH_CHECK -m recent --update --seconds 60 --hitcount 4 --rttl --name SSH -j SSH_ATTACKED"
            # Define SSH_ATTACKED chain
            commands << "#{iptables} -A SSH_ATTACKED -j LOG --log-prefix 'SSH attack: ' --log-level 7"
            commands << "#{iptables} -A SSH_ATTACKED -j REJECT"
          end
        end

        commands += masq_private(options)

        interfaces.uniq.each do |interface|
          iptables_bins.each do |iptables|
            %w(tcp udp).each do |proto|
              commands << "#{iptables} -A INPUT -i #{interface} -m conntrack --ctstate NEW -p #{proto} -j REJECT"
            end
          end

          # Block ICMP timestamp requests on IPv4
          commands << "#{ip4tables_bin} -A INPUT -i #{interface} -p icmp --icmp-type timestamp-request -j DROP"
          commands << "#{ip4tables_bin} -A OUTPUT -o #{interface} -p icmp --icmp-type timestamp-reply -j DROP"
        end

        commands * "\n"

        #commands.map{|c| "echo '#{c}'\n#{c}"} * "\n"
      end

      def write_scripts options = {root: ''}
        root = options[:root] || ''
        mkdir_p "#{root}/etc/cloud_model/"
        @host.sftp.file.open("#{root}/etc/cloud_model/firewall_start", 'w', 0700) do |f|
          f.puts shebang + start_script(options)
        end
        @host.sftp.file.open("#{root}/etc/cloud_model/firewall_stop", 'w', 0700) do |f|
          f.puts shebang + stop_script(options)
        end
        @host.sftp.file.open("#{root}/etc/cloud_model/firewall_list", 'w', 0700) do |f|
          f.puts shebang + list_script(options)
        end

        true
      end
    end
  end
end


text:
verify_stack_after_op = False

#  ######################################
import copy
from ethereum import utils
from ethereum import opcodes
from ethereum.slogging import get_logger
from rlp.utils import encode_hex, ascii_chr
from ethereum.utils import to_string

log_log = get_logger('eth.vm.log')
log_vm_exit = get_logger('eth.vm.exit')
log_vm_op = get_logger('eth.vm.op')
log_vm_op_stack = get_logger('eth.vm.op.stack')
log_vm_op_memory = get_logger('eth.vm.op.memory')
log_vm_op_storage = get_logger('eth.vm.op.storage')

TT256 = 2 ** 256
TT256M1 = 2 ** 256 - 1
TT255 = 2 ** 255

class CallData(object):

    def __init__(self, parent_memory, offset=0, size=None):
        self.data = parent_memory
        self.offset = offset
        self.size = len(self.data) if size is None else size
        self.rlimit = self.offset + self.size

    def extract_all(self):
        d = self.data[self.offset: self.offset + self.size]
        d += [0] * (self.size - len(d))
        return b''.join([ascii_chr(x) for x in d])

    def extract32(self, i):
        if i >= self.size:
            return 0
        o = self.data[self.offset + i: min(self.offset + i + 32, self.rlimit)]
        return utils.bytearray_to_int(o + [0] * (32 - len(o)))

    def extract_copy(self, mem, memstart, datastart, size):
        for i in range(size):
            if datastart + i < self.size:
                mem[memstart + i] = self.data[self.offset + datastart + i]
            else:
                mem[memstart + i] = 0

class Message(object):

    def __init__(self, sender, to, value, gas, data, depth=0,
            code_address=None, is_create=False, transfers_value=True):
        self.sender = sender
        self.to = to
        self.value = value
        self.gas = gas
        self.data = data
        self.depth = depth
        self.logs = []
        self.code_address = code_address
        self.is_create = is_create
        self.transfers_value = transfers_value

    def __repr__(self):
        return '<Message(to:%s...)>' % self.to[:8]

class Compustate():

    def __init__(self, **kwargs):
        self.memory = []
        self.stack = []
        self.pc = 0
        self.gas = 0
        for kw in kwargs:
            setattr(self, kw, kwargs[kw])

# Preprocesses code, and determines which locations are in the middle
# of pushdata and thus invalid
def preprocess_code(code):
    assert isinstance(code, bytes)
    code = memoryview(code).tolist()
    ops = []
    i = 0
    while i < len(code):
        o = copy.copy(opcodes.opcodes.get(code[i], ['INVALID', 0, 0, 0]) + [code[i], 0])
        ops.append(o)
        if o[0][:4] == 'PUSH':
            for j in range(int(o[0][4:])):
                i += 1
                byte = code[i] if i < len(code) else 0
                o[-1] = (o[-1] << 8) + byte
                if i < len(code):
                    ops.append(['INVALID', 0, 0, 0, byte, 0])
        i += 1
    return ops

def mem_extend(mem, compustate, op, start, sz):
    if sz:
        oldsize = len(mem) // 32
        old_totalfee = oldsize * opcodes.GMEMORY + \
            oldsize ** 2 // opcodes.GQUADRATICMEMDENOM
        newsize = utils.ceil32(start + sz) // 32
        # if newsize > 524288:
        #     raise Exception("Memory above 16 MB per call not supported by this VM")
        new_totalfee = newsize * opcodes.GMEMORY + \
            newsize ** 2 // opcodes.GQUADRATICMEMDENOM
        if old_totalfee < new_totalfee:
            memfee = new_totalfee - old_totalfee
            if compustate.gas < memfee:
                compustate.gas = 0
                return False
            compustate.gas -= memfee
            m_extend = (newsize - oldsize) * 32
            mem.extend([0] * m_extend)
    return True

def data_copy(compustate, size):
    if size:
        copyfee = opcodes.GCOPY * utils.ceil32(size) // 32
        if compustate.gas < copyfee:
            compustate.gas = 0
            return False
        compustate.gas -= copyfee
    return True

def eat_gas(compustate, amount):
    if compustate.gas < amount:
        compustate.gas = 0
        return False
    else:
        compustate.gas -= amount
        return True

def max_call_gas(gas):
    """Since EIP150 CALLs will send only all but 1/64th of the available gas.
    """
    return gas - (gas // opcodes.CALL_CHILD_LIMIT_DENOM)

def vm_exception(error, **kargs):
    log_vm_exit.trace('EXCEPTION', cause=error, **kargs)
    return 0, 0, []

def peaceful_exit(cause, gas, data, **kargs):
    log_vm_exit.trace('EXIT', cause=cause, **kargs)
    return 1, gas, data

code_cache = {}

def vm_execute(ext, msg, code):
    # precompute trace flag
    # if we trace vm, we're in slow mode anyway
    trace_vm = log_vm_op.is_active('trace')

    compustate = Compustate(gas=msg.gas)
    stk = compustate.stack
    mem = compustate.memory

    if code in code_cache:
        processed_code = code_cache[code]
    else:
        processed_code = preprocess_code(code)
        code_cache[code] = processed_code

    codelen = len(processed_code)

    op = None
    steps = 0
    _prevop = None  # for trace only

    while 1:
        # stack size limit error
        if compustate.pc >= codelen:
            return peaceful_exit('CODE OUT OF RANGE', compustate.gas, [])

        op, in_args, out_args, fee, opcode, pushval = \
            processed_code[compustate.pc]

        # out of gas error
        if fee > compustate.gas:
            return vm_exception('OUT OF GAS')

        # empty stack error
        if in_args > len(compustate.stack):
            return vm_exception('INSUFFICIENT STACK',
                                op=op, needed=to_string(in_args),
                                available=to_string(len(compustate.stack)))

        if len(compustate.stack) - in_args + out_args > 1024:
            return vm_exception('STACK SIZE LIMIT EXCEEDED',
                                op=op,
                                pre_height=to_string(len(compustate.stack)))

        # Apply operation
        compustate.gas -= fee
        compustate.pc += 1

        if trace_vm:
            """
            This diverges from normal logging, as we use the logging namespace
            only to decide which features get logged in 'eth.vm.op'
            i.e. tracing can not be activated by activating a sub
            like 'eth.vm.op.stack'
            """
            trace_data = {}
            trace_data['stack'] = list(map(to_string, list(compustate.stack)))
            if _prevop in ('MLOAD', 'MSTORE', 'MSTORE8', 'SHA3', 'CALL',
                           'CALLCODE', 'CREATE', 'CALLDATACOPY', 'CODECOPY',
                           'EXTCODECOPY'):
                if len(compustate.memory) < 1024:
                    trace_data['memory'] = \
                        b''.join([encode_hex(ascii_chr(x)) for x
                                  in compustate.memory])
                else:
                    trace_data['sha3memory'] = \
                        encode_hex(utils.sha3(''.join([ascii_chr(x) for
                                              x in compustate.memory])))
            if _prevop in ('SSTORE', 'SLOAD') or steps == 0:
                trace_data['storage'] = ext.log_storage(msg.to)
            trace_data['gas'] = to_string(compustate.gas + fee)
            trace_data['inst'] = opcode
            trace_data['pc'] = to_string(compustate.pc - 1)
            if steps == 0:
                trace_data['depth'] = msg.depth
                trace_data['address'] = msg.to
            trace_data['op'] = op
            trace_data['steps'] = steps
            if op[:4] == 'PUSH':
                trace_data['pushvalue'] = pushval
            log_vm_op.trace('vm', **trace_data)
            steps += 1
            _prevop = op

        # Invalid operation
        if op == 'INVALID':
            return vm_exception('INVALID OP', opcode=opcode)

        # Valid operations
        if opcode < 0x10:
            if op == 'STOP':
                return peaceful_exit('STOP', compustate.gas, [])
            elif op == 'ADD':
                stk.append((stk.pop() + stk.pop()) & TT256M1)
            elif op == 'SUB':
                stk.append((stk.pop() - stk.pop()) & TT256M1)
            elif op == 'MUL':
                stk.append((stk.pop() * stk.pop()) & TT256M1)
            elif op == 'DIV':
                s0, s1 = stk.pop(), stk.pop()
                stk.append(0 if s1 == 0 else s0 // s1)
            elif op == 'MOD':
                s0, s1 = stk.pop(), stk.pop()
                stk.append(0 if s1 == 0 else s0 % s1)
            elif op == 'SDIV':
                s0, s1 = utils.to_signed(stk.pop()), utils.to_signed(stk.pop())
                stk.append(0 if s1 == 0 else (abs(s0) // abs(s1) *
                                              (-1 if s0 * s1 < 0 else 1)) & TT256M1)
            elif op == 'SMOD':
                s0, s1 = utils.to_signed(stk.pop()), utils.to_signed(stk.pop())
                stk.append(0 if s1 == 0 else (abs(s0) % abs(s1) *
                                              (-1 if s0 < 0 else 1)) & TT256M1)
            elif op == 'ADDMOD':
                s0, s1, s2 = stk.pop(), stk.pop(), stk.pop()
                stk.append((s0 + s1) % s2 if s2 else 0)
            elif op == 'MULMOD':
                s0, s1, s2 = stk.pop(), stk.pop(), stk.pop()
                stk.append((s0 * s1) % s2 if s2 else 0)
            elif op == 'EXP':
                base, exponent = stk.pop(), stk.pop()
                # fee for exponent is dependent on its bytes
                # calc n bytes to represent exponent
                nbytes = len(utils.encode_int(exponent))
                expfee = nbytes * opcodes.GEXPONENTBYTE
                if compustate.gas < expfee:
                    compustate.gas = 0
                    return vm_exception('OOG EXPONENT')
                compustate.gas -= expfee
                stk.append(pow(base, exponent, TT256))
            elif op == 'SIGNEXTEND':
                s0, s1 = stk.pop(), stk.pop()
                if s0 <= 31:
                    testbit = s0 * 8 + 7
                    if s1 & (1 << testbit):
                        stk.append(s1 | (TT256 - (1 << testbit)))
                    else:
                        stk.append(s1 & ((1 << testbit) - 1))
                else:
                    stk.append(s1)
        elif opcode < 0x20:
            if op == 'LT':
                stk.append(1 if stk.pop() < stk.pop() else 0)
            elif op == 'GT':
                stk.append(1 if stk.pop() > stk.pop() else 0)
            elif op == 'SLT':
                s0, s1 = utils.to_signed(stk.pop()), utils.to_signed(stk.pop())
                stk.append(1 if s0 < s1 else 0)
            elif op == 'SGT':
                s0, s1 = utils.to_signed(stk.pop()), utils.to_signed(stk.pop())
                stk.append(1 if s0 > s1 else 0)
            elif op == 'EQ':
                stk.append(1 if stk.pop() == stk.pop() else 0)
            elif op == 'ISZERO':
                stk.append(0 if stk.pop() else 1)
            elif op == 'AND':
                stk.append(stk.pop() & stk.pop())
            elif op == 'OR':
                stk.append(stk.pop() | stk.pop())
            elif op == 'XOR':
                stk.append(stk.pop() ^ stk.pop())
            elif op == 'NOT':
                stk.append(TT256M1 - stk.pop())
            elif op == 'BYTE':
                s0, s1 = stk.pop(), stk.pop()
                if s0 >= 32:
                    stk.append(0)
                else:
                    stk.append((s1 // 256 ** (31 - s0)) % 256)
        elif opcode < 0x40:
            if op == 'SHA3':
                s0, s1 = stk.pop(), stk.pop()
                compustate.gas -= opcodes.GSHA3WORD * (utils.ceil32(s1) // 32)
                if compustate.gas < 0:
                    return vm_exception('OOG PAYING FOR SHA3')
                if not mem_extend(mem, compustate, op, s0, s1):
                    return vm_exception('OOG EXTENDING MEMORY')
                data = b''.join(map(ascii_chr, mem[s0: s0 + s1]))
                stk.append(utils.big_endian_to_int(utils.sha3(data)))
            elif op == 'ADDRESS':
                stk.append(utils.coerce_to_int(msg.to))
            elif op == 'BALANCE':
                # EIP150: Increase the gas cost of BALANCE to 400
                if ext.post_anti_dos_hardfork:
                    if not eat_gas(compustate, opcodes.BALANCE_SUPPLEMENTAL_GAS):
                        return vm_exception("OUT OF GAS")
                addr = utils.coerce_addr_to_hex(stk.pop() % 2 ** 160)
                stk.append(ext.get_balance(addr))
            elif op == 'ORIGIN':
                stk.append(utils.coerce_to_int(ext.tx_origin))
            elif op == 'CALLER':
                stk.append(utils.coerce_to_int(msg.sender))
            elif op == 'CALLVALUE':
                stk.append(msg.value)
            elif op == 'CALLDATALOAD':
                stk.append(msg.data.extract32(stk.pop()))
            elif op == 'CALLDATASIZE':
                stk.append(msg.data.size)
            elif op == 'CALLDATACOPY':
                mstart, dstart, size = stk.pop(), stk.pop(), stk.pop()
                if not mem_extend(mem, compustate, op, mstart, size):
                    return vm_exception('OOG EXTENDING MEMORY')
                if not data_copy(compustate, size):
                    return vm_exception('OOG COPY DATA')
                msg.data.extract_copy(mem, mstart, dstart, size)
            elif op == 'CODESIZE':
                stk.append(len(processed_code))
            elif op == 'CODECOPY':
                start, s1, size = stk.pop(), stk.pop(), stk.pop()
                if not mem_extend(mem, compustate, op, start, size):
                    return vm_exception('OOG EXTENDING MEMORY')
                if not data_copy(compustate, size):
                    return vm_exception('OOG COPY DATA')
                for i in range(size):
                    if s1 + i < len(processed_code):
                        mem[start + i] = processed_code[s1 + i][4]
                    else:
                        mem[start + i] = 0
            elif op == 'GASPRICE':
                stk.append(ext.tx_gasprice)
            elif op == 'EXTCODESIZE':
                # EIP150: Increase the gas cost of EXTCODESIZE to 700
                if ext.post_anti_dos_hardfork:
                    if not eat_gas(compustate, opcodes.EXTCODELOAD_SUPPLEMENTAL_GAS):
                        return vm_exception("OUT OF GAS")
                addr = utils.coerce_addr_to_hex(stk.pop() % 2 ** 160)
                stk.append(len(ext.get_code(addr) or b''))
            elif op == 'EXTCODECOPY':
                # EIP150: Increase the base gas cost of EXTCODECOPY to 700
                if ext.post_anti_dos_hardfork:
                    if not eat_gas(compustate, opcodes.EXTCODELOAD_SUPPLEMENTAL_GAS):
                        return vm_exception("OUT OF GAS")
                addr = utils.coerce_addr_to_hex(stk.pop() % 2 ** 160)
                start, s2, size = stk.pop(), stk.pop(), stk.pop()
                extcode = ext.get_code(addr) or b''
                assert utils.is_string(extcode)
                if not mem_extend(mem, compustate, op, start, size):
                    return vm_exception('OOG EXTENDING MEMORY')
                if not data_copy(compustate, size):
                    return vm_exception('OOG COPY DATA')
                for i in range(size):
                    if s2 + i < len(extcode):
                        mem[start + i] = utils.safe_ord(extcode[s2 + i])
                    else:
                        mem[start + i] = 0
        elif opcode < 0x50:
            if op == 'BLOCKHASH':
                stk.append(utils.big_endian_to_int(ext.block_hash(stk.pop())))
            elif op == 'COINBASE':
                stk.append(utils.big_endian_to_int(ext.block_coinbase))
            elif op == 'TIMESTAMP':
                stk.append(ext.block_timestamp)
            elif op == 'NUMBER':
                stk.append(ext.block_number)
            elif op == 'DIFFICULTY':
                stk.append(ext.block_difficulty)
            elif op == 'GASLIMIT':
                stk.append(ext.block_gas_limit)
        elif opcode < 0x60:
            if op == 'POP':
                stk.pop()
            elif op == 'MLOAD':
                s0 = stk.pop()
                if not mem_extend(mem, compustate, op, s0, 32):
                    return vm_exception('OOG EXTENDING MEMORY')
                data = b''.join(map(ascii_chr, mem[s0: s0 + 32]))
                stk.append(utils.big_endian_to_int(data))
            elif op == 'MSTORE':
                s0, s1 = stk.pop(), stk.pop()
                if not mem_extend(mem, compustate, op, s0, 32):
                    return vm_exception('OOG EXTENDING MEMORY')
                v = s1
                for i in range(31, -1, -1):
                    mem[s0 + i] = v % 256
                    v //= 256
            elif op == 'MSTORE8':
                s0, s1 = stk.pop(), stk.pop()
                if not mem_extend(mem, compustate, op, s0, 1):
                    return vm_exception('OOG EXTENDING MEMORY')
                mem[s0] = s1 % 256
            elif op == 'SLOAD':
                # EIP150: Increase the gas cost of SLOAD to 200
                if ext.post_anti_dos_hardfork:
                    if not eat_gas(compustate, opcodes.SLOAD_SUPPLEMENTAL_GAS):
                        return vm_exception("OUT OF GAS")
                stk.append(ext.get_storage_data(msg.to, stk.pop()))
            elif op == 'SSTORE':
                s0, s1 = stk.pop(), stk.pop()
                if ext.get_storage_data(msg.to, s0):
                    gascost = opcodes.GSTORAGEMOD if s1 else opcodes.GSTORAGEKILL
                    refund = 0 if s1 else opcodes.GSTORAGEREFUND
                else:
                    gascost = opcodes.GSTORAGEADD if s1 else opcodes.GSTORAGEMOD
                    refund = 0
                if compustate.gas < gascost:
                    return vm_exception('OUT OF GAS')
                compustate.gas -= gascost
                ext.add_refund(refund)  # adds neg gascost as a refund if below zero
                ext.set_storage_data(msg.to, s0, s1)
            elif op == 'JUMP':
                compustate.pc = stk.pop()
                opnew = processed_code[compustate.pc][0] if \
                    compustate.pc < len(processed_code) else 'STOP'
                if opnew != 'JUMPDEST':
                    return vm_exception('BAD JUMPDEST')
            elif op == 'JUMPI':
                s0, s1 = stk.pop(), stk.pop()
                if s1:
                    compustate.pc = s0
                    opnew = processed_code[compustate.pc][0] if \
                        compustate.pc < len(processed_code) else 'STOP'
                    if opnew != 'JUMPDEST':
                        return vm_exception('BAD JUMPDEST')
            elif op == 'PC':
                stk.append(compustate.pc - 1)
            elif op == 'MSIZE':
                stk.append(len(mem))
            elif op == 'GAS':
                stk.append(compustate.gas)  # AFTER subtracting cost 1
        elif op[:4] == 'PUSH':
            pushnum = int(op[4:])
            compustate.pc += pushnum
            stk.append(pushval)
        elif op[:3] == 'DUP':
            depth = int(op[3:])
            stk.append(stk[-depth])
        elif op[:4] == 'SWAP':
            depth = int(op[4:])
            temp = stk[-depth - 1]
            stk[-depth - 1] = stk[-1]
            stk[-1] = temp

        elif op[:3] == 'LOG':
            """
            0xa0 ... 0xa4, 32/64/96/128/160 + len(data) gas
            a. Opcodes LOG0...LOG4 are added, takes 2-6 stack arguments
                    MEMSTART MEMSZ (TOPIC1) (TOPIC2) (TOPIC3) (TOPIC4)
            b. Logs are kept track of during tx execution exactly the same way as suicides
               (except as an ordered list, not a set).
               Each log is in the form [address, [topic1, ... ], data] where:
               * address is what the ADDRESS opcode would output
               * data is mem[MEMSTART: MEMSTART + MEMSZ]
               * topics are as provided by the opcode
            c. The ordered list of logs in the transaction are expressed as [log0, log1, ..., logN].
            """
            depth = int(op[3:])
            mstart, msz = stk.pop(), stk.pop()
            topics = [stk.pop() for x in range(depth)]
            compustate.gas -= msz * opcodes.GLOGBYTE
            if not mem_extend(mem, compustate, op, mstart, msz):
                return vm_exception('OOG EXTENDING MEMORY')
            data = b''.join(map(ascii_chr, mem[mstart: mstart + msz]))
            ext.log(msg.to, topics, data)
            log_log.trace('LOG', to=msg.to, topics=topics, data=list(map(utils.safe_ord, data)))
            # print('LOG', msg.to, topics, list(map(ord, data)))

        elif op == 'CREATE':
            value, mstart, msz = stk.pop(), stk.pop(), stk.pop()
            if not mem_extend(mem, compustate, op, mstart, msz):
                return vm_exception('OOG EXTENDING MEMORY')
            if ext.get_balance(msg.to) >= value and msg.depth < 1024:
                cd = CallData(mem, mstart, msz)
                ingas = compustate.gas
                # EIP150(1b) CREATE only provides all but one 64th of the
                # parent gas to the child call
                if ext.post_anti_dos_hardfork:
                    ingas = max_call_gas(ingas)

                create_msg = Message(msg.to, b'', value, ingas, cd, msg.depth + 1)
                o, gas, addr = ext.create(create_msg)
                if o:
                    stk.append(utils.coerce_to_int(addr))
                    compustate.gas -= (ingas - gas)
                else:
                    stk.append(0)
                    compustate.gas -= ingas
            else:
                stk.append(0)
        elif op == 'CALL':
            gas, to, value, meminstart, meminsz, memoutstart, memoutsz = \
                stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop()
            if not mem_extend(mem, compustate, op, meminstart, meminsz) or \
                    not mem_extend(mem, compustate, op, memoutstart, memoutsz):
                return vm_exception('OOG EXTENDING MEMORY')
            to = utils.encode_int(to)
            to = ((b'\x00' * (32 - len(to))) + to)[12:]
            extra_gas = (not ext.account_exists(to)) * opcodes.GCALLNEWACCOUNT + \
                    (value > 0) * opcodes.GCALLVALUETRANSFER + \
                    ext.post_anti_dos_hardfork * opcodes.CALL_SUPPLEMENTAL_GAS
                    # ^ EIP150 Increase the gas cost of CALL to 700

            if ext.post_anti_dos_hardfork:
                # EIP150(1b) if a call asks for more gas than all but one 64th of
                # the maximum allowed amount, call with all but one 64th of the
                # maximum allowed amount of gas
                if compustate.gas < extra_gas:
                    return vm_exception('OUT OF GAS', needed=extra_gas)
                gas = min(gas, max_call_gas(compustate.gas - extra_gas))
            else:
                if compustate.gas < gas + extra_gas:
                    return vm_exception('OUT OF GAS', needed=gas + extra_gas)

            submsg_gas = gas + opcodes.GSTIPEND * (value > 0)
            if ext.get_balance(msg.to) >= value and msg.depth < 1024:
                compustate.gas -= (gas + extra_gas)
                cd = CallData(mem, meminstart, meminsz)
                call_msg = Message(msg.to, to, value, submsg_gas, cd,
                                   msg.depth + 1, code_address=to)
                result, gas, data = ext.msg(call_msg)
                if result == 0:
                    stk.append(0)
                else:
                    stk.append(1)
                    compustate.gas += gas
                    for i in range(min(len(data), memoutsz)):
                        mem[memoutstart + i] = data[i]
            else:
                compustate.gas -= (gas + extra_gas - submsg_gas)
                stk.append(0)
        elif op == 'CALLCODE' or op == 'DELEGATECALL':
            if op == 'CALLCODE':
                gas, to, value, meminstart, meminsz, memoutstart, memoutsz = \
                    stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop()
            else:
                gas, to, meminstart, meminsz, memoutstart, memoutsz = \
                    stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop()
                value = 0
            if not mem_extend(mem, compustate, op, meminstart, meminsz) or \
                    not mem_extend(mem, compustate, op, memoutstart, memoutsz):
                return vm_exception('OOG EXTENDING MEMORY')
            extra_gas = (value > 0) * opcodes.GCALLVALUETRANSFER + \
                    ext.post_anti_dos_hardfork * opcodes.CALL_SUPPLEMENTAL_GAS
                    # ^ EIP150 Increase the gas cost of CALLCODE, DELEGATECALL to 700

            if ext.post_anti_dos_hardfork:
                # EIP150(1b) if a call asks for more gas than all but one 64th of
                # the maximum allowed amount, call with all but one 64th of the
                # maximum allowed amount of gas
                if compustate.gas < extra_gas:
                    return vm_exception('OUT OF GAS', needed=extra_gas)
                gas = min(gas, max_call_gas(compustate.gas - extra_gas))
            else:
                if compustate.gas < gas + extra_gas:
                    return vm_exception('OUT OF GAS', needed=gas + extra_gas)

            submsg_gas = gas + opcodes.GSTIPEND * (value > 0)
            if ext.get_balance(msg.to) >= value and msg.depth < 1024:
                compustate.gas -= (gas + extra_gas)
                to = utils.encode_int(to)
                to = ((b'\x00' * (32 - len(to))) + to)[12:]
                cd = CallData(mem, meminstart, meminsz)
                if ext.post_homestead_hardfork and op == 'DELEGATECALL':
                    call_msg = Message(msg.sender, msg.to, msg.value, submsg_gas, cd,
                                       msg.depth + 1, code_address=to, transfers_value=False)
                elif op == 'DELEGATECALL':
                    return vm_exception('OPCODE INACTIVE')
                else:
                    call_msg = Message(msg.to, msg.to, value, submsg_gas, cd,
                                       msg.depth + 1, code_address=to)
                result, gas, data = ext.msg(call_msg)
                if result == 0:
                    stk.append(0)
                else:
                    stk.append(1)
                    compustate.gas += gas
                    for i in range(min(len(data), memoutsz)):
                        mem[memoutstart + i] = data[i]
            else:
                compustate.gas -= (gas + extra_gas - submsg_gas)
                stk.append(0)
        elif op == 'RETURN':
            s0, s1 = stk.pop(), stk.pop()
            if not mem_extend(mem, compustate, op, s0, s1):
                return vm_exception('OOG EXTENDING MEMORY')
            return peaceful_exit('RETURN', compustate.gas, mem[s0: s0 + s1])
        elif op == 'SUICIDE':
            to = utils.encode_int(stk.pop())
            to = ((b'\x00' * (32 - len(to))) + to)[12:]

            if ext.post_anti_dos_hardfork:
                # EIP150 Increase the gas cost of SUICIDE to 5000
                extra_gas = opcodes.SUICIDE_SUPPLEMENTAL_GAS + \
                        (not ext.account_exists(to)) * opcodes.GCALLNEWACCOUNT
                # ^ EIP150(1c) If SUICIDE hits a newly created account, it
                # triggers an additional gas cost of 25000 (similar to CALLs)
                if not eat_gas(compustate, extra_gas):
                    return vm_exception("OUT OF GAS")

            xfer = ext.get_balance(msg.to)
            ext.set_balance(to, ext.get_balance(to) + xfer)
            ext.set_balance(msg.to, 0)
            ext.add_suicide(msg.to)
            # print('suiciding %s %s %d' % (msg.to, to, xfer))
            return 1, compustate.gas, []

        # this is slow!
        # for a in stk:
        #     assert is_numeric(a), (op, stk)
        #     assert a >= 0 and a < 2**256, (a, op, stk)

class VmExtBase():

    def __init__(self):
        self.get_code = lambda addr: b''
        self.get_balance = lambda addr: 0
        self.set_balance = lambda addr, balance: 0
        self.set_storage_data = lambda addr, key, value: 0
        self.get_storage_data = lambda addr, key: 0
        self.log_storage = lambda addr: 0
        self.add_suicide = lambda addr: 0
        self.add_refund = lambda x: 0
        self.block_prevhash = 0
        self.block_coinbase = 0
        self.block_timestamp = 0
        self.block_number = 0
        self.block_difficulty = 0
        self.block_gas_limit = 0
        self.log = lambda addr, topics, data: 0
        self.tx_origin = b'0' * 40
        self.tx_gasprice = 0
        self.create = lambda msg: 0, 0, 0
        self.call = lambda msg: 0, 0, 0
        self.sendmsg = lambda msg: 0, 0, 0


text:
using SpritesAndBones.Utility;
using System.Collections.Generic;
using UnityEngine;

namespace SpritesAndBones
{
    [ExecuteInEditMode]
    [RequireComponent(typeof(Bone))]
    public class InverseKinematics : MonoBehaviour
    {
        [HideInInspector]
        public float influence = 1.0f;

        public int chainLength = 0;
        public Transform target;
        private Skeleton skeleton = null;

        public Transform RootBone
        {
            get
            {
                Transform root = null;

                if (chainLength == 0)
                {
                    root = transform.root;
                }
                else
                {
                    int n = chainLength;
                    root = transform;
                    while (n-- > 0)
                    {
                        if (root.parent == null)
                            break;
                        else
                            root = root.parent;
                    }
                }
                return root;
            }
        }

        private int ChainLength
        {
            get
            {
                if (chainLength > 0)
                    return chainLength;
                else
                {
                    int n = 0;
                    var parent = transform.parent;
                    while (parent != null && parent.gameObject.GetComponent<Bone>() != null)
                    {
                        n++;
                        parent = parent.parent;
                    }
                    return n + 1;
                }
            }
        }

        public int iterations = 20;

        [Range(0.01f, 1)]
        public float damping = 1;

        public Node[] angleLimits = new Node[0];

        private Dictionary<Transform, Node> nodeCache;

        [System.Serializable]
        public class Node
        {
            public Transform Transform;

            [Range(0, 360)]
            public float from;

            [Range(0, 360)]
            public float to;
        }

        private void Start()
        {
            // Cache optimization
            if (angleLimits.Length > 0 && nodeCache != null && nodeCache.Count != angleLimits.Length ||
            angleLimits.Length > 0 && nodeCache == null)
            {
                nodeCache = new Dictionary<Transform, Node>(angleLimits.Length);
                foreach (var node in angleLimits)
                    if (!nodeCache.ContainsKey(node.Transform))
                        nodeCache.Add(node.Transform, node);
            }
            if (skeleton == null || skeleton != null && !transform.IsChildOf(skeleton.transform))
            {
                Skeleton[] skeletons = transform.root.gameObject.GetComponentsInChildren<Skeleton>(true);
                foreach (Skeleton s in skeletons)
                {
                    if (transform.IsChildOf(s.transform))
                    {
                        skeleton = s;
                    }
                }
            }
        }

        private void Update()
        {
            if (chainLength < 0)
                chainLength = 0;
            if (!Application.isPlaying)
                Start();
        }

        /**
         * Code ported from the Gamemaker tool SK2D by Drifter
         * http://gmc.yoyogames.com/index.php?showtopic=462301
         * Angle Limit code adapted from Veli-Pekka Kokkonen's SimpleCCD http://goo.gl/6oSzDx
         **/

        public void resolveSK2D()
        {
            for (int it = 0; it < iterations; it++)
            {
                int i = ChainLength;
                Transform bone = transform;
                Bone b = bone.GetComponent<Bone>();

                while (--i >= 0 && bone != null)
                {
                    Vector3 root = bone.position;

                    // Z position can be different than 0
                    Vector3 root2tip = ((Vector3)b.Head - (Vector3)(Vector2)root);
                    Vector3 root2target = (((target != null) ? (Vector3)(Vector2)target.transform.position : (Vector3)b.Head) - (Vector3)(Vector2)root);

                    // Calculate how much we should rotate to get to the target
                    float angle = SignedAngle(root2tip, root2target, bone);

                    // If you want to flip the bone on the y axis invert the angle
                    float yAngle = Utils.ClampAngle(bone.rotation.eulerAngles.y);
                    if (yAngle > 90 && yAngle < 270)
                        angle *= -1;

                    // "Slows" down the IK solving
                    angle *= damping;

                    // Wanted angle for rotation
                    angle = -(angle - bone.localRotation.eulerAngles.z);

                    if (nodeCache != null && nodeCache.ContainsKey(bone))
                    {
                        // Clamp angle in local space
                        var node = nodeCache[bone];
                        angle = ClampAngle(angle, node.from, node.to);
                    }

                    Quaternion newRotation = Quaternion.Euler(bone.localRotation.eulerAngles.x, bone.localRotation.eulerAngles.y, angle);

                    if (!IsNaNRot(newRotation))
                    {
                        bone.localRotation = newRotation;
                    }

                    bone = bone.parent;
                }
            }
        }

        public float SignedAngle(Vector3 a, Vector3 b, Transform t)
        {
            float angle = Vector3.Angle(a, b);

            // Use skeleton as root, change dir if the rotation is flipped
            Vector3 dir = (skeleton && skeleton.transform.localRotation.eulerAngles.y == 180.0f && skeleton.transform.localRotation.eulerAngles.x == 0.0f) ? Vector3.forward : Vector3.back;
            float sign = Mathf.Sign(Vector3.Dot(dir, Vector3.Cross(a, b)));
            angle = angle * sign;
            // Flip sign if character is turned around
            angle *= Mathf.Sign(t.root.localScale.x);
            return angle;
        }

        private float ClampAngle(float angle, float from, float to)
        {
            angle = Mathf.Abs((angle % 360) + 360) % 360;

            //Check limits
            if (from > to && (angle > from || angle < to))
                return angle;
            else if (to > from && (angle < to && angle > from))
                return angle;

            //Return nearest limit if not in bounds
            return (Mathf.Abs(angle - from) < Mathf.Abs(angle - to) && Mathf.Abs(angle - from) < Mathf.Abs((angle + 360) - to)) || (Mathf.Abs(angle - from - 360) < Mathf.Abs(angle - to) && Mathf.Abs(angle - from - 360) < Mathf.Abs((angle + 360) - to)) ? from : to;
        }

        private bool IsNaNRot(Quaternion q)
        {
            return (float.IsNaN(q.x) || float.IsNaN(q.y) || float.IsNaN(q.z) || float.IsNaN(q.w));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace English_alphabet
{
    class Program
    {
        static void Main(string[] args)
        {
            for (char i = 'a'; i <= 'z'; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}


text:
from peewee import Model, CharField, DateTimeField, IntegerField, BooleanField

from utils import db

class Strawpoll(Model):
    class Meta:
        database = db

    id = IntegerField(unique=True, null=False)
    title = CharField(null=False)

    def get_url(self):
        return "http://www.strawpoll.me/{0}".format(self.id)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using Cake.Core.Composition;
using Cake.Core.Diagnostics;
using Cake.Core.IO;
using Cake.Core.Scripting;
using Cake.Scripting.Abstractions;
using Cake.Scripting.CodeGen;
using Cake.Scripting.CodeGen.Generators;
using Cake.Scripting.IO;
using Cake.Scripting.Reflection;
using IScriptAliasFinder = Cake.Scripting.CodeGen.IScriptAliasFinder;

namespace Cake.Scripting
{
    public sealed class ScriptingModule : ICakeModule
    {
        private readonly IFileSystem _fileSystem;
        private readonly ICakeLog _log;

        public ScriptingModule(IFileSystem fileSystem, ICakeLog log)
        {
            _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
            _log = log ?? throw new ArgumentNullException(nameof(log));
        }

        public void Register(ICakeContainerRegistrar registrar)
        {
            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            // IO
            var bufferedFileSystem = new BufferedFileSystem(_fileSystem, _log);
            registrar.RegisterInstance(bufferedFileSystem)
                .As<IFileSystem>()
                .As<IBufferedFileSystem>();

            // Scripting
            registrar.RegisterType<CakeScriptAliasFinder>().As<IScriptAliasFinder>().Singleton();
            registrar.RegisterType<CakeScriptGenerator>().As<IScriptGenerationService>().Singleton();
            registrar.RegisterType<CakeAliasGenerator>().As<ICakeAliasGenerator>().Singleton();
            registrar.RegisterType<ReferenceAssemblyResolver>().As<IReferenceAssemblyResolver>().Singleton();
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title><%= htmlWebpackPlugin.options.package.name %></title>
    <meta name="description" content="<%= htmlWebpackPlugin.options.package.description %>">
    <link href="http://fonts.googleapis.com/css?family=Noto+Sans|Roboto:400,300,500" rel="stylesheet" type="text/css">
    <link href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/paper/bootstrap.min.css" rel="stylesheet">

    <a href="<%= htmlWebpackPlugin.options.package.repository.url %>">


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fdangelo.circleworld"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="19" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" android:allowBackup="true">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="sensor"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>