text:
<?php

namespace app\controllers;

use Yii;
use app\models\Post;
use app\models\PostSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * PostAdminController implements the CRUD actions for Post model.
 */
class AdminPostController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'ruleConfig' => [
                    'class' => \app\components\AccessRule::className(),
                ],
                'only' => ['index', 'view', 'create', 'update', 'delete'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => [\app\models\User::ROLE_ADMIN],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all Post models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PostSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Post model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Post model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Post();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Post model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Post model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        //uncomment this if you want to delete
//        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Post model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Post the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Post::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="20" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.z003damh.laptopremotecontrol.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
class NSObject

def browse(*args)
A11y::Console.browse(*args)
end
def view(*args)
A11y::Console.view(*args)
end
def touch(*args)
A11y::Console.touch(*args)
end

alias :b :browse
alias :v :view

end


text:
package uk.ac.sdss.extractcert;

import java.security.cert.Certificate;

import junit.framework.TestCase;

public class CertExtractorTest extends TestCase {

	public final void testCertExtractor() throws Exception {
		CertExtractor ce = CertExtractor.getInstance();
		assertNotNull(ce);

		// test against a raw Tomcat instance
		Certificate cert = ce.extractCertificate("dlib-idp.edina.ac.uk", 8443);
		assertNotNull(cert);
	}

}


text:
'use strict';

module.exports = SliceStream;

var Transform = require('readable-stream/transform');
var inherits = require("util").inherits;

inherits(SliceStream, Transform);

function SliceStream(opts, sliceFn) {
  if (!(this instanceof SliceStream)) {
    return new SliceStream(opts, sliceFn);
  }

  this._opts = opts;
  this._accumulatedLength = 0;
  this.sliceFn = sliceFn;

  Transform.call(this);
}

SliceStream.prototype._transform = function (chunk, encoding, callback) {
  this._accumulatedLength += chunk.length;

  if (this._accumulatedLength >= this._opts.length) {
    //todo handle more than one slice in a stream
    var offset = chunk.length - (this._accumulatedLength - this._opts.length);
    this.sliceFn(chunk.slice(0, offset), true, chunk.slice(offset));
    callback();
  } else {
    this.sliceFn(chunk);
    callback();
  }
};


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Jard. Bot. État Bruxelles 24:408, t. 12; Flore du Congo Belge 6:263, t. 24. 1954

#### Original name
null

### Remarks
null


text:
/*
 *  include/asm-s390/dma-mapping.h
 *
 *  S390 version
 *
 *  This file exists so that #include <dma-mapping.h> doesn't break anything.
 */

#ifndef _ASM_DMA_MAPPING_H
#define _ASM_DMA_MAPPING_H

#endif /* _ASM_DMA_MAPPING_H */


text:
#include "config.h"
#include "RenderSVGResourceContainer.h"

#include "RenderLayer.h"
#include "RenderSVGRoot.h"
#include "RenderView.h"
#include "SVGRenderingContext.h"
#include "SVGResourcesCache.h"
#include <wtf/StackStats.h>

namespace WebCore {

static inline SVGDocumentExtensions& svgExtensionsFromElement(SVGElement& element)
{
    return element.document().accessSVGExtensions();
}

RenderSVGResourceContainer::RenderSVGResourceContainer(SVGElement& element, RenderStyle&& style)
    : RenderSVGHiddenContainer(element, WTFMove(style))
    , m_id(element.getIdAttribute())
    , m_registered(false)
    , m_isInvalidating(false)
{
}

RenderSVGResourceContainer::~RenderSVGResourceContainer()
{
    if (m_registered)
        svgExtensionsFromElement(element()).removeResource(m_id);
}

void RenderSVGResourceContainer::layout()
{
    StackStats::LayoutCheckPoint layoutCheckPoint;
    // Invalidate all resources if our layout changed.
    if (selfNeedsClientInvalidation())
        RenderSVGRoot::addResourceForClientInvalidation(this);

    RenderSVGHiddenContainer::layout();
}

void RenderSVGResourceContainer::willBeDestroyed()
{
    SVGResourcesCache::resourceDestroyed(*this);
    RenderSVGHiddenContainer::willBeDestroyed();
}

void RenderSVGResourceContainer::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
    RenderSVGHiddenContainer::styleDidChange(diff, oldStyle);

    if (!m_registered) {
        m_registered = true;
        registerResource();
    }
}

void RenderSVGResourceContainer::idChanged()
{
    // Invalidate all our current clients.
    removeAllClientsFromCache();

    // Remove old id, that is guaranteed to be present in cache.
    svgExtensionsFromElement(element()).removeResource(m_id);
    m_id = element().getIdAttribute();

    registerResource();
}

void RenderSVGResourceContainer::markAllClientsForInvalidation(InvalidationMode mode)
{
    if ((m_clients.isEmpty() && m_clientLayers.isEmpty()) || m_isInvalidating)
        return;

    m_isInvalidating = true;
    bool needsLayout = mode == LayoutAndBoundariesInvalidation;
    bool markForInvalidation = mode != ParentOnlyInvalidation;
    auto* root = SVGRenderSupport::findTreeRootObject(*this);

    for (auto* client : m_clients) {
        // We should not mark any client outside the current root for invalidation
        if (root != SVGRenderSupport::findTreeRootObject(*client))
            continue;

        if (is<RenderSVGResourceContainer>(*client)) {
            downcast<RenderSVGResourceContainer>(*client).removeAllClientsFromCache(markForInvalidation);
            continue;
        }

        if (markForInvalidation)
            markClientForInvalidation(*client, mode);

        RenderSVGResource::markForLayoutAndParentResourceInvalidation(*client, needsLayout);
    }

    markAllClientLayersForInvalidation();

    m_isInvalidating = false;
}

void RenderSVGResourceContainer::markAllClientLayersForInvalidation()
{
    for (auto* clientLayer : m_clientLayers)
        clientLayer->filterNeedsRepaint();
}

void RenderSVGResourceContainer::markClientForInvalidation(RenderObject& client, InvalidationMode mode)
{
    ASSERT(!m_clients.isEmpty());

    switch (mode) {
    case LayoutAndBoundariesInvalidation:
    case BoundariesInvalidation:
        client.setNeedsBoundariesUpdate();
        break;
    case RepaintInvalidation:
        if (!client.documentBeingDestroyed())
            client.repaint();
        break;
    case ParentOnlyInvalidation:
        break;
    }
}

void RenderSVGResourceContainer::addClient(RenderElement& client)
{
    m_clients.add(&client);
}

void RenderSVGResourceContainer::removeClient(RenderElement& client)
{
    removeClientFromCache(client, false);
    m_clients.remove(&client);
}

void RenderSVGResourceContainer::addClientRenderLayer(RenderLayer* client)
{
    ASSERT(client);
    m_clientLayers.add(client);
}

void RenderSVGResourceContainer::removeClientRenderLayer(RenderLayer* client)
{
    ASSERT(client);
    m_clientLayers.remove(client);
}

void RenderSVGResourceContainer::registerResource()
{
    SVGDocumentExtensions& extensions = svgExtensionsFromElement(element());
    if (!extensions.isIdOfPendingResource(m_id)) {
        extensions.addResource(m_id, this);
        return;
    }

    std::unique_ptr<SVGDocumentExtensions::PendingElements> clients = extensions.removePendingResource(m_id);

    // Cache us with the new id.
    extensions.addResource(m_id, this);

    // Update cached resources of pending clients.
    for (auto* client : *clients) {
        ASSERT(client->hasPendingResources());
        extensions.clearHasPendingResourcesIfPossible(client);
        auto* renderer = client->renderer();
        if (!renderer)
            continue;
        SVGResourcesCache::clientStyleChanged(*renderer, StyleDifferenceLayout, renderer->style());
        renderer->setNeedsLayout();
    }
}

bool RenderSVGResourceContainer::shouldTransformOnTextPainting(const RenderElement& renderer, AffineTransform& resourceTransform)
{
#if USE(CG)
    UNUSED_PARAM(renderer);
    UNUSED_PARAM(resourceTransform);
    return false;
#else
    // This method should only be called for RenderObjects that deal with text rendering. Cmp. RenderObject.h's is*() methods.
    ASSERT(renderer.isSVGText() || renderer.isSVGTextPath() || renderer.isSVGInline());

    // In text drawing, the scaling part of the graphics context CTM is removed, compare SVGInlineTextBox::paintTextWithShadows.
    // So, we use that scaling factor here, too, and then push it down to pattern or gradient space
    // in order to keep the pattern or gradient correctly scaled.
    float scalingFactor = SVGRenderingContext::calculateScreenFontSizeScalingFactor(renderer);
    if (scalingFactor == 1)
        return false;
    resourceTransform.scale(scalingFactor);
    return true;
#endif
}

// FIXME: This does not belong here.
AffineTransform RenderSVGResourceContainer::transformOnNonScalingStroke(RenderObject* object, const AffineTransform& resourceTransform)
{
    if (!object->isSVGShape())
        return resourceTransform;

    SVGGraphicsElement* element = downcast<SVGGraphicsElement>(object->node());
    AffineTransform transform = element->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
    transform *= resourceTransform;
    return transform;
}

}


text:
Engine::Core::Map Engine::Core::MapLoader::Load(string Path, RenderWindow* Window)
{
	auto CheckAttribute = [](string AttributeName, xml_attribute<char>* Attribute) -> void
	{
		if (!Attribute)
		{
			string ErrorMessage = string("No attribute with the name: ") + AttributeName;
			throw runtime_error(ErrorMessage);
		}
	};

	auto GetAttribute = [CheckAttribute](string AttributeName, xml_node<char>* Node) -> string
	{
		xml_attribute<char>* Attribute = Node->first_attribute((char*)AttributeName.c_str());
		CheckAttribute(AttributeName, Attribute);
		return string(Attribute->value());
	};

	xml_document<> MapDocument;
	vector<char> MapContents;

	fstream File(Path);

	if (!File)
	{
		string ErrorMessage = "Failed to open map: " + Path;
		MessageBoxA(Window->getSystemHandle(), ErrorMessage.c_str(), "Error - Map", MB_OK | MB_ICONEXCLAMATION);
		exit(EXIT_FAILURE);
	}

	try
	{
		MapContents = vector<char>((istreambuf_iterator<char>(File)), istreambuf_iterator<char>());
		MapContents.push_back('\0');
		MapDocument.parse<0>(&MapContents[0]);
	}
	catch (parse_error &e)
	{
		throw runtime_error(e.what());
	}

	Map M = Map();
	xml_node<char>* Root = MapDocument.first_node("Map");

	if (!Root)
		throw runtime_error("Failed to find the root node of the map document 'Map'.");

	M.AddBackground(GetAttribute("Background", Root));

	///Load in all of the props into the map.
	for (xml_node<char>* PropNode = Root->first_node("Prop"); PropNode; PropNode = PropNode->next_sibling("Prop"))
	{
		///Get the location of prop in the world.
		///X
		Vector2f Position(0, 0);
		Position.x = stof(GetAttribute("X", PropNode));
		///Y
		Position.y = stof(GetAttribute("Y", PropNode));
		///Get if the prop can collide with the player.
		bool DoesCollision = Engine::Misc::StringToBool(GetAttribute("DoesCollision", PropNode));

		M.AddProp(string(PropNode->value()), Position, DoesCollision);
	}

	return M;
}


text:
package com.pengyifan.leetcode;

import com.pengyifan.leetcode.commons.ListNode;

/**
 * Given a linked list and a value x, partition it such that all nodes less
 * than x come before nodes greater than or equal to x.
 *

 * You should preserve the original relative order of the nodes in each of the
 * two partitions.
 *

 * For example,
 *

 * Given 1->4->3->2->5->2 and x = 3,
 *

 * return 1->2->2->4->3->5.
 */
public class PartitionList {

  public ListNode partition(ListNode head, int x) {
    if (head == null || head.next == null) {
      return head;
    }

    ListNode head1 = new ListNode(0);
    ListNode head2 = new ListNode(0);

    ListNode p = head1;
    ListNode q = head2;
    while (head != null) {
      if (head.val < x) {
        p.next = head;
        p = head;
      } else {
        q.next = head;
        q = head;
      }
      head = head.next;
    }
    p.next = head2.next;
    q.next = null;
    return head1.next;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/AIRshare.iml" filepath="$PROJECT_DIR$/AIRshare.iml" />
      <module fileurl="file://$PROJECT_DIR$/aFileChooser/aFileChooser.iml" filepath="$PROJECT_DIR$/aFileChooser/aFileChooser.iml" />
      <module fileurl="file://$PROJECT_DIR$/captureActivity/captureActivity.iml" filepath="$PROJECT_DIR$/captureActivity/captureActivity.iml" />
      <module fileurl="file://$PROJECT_DIR$/licencesDialog/licencesDialog.iml" filepath="$PROJECT_DIR$/licencesDialog/licencesDialog.iml" />
      <module fileurl="file://$PROJECT_DIR$/shAIRe/shAIRe.iml" filepath="$PROJECT_DIR$/shAIRe/shAIRe.iml" />
    </modules>
  </component>
</project>


text:
/**
 * CCControlSwitch: Switch control ui component
 * @class
 * @extends cc.Control
 */
cc.ControlSwitch = cc.Control.extend(/** @lends cc.ControlSwitch# */{
    /** Sprite which represents the view. */
    _switchSprite:null,
    _initialTouchXPosition:0,

    _moved:false,
    /** A Boolean value that determines the off/on state of the switch. */
    _on:false,
    _className:"ControlSwitch",
    ctor:function (maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel) {
        cc.Control.prototype.ctor.call(this);

        offLabel && this.initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel);
    },

    /** Creates a switch with a mask sprite, on/off sprites for on/off states, a thumb sprite and an on/off labels. */
    initWithMaskSprite:function (maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel) {
        if(!maskSprite)
            throw new Error("cc.ControlSwitch.initWithMaskSprite(): maskSprite should be non-null.");
        if(!onSprite)
            throw new Error("cc.ControlSwitch.initWithMaskSprite(): onSprite should be non-null.");
        if(!offSprite)
            throw new Error("cc.ControlSwitch.initWithMaskSprite(): offSprite should be non-null.");
        if(!thumbSprite)
            throw new Error("cc.ControlSwitch.initWithMaskSprite(): thumbSprite should be non-null.");
        if (this.init()) {
            this._on = true;

            this._switchSprite = new cc.ControlSwitchSprite();
            this._switchSprite.initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel);
            this._switchSprite.setPosition(this._switchSprite.getContentSize().width / 2, this._switchSprite.getContentSize().height / 2);
            this.addChild(this._switchSprite);

            this.ignoreAnchorPointForPosition(false);
            this.setAnchorPoint(0.5, 0.5);
            this.setContentSize(this._switchSprite.getContentSize());
            return true;
        }
        return false;
    },

    setOn:function (isOn, animated) {
        animated = animated || false;
        this._on = isOn;
        var xPosition = (this._on) ? this._switchSprite.getOnPosition() : this._switchSprite.getOffPosition();
        if(animated){
            this._switchSprite.runAction(new cc.ActionTween(0.2, "sliderXPosition", this._switchSprite.getSliderXPosition(),xPosition));
        }else{
            this._switchSprite.setSliderXPosition(xPosition);
        }
        this.sendActionsForControlEvents(cc.CONTROL_EVENT_VALUECHANGED);
    },

    isOn:function () {
        return this._on;
    },

    hasMoved:function () {
        return this._moved;
    },

    setEnabled:function (enabled) {
        this._enabled = enabled;

        this._switchSprite.setOpacity((enabled) ? 255 : 128);
    },

    locationFromTouch:function (touch) {
        var touchLocation = touch.getLocation();                      // Get the touch position
        touchLocation = this.convertToNodeSpace(touchLocation);                  // Convert to the node space of this class

        return touchLocation;
    },

    onTouchBegan:function (touch, event) {
        if (!this.isTouchInside(touch)  || !this.isEnabled()|| !this.isVisible()) {
            return false;
        }

        this._moved = false;

        var location = this.locationFromTouch(touch);

        this._initialTouchXPosition = location.x - this._switchSprite.getSliderXPosition();

        this._switchSprite.getThumbSprite().setColor(cc.color.GRAY);
        this._switchSprite.needsLayout();

        return true;
    },

    onTouchMoved:function (touch, event) {
        var location = this.locationFromTouch(touch);
        location = cc.p(location.x - this._initialTouchXPosition, 0);

        this._moved = true;

        this._switchSprite.setSliderXPosition(location.x);
    },

    onTouchEnded:function (touch, event) {
        var location = this.locationFromTouch(touch);

        this._switchSprite.getThumbSprite().setColor(cc.color.WHITE);

        if (this.hasMoved()) {
            this.setOn(!(location.x < this._switchSprite.getContentSize().width / 2), true);
        } else {
            this.setOn(!this._on, true);
        }
    },

    onTouchCancelled:function (touch, event) {
        var location = this.locationFromTouch(touch);

        this._switchSprite.getThumbSprite().setColor(cc.color.WHITE);

        if (this.hasMoved()) {
            this.setOn(!(location.x < this._switchSprite.getContentSize().width / 2), true);
        } else {
            this.setOn(!this._on, true);
        }
    }
});

/** Creates a switch with a mask sprite, on/off sprites for on/off states and a thumb sprite.
 *  @deprecated
 */
cc.ControlSwitch.create = function (maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel) {
    return new cc.ControlSwitch(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel);
};

/**
 * ControlSwitchSprite: Sprite switch control ui component
 * @class
 * @extends cc.Sprite
 *
 * @property {Number}           sliderX         - Slider's x position
 * @property {cc.Point}         onPos           - The position of slider when switch is on
 * @property {cc.Point}         offPos          - The position of slider when switch is off
 * @property {cc.Texture2D}     maskTexture     - The texture of the mask
 * @property {cc.Point}         texturePos      - The position of the texture
 * @property {cc.Point}         maskPos         - The position of the mask
 * @property {cc.Sprite}        onSprite        - The sprite of switch on
 * @property {cc.Sprite}        offSprite       - The sprite of switch off
 * @property {cc.Sprite}        thumbSprite     - The thumb sprite of the switch control
 * @property {cc.LabelTTF}      onLabel         - The sprite of switch on
 * @property {cc.LabelTTF}      offLabel        - The sprite of switch off
 * @property {Number}           onSideWidth     - <@readonly> The width of the on side of the switch control
 * @property {Number}           offSideWidth    - <@readonly> The width of the off side of the switch control
 */
cc.ControlSwitchSprite = cc.Sprite.extend({
    _sliderXPosition:0,
    _onPosition:0,
    _offPosition:0,

    _textureLocation:0,
    _maskLocation:0,
    _maskSize:null,

    _onSprite:null,
    _offSprite:null,
    _thumbSprite:null,
    _onLabel:null,
    _offLabel:null,
    _clipper:null,
    _stencil:null,
    _backRT:null,

    ctor:function () {
        cc.Sprite.prototype.ctor.call(this);
        this._sliderXPosition = 0;
        this._onPosition = 0;
        this._offPosition = 0;
        this._maskLocation = 0;
        this._maskSize = cc.size(0, 0);
        this._onSprite = null;
        this._offSprite = null;
        this._thumbSprite = null;
        this._onLabel = null;
        this._offLabel = null;
    },

    initWithMaskSprite:function (maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel) {
        if (cc.Sprite.prototype.init.call(this)) {
            this.setSpriteFrame(maskSprite.displayFrame());
            // Sets the default values
            this._onPosition = 0;
            this._offPosition = -onSprite.getContentSize().width + thumbSprite.getContentSize().width / 2;
            this._sliderXPosition = this._onPosition;

            this.setOnSprite(onSprite);
            this.setOffSprite(offSprite);
            this.setThumbSprite(thumbSprite);
            this.setOnLabel(onLabel);
            this.setOffLabel(offLabel);

            // Set up the mask with the Mask shader
            this._stencil = maskSprite;
            var maskSize = this._maskSize = this._stencil.getContentSize();
            this._stencil.setPosition(0, 0);

            // Init clipper for mask
            this._clipper = new cc.ClippingNode();
            this._clipper.setAnchorPoint(0.5, 0.5);
            this._clipper.setPosition(maskSize.width / 2, maskSize.height / 2);
            this._clipper.setStencil(this._stencil);
            this.addChild(this._clipper);

            this._clipper.addChild(onSprite);
            this._clipper.addChild(offSprite);
            this._clipper.addChild(onLabel);
            this._clipper.addChild(offLabel);

            this.addChild(this._thumbSprite);

            this.needsLayout();
            return true;
        }
        return false;
    },

    needsLayout:function () {
        var maskSize = this._maskSize;
        this._onSprite.setPosition(
            this._onSprite.getContentSize().width / 2 + this._sliderXPosition - maskSize.width / 2,
            this._onSprite.getContentSize().height / 2 - maskSize.height / 2
        );
        this._offSprite.setPosition(
            this._onSprite.getContentSize().width + this._offSprite.getContentSize().width / 2 + this._sliderXPosition - maskSize.width / 2,
            this._offSprite.getContentSize().height / 2 - maskSize.height / 2
        );

        if (this._onLabel) {
            this._onLabel.setPosition(
                this._onSprite.getPositionX() - this._thumbSprite.getContentSize().width / 6,
                this._onSprite.getContentSize().height / 2 - maskSize.height / 2
            );
        }
        if (this._offLabel) {
            this._offLabel.setPosition(
                this._offSprite.getPositionX() + this._thumbSprite.getContentSize().width / 6,
                this._offSprite.getContentSize().height / 2 - maskSize.height / 2
            );
        }
        this._thumbSprite.setPosition(
            this._onSprite.getContentSize().width + this._sliderXPosition,
            this._maskSize.height / 2
        );
    },

    setSliderXPosition:function (sliderXPosition) {
        if (sliderXPosition <= this._offPosition) {
            // Off
            sliderXPosition = this._offPosition;
        } else if (sliderXPosition >= this._onPosition) {
            // On
            sliderXPosition = this._onPosition;
        }

        this._sliderXPosition = sliderXPosition;

        this.needsLayout();
    },
    getSliderXPosition:function () {
        return this._sliderXPosition;
    },

    _getOnSideWidth:function () {
        return this._onSprite.getContentSize().width;
    },

    _getOffSideWidth:function () {
        return this._offSprite.getContentSize().height;
    },

    updateTweenAction:function (value, key) {
        if (key === "sliderXPosition")
            this.setSliderXPosition(value);
    },

    setOnPosition:function (onPosition) {
        this._onPosition = onPosition;
    },
    getOnPosition:function () {
        return this._onPosition;
    },

    setOffPosition:function (offPosition) {
        this._offPosition = offPosition;
    },
    getOffPosition:function () {
        return this._offPosition;
    },

    setMaskTexture:function (maskTexture) {
        this._stencil.setTexture(maskTexture);
    },
    getMaskTexture:function () {
        return this._stencil.getTexture();
    },

    setTextureLocation:function (textureLocation) {
        this._textureLocation = textureLocation;
    },
    getTextureLocation:function () {
        return this._textureLocation;
    },

    setMaskLocation:function (maskLocation) {
        this._maskLocation = maskLocation;
    },
    getMaskLocation:function () {
        return this._maskLocation;
    },

    setOnSprite:function (onSprite) {
        this._onSprite = onSprite;
    },
    getOnSprite:function () {
        return this._onSprite;
    },

    setOffSprite:function (offSprite) {
        this._offSprite = offSprite;
    },
    getOffSprite:function () {
        return this._offSprite;
    },

    setThumbSprite:function (thumbSprite) {
        this._thumbSprite = thumbSprite;
    },
    getThumbSprite:function () {
        return this._thumbSprite;
    },

    setOnLabel:function (onLabel) {
        this._onLabel = onLabel;
    },
    getOnLabel:function () {
        return this._onLabel;
    },

    setOffLabel:function (offLabel) {
        this._offLabel = offLabel;
    },
    getOffLabel:function () {
        return this._offLabel;
    }
});

var _p = cc.ControlSwitchSprite.prototype;

/** @expose */
_p.sliderX;
cc.defineGetterSetter(_p, "sliderX", _p.getSliderXPosition, _p.setSliderXPosition);
/** @expose */
_p.onPos;
cc.defineGetterSetter(_p, "onPos", _p.getOnPosition, _p.setOnPosition);
/** @expose */
_p.offPos;
cc.defineGetterSetter(_p, "offPos", _p.getOffPosition, _p.setOffPosition);
/** @expose */
_p.maskTexture;
cc.defineGetterSetter(_p, "maskTexture", _p.getMaskTexture, _p.setMaskTexture);
/** @expose */
_p.maskPos;
cc.defineGetterSetter(_p, "maskPos", _p.getMaskLocation, _p.setMaskLocation);
/** @expose */
_p.onSprite;
cc.defineGetterSetter(_p, "onSprite", _p.getOnSprite, _p.setOnSprite);
/** @expose */
_p.offSprite;
cc.defineGetterSetter(_p, "offSprite", _p.getOffSprite, _p.setOffSprite);
/** @expose */
_p.thumbSprite;
cc.defineGetterSetter(_p, "thumbSprite", _p.getThumbSprite, _p.setThumbSprite);
/** @expose */
_p.onLabel;
cc.defineGetterSetter(_p, "onLabel", _p.getOnLabel, _p.setOnLabel);
/** @expose */
_p.offLabel;
cc.defineGetterSetter(_p, "offLabel", _p.getOffLabel, _p.setOffLabel);
/** @expose */
_p.onSideWidth;
cc.defineGetterSetter(_p, "onSideWidth", _p._getOnSideWidth);
/** @expose */
_p.offSideWidth;
cc.defineGetterSetter(_p, "offSideWidth", _p._getOffSideWidth);

_p = null;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>IndexTranslator (Google App Engine Java API)</title>
<meta name="date" content="2013-11-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.appengine.api.datastore

Class IndexTranslator

java.lang.Object

com.google.appengine.api.datastore.IndexTranslator

public class IndexTranslator
extends java.lang.Object

Helper class to translate between Index to com.google.storage.onestore.v3.OnestoreEntity.Index.

Constructor Summary

Constructors

Constructor and Description

IndexTranslator()

Method Summary

Methods

Modifier and Type
Method and Description

static Index
convertFromPb(OnestoreEntity.CompositeIndex ci)

static Index.Property
convertFromPb(OnestoreEntity.Index.Property property)

static Index
convertFromPb(OnestoreEntity.Index index)

static OnestoreEntity.Index.Property
convertToPb(Index.Property property)

static OnestoreEntity.Index
convertToPb(Index index)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

IndexTranslator

public IndexTranslator()

Method Detail

convertToPb

public static OnestoreEntity.Index convertToPb(Index index)

convertToPb

public static OnestoreEntity.Index.Property convertToPb(Index.Property property)

convertFromPb

public static Index convertFromPb(OnestoreEntity.CompositeIndex ci)

convertFromPb

public static Index.Property convertFromPb(OnestoreEntity.Index.Property property)

convertFromPb

public static Index convertFromPb(OnestoreEntity.Index index)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
module Gws::ReadableSetting
  extend ActiveSupport::Concern

  included do
    class_variable_set(:@@_readable_setting_include_custom_groups, nil)
    class_variable_set(:@@_requires_read_permission_to_read, true)

    field :readable_setting_range, type: String, default: 'select'
    field :readable_groups_hash, type: Hash
    field :readable_members_hash, type: Hash
    field :readable_custom_groups_hash, type: Hash

    embeds_ids :readable_groups, class_name: "Gws::Group"
    embeds_ids :readable_members, class_name: "Gws::User"
    embeds_ids :readable_custom_groups, class_name: "Gws::CustomGroup"

    permit_params :readable_setting_range
    permit_params readable_group_ids: [], readable_member_ids: [], readable_custom_group_ids: []

    before_validation :apply_readable_setting_range, if: ->{ readable_setting_range_changed? && readable_setting_range }
    before_validation :set_readable_groups_hash
    before_validation :set_readable_members_hash
    before_validation :set_readable_custom_groups_hash

    # Allow readable settings and readable permissions.
    scope :readable, ->(user, opts = {}) {
      if requires_read_permission_to_read?
        return none unless self.allowed?(:read, user, opts)
      end
      or_conds = readable_conditions(user, opts)
      where("$and" => [{ "$or" => or_conds }])
    }
  end

  def readable_setting_present?
    return true if readable_group_ids.present?
    return true if readable_member_ids.present?
    return true if readable_custom_group_ids.present?

    false
  end

  def readable?(user, opts = {})
    opts[:site] ||= self.site

    if self.class.requires_read_permission_to_read?
      return false unless self.class.allowed?(:read, user, opts)
    end
    return true if !readable_setting_present?
    return true if readable_group_ids.any? { |m| user.group_ids.include?(m) }
    return true if readable_member_ids.include?(user.id)
    return true if readable_custom_groups.any? { |m| m.member?(user) }

    false
  end

  def readable_groups_hash
    self[:readable_groups_hash].presence || readable_groups.map { |m| [m.id, m.name] }.to_h
  end

  def readable_group_names
    readable_groups_hash.values
  end

  def readable_members_hash
    self[:readable_members_hash].presence || readable_members.map { |m| [m.id, m.long_name] }.to_h
  end

  def readable_member_names
    readable_members_hash.values
  end

  def readable_custom__groups_hash
    self[:readable_custom_groups_hash].presence || readable_custom_groups.map { |m| [m.id, m.name] }.to_h
  end

  def readable_custom_group_names
    readable_custom_groups_hash.values
  end

  def readable_setting_range_options
    %w(public select private).map { |v| [I18n.t("gws.options.readable_setting_range.#{v}"), v] }
  end

  def readable_setting_range_label
    val = readable_setting_range
    val = 'public' unless readable_setting_present?
    I18n.t("gws.options.readable_setting_range.#{val}")
  end

  def overall_readers
    case readable_setting_range
    when 'public'
      Gws::User.all
    when 'select'
      user_ids = readable_members.pluck(:id)
      group_ids = readable_groups.active.pluck(:id)
      if self.class.readable_setting_included_custom_groups?
        user_ids += readable_custom_groups.pluck(:member_ids).flatten
        group_ids += readable_custom_groups.pluck(:member_group_ids).flatten
      end

      group_ids.compact!
      group_ids.uniq!
      group_ids += Gws::Group.site(@cur_site || site).in(id: group_ids).active.pluck(:id)

      user_ids += Gws::User.in(group_ids: group_ids).pluck(:id)
      user_ids.uniq!
      Gws::User.in(id: user_ids)
    else # private
      Gws::User.none
    end
  end

  private

  def apply_readable_setting_range
    if readable_setting_range == 'public'
      self.readable_group_ids = []
      self.readable_member_ids = []
      self.readable_custom_group_ids = []
    elsif readable_setting_range == 'private'
      self.readable_group_ids = []
      self.readable_member_ids = [@cur_user.id].compact
      self.readable_custom_group_ids = []
    end
  end

  def set_readable_groups_hash
    self.readable_groups_hash = readable_groups.map { |m| [m.id, m.name] }.to_h
  end

  def set_readable_members_hash
    self.readable_members_hash = readable_members.map { |m| [m.id, m.long_name] }.to_h
  end

  def set_readable_custom_groups_hash
    self.readable_custom_groups_hash = readable_custom_groups.map { |m| [m.id, m.name] }.to_h
  end

  module ClassMethods
    def readable_setting_included_custom_groups?
      class_variable_get(:@@_readable_setting_include_custom_groups)
    end

    def readable_conditions(user, opts = {})
      or_conds = [
        { "readable_group_ids.0" => { "$exists" => false },
          "readable_member_ids.0" => { "$exists" => false },
          "readable_custom_group_ids.0" => { "$exists" => false } },
        { :readable_group_ids.in => user.group_ids },
        { readable_member_ids: user.id },
      ]
      if readable_setting_included_custom_groups?
        or_conds << { :readable_custom_group_ids.in => Gws::CustomGroup.member(user).pluck(:id) }
      end
      or_conds
    end

    def requires_read_permission_to_read?
      class_variable_get(:@@_requires_read_permission_to_read)
    end

    private

    def readable_setting_include_custom_groups
      class_variable_set(:@@_readable_setting_include_custom_groups, true)
    end

    def no_needs_read_permission_to_read
      class_variable_set(:@@_requires_read_permission_to_read, false)
    end
  end
end


text:
#region Copyright © 2005 Paul Welter. All rights reserved.

#endregion

using System;

namespace MSBuild.Community.Tasks {

	/// <summary>
	/// Describes a factory for IFtpWebRequest.
	/// </summary>
	public interface IFtpWebRequestCreator {

		/// <summary>
		/// Instantiates an FtpWebRequest.
		/// </summary>
		IFtpWebRequest Create(Uri uri, string method);
	}

}


text:
using System;

namespace CryptoPals
{
    public class MersenneTwister
    {
        #region The constants
        const int w = 32;
        const int n = 624;
        const int m = 397;
        const int r = 31;
        const uint a = 0x9908B0DF;
        const int u = 11;
        const uint d = 0xFFFFFFFF;
        const int s = 7;
        const uint b = 0x9D2C5680;
        const int t = 15;
        const uint c = 0xEFC60000;
        const int l = 18;

        const uint f = 1812433253;

        const uint lowerMask = (1u << r) - 1;
        const uint upperMask = ~lowerMask;
        #endregion

        uint[] state;
        int index;

        public MersenneTwister(uint seed = 5489) {
            // Initialize the state
            this.index = n;
            this.state = new uint[n]; // The state
            this.state[0] = seed;
            for (uint i = 1; i < n; i++)
                this.state[i] = f * (this.state[i - 1] ^ (this.state[i - 1] >> (w - 2))) + i;
        }
        public MersenneTwister(byte[] seed) : this(ConversionHelpers.ToUInt(seed)) { }
        public MersenneTwister(uint[] state) {
            this.index = n;
            this.state = state;
        }

        public uint Next() {
            // Extract the next number
            if (this.index >= n)
                this.twist();

            uint y = this.state[this.index];
            y = y ^ ((y >> u) & d);
            y = y ^ ((y << s) & b);
            y = y ^ ((y << t) & c);
            y = y ^ (y >> l);

            this.index++;
            return y;
        }

        public byte[] NextBytes() {
            return ConversionHelpers.ToLittleEndian(this.Next());
        }
        public byte[] NextBytes(int length) {
            byte[] result = new byte[length];
            for (int i = 0; i < length; i += 4)
                Array.Copy(this.NextBytes(), 0, result, i, Math.Min(4, length - i));
            return result;
        }

        private void twist() {
            // Generate the next n values for the state
            for (int i = 0; i < n; i++) {
                uint x = (this.state[i] & upperMask) + (this.state[(i + 1) % n] & lowerMask);
                uint xA = x >> 1;
                if (x % 2 != 0)
                    xA = xA ^ a;
                this.state[i] = this.state[(i + m) % n] ^ xA;
            }
            this.index = 0;
        }

        public static uint Untemper(uint y) {
            y = untemperRightShift(y, l);
            y = untemperLeftShift(y, c, t);
            y = untemperLeftShift(y, b, s);
            y = untemperRightShift(y, u);

            return y;
        }

        static uint untemperRightShift(uint y, int bitsShifted) {
            if (bitsShifted <= 0)
                throw new Exception("The untemperRightShift method expects the # bits shifted to be at least 1");
            const int size = 32;
            uint result = 0;

            // The idea: we know that the bits are shifted x to the right, so the x left most bits we receive are correct
            uint mask = 1u << (size - 1);
            for (int i = 0; i < bitsShifted; i++) {
                result |= y & mask;
                mask >>= 1;
            }

            // Then, since we know what the next bit from the left is xored with, we know what it must be
            while (mask != 0) {
                result |= ((result >> bitsShifted) ^ y) & mask;
                mask >>= 1;
            }

            return result;
        }
        static uint untemperLeftShift(uint y, uint magicNumber, int bitsShifted) {
            if (bitsShifted <= 0)
                throw new Exception("The untemperLeftShift method expects the # bits shifted to be at least 1");
            uint result = 0;

            // The idea: we know that the bits are shifted x to the left, so the x right most bits we receive are correct
            uint mask = 1;
            for (int i = 0; i < bitsShifted; i++) {
                result |= y & mask;
                mask <<= 1;
            }

            // Then, since we know what the next bit from the right is xored with, we know what it must be
            while (mask != 0) {
                result |= (((result << bitsShifted) & magicNumber) ^ y) & mask;
                mask <<= 1;
            }

            return result;
        }
    }
}


text:
require 'jemc_cexample'

p JEMC::CExample
p JEMC::CExample.singleton_methods(false)
p JEMC::CExample.dummy
p JEMC::CExample.version
p JEMC::CExample.passthru 55


text:
require 'active_support/concern'

require 'zermelo/record'

module Zermelo
  module Records
    module Stub
      extend ActiveSupport::Concern

      include Zermelo::Record

      included do
        set_backend :stub
      end
    end
  end
end


text:
using System;

namespace sar.Tools
{
	public class ErrorLogger : FileLogger
	{
		public ErrorLogger(string filename) : base(filename, false)
		{
		}

		public void Write(Exception ex)
		{
			Exception inner = ExceptionHelper.GetInner(ex);

			base.WriteLine(ConsoleHelper.HR);
			base.WriteLine("Time: " + DateTime.Now.ToString());
			base.WriteLine("Type: " + inner.GetType().ToString());
			base.WriteLine("Error: " + inner.Message);
			base.WriteLine(ConsoleHelper.HR);
			base.WriteLine(ExceptionHelper.GetStackTrace(inner));
			base.WriteLine("");
		}
	}
}


text:
#include <sys/event.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef __APPLE__
#include <libkern/OSAtomic.h>
#endif
#include <assert.h>
#include <sys/sysctl.h>
#include <stdarg.h>
#include <time.h>

#include <dispatch/dispatch.h>
#include <dispatch/private.h>

#include <bsdtests.h>
#include "dispatch_test.h"

#if defined(DISPATCH_SOURCE_TYPE_VM) && defined(NOTE_VM_PRESSURE)

#if TARGET_OS_EMBEDDED
#define ALLOC_SIZE ((size_t)(1024*1024*1ul))	// 1MB
#define NOTIFICATIONS 1
#else
#define ALLOC_SIZE ((size_t)(1024*1024*20ul))	// 20MB
#define NOTIFICATIONS 2
#endif
#define pg2mb(p) ((p) * ALLOC_SIZE/(1024*1024))
#ifdef __LP64__
#define MAXMEM ((size_t)SIZE_MAX)
#else
#define MAXMEM ((size_t)(3200ul*1024*1024))		// 3200MB
#endif

static char **pages;
static volatile int32_t handler_call_count;
static volatile int32_t page_count;
static int32_t max_page_count;
static dispatch_source_t vm_source;
static dispatch_queue_t vm_queue;
static time_t initial;
static int interval = 16;

#define log_msg(msg, ...) \
do { \
	fprintf(stderr, "[%2ds] " msg, (int)(time(NULL) - initial), ##__VA_ARGS__);\
} while (0)

static bool
dispatch_test_check_evfilt_vm(void)
{
	int kq = kqueue();
	assert(kq != -1);
	struct kevent ke = {
		.filter = EVFILT_VM,
		.flags = EV_ADD|EV_ENABLE|EV_RECEIPT,
		.fflags = NOTE_VM_PRESSURE,
	};
	int r = kevent(kq, &ke, 1, &ke, 1, NULL);
	close(kq);
	return !(r > 0 && ke.flags & EV_ERROR && ke.data == ENOTSUP);
}

static void
cleanup(void)
{
	dispatch_source_cancel(vm_source);
	dispatch_release(vm_source);
	dispatch_release(vm_queue);

	int32_t pc = 0, i;
	for (i = 0; i < max_page_count; ++i) {
	   if (pages[i]) {
		   pc++;
		   free(pages[i]);
	   }
	}
	if (pc) {
		log_msg("Freed %ldMB\n", pg2mb(pc));
	}
	free(pages);
	test_stop();
}

int
main(void)
{
	dispatch_test_start("Dispatch VM Pressure test"); // rdar://problem/7000945
	if (!dispatch_test_check_evfilt_vm()) {
		test_skip("EVFILT_VM not supported");
		test_stop();
		return 0;
	}
	initial = time(NULL);
	uint64_t memsize;
#ifdef __linux__
	memsize = sysconf(_SC_PAGESIZE) * sysconf(_SC_PHYS_PAGES);
#else
	size_t s = sizeof(memsize);
	int rc = sysctlbyname("hw.memsize", &memsize, &s, NULL, 0);
	assert(rc == 0);
#endif
	max_page_count = MIN(memsize, MAXMEM) / ALLOC_SIZE;
	pages = calloc(max_page_count, sizeof(char*));

	vm_queue = dispatch_queue_create("VM Pressure", NULL);
	vm_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VM, 0,
			DISPATCH_VM_PRESSURE, vm_queue);
	dispatch_source_set_event_handler(vm_source, ^{
		if (!page_count) {
			// Too much memory pressure already to start the test
			test_skip("Memory pressure at start of test");
			cleanup();
		}
		if (OSAtomicIncrement32Barrier(&handler_call_count) != NOTIFICATIONS) {
			log_msg("Ignoring vm pressure notification\n");
			interval = 1;
			return;
		}
		test_long("dispatch_source_get_data()",
				dispatch_source_get_data(vm_source), NOTE_VM_PRESSURE);
		int32_t i, pc = page_count + 1;
		for (i = 0; i < pc && pages[i]; ++i) {
				free(pages[i]);
				pages[i] = NULL;
		}
		log_msg("Freed %ldMB\n", pg2mb(i));
	});
	dispatch_resume(vm_source);
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC),
			dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
		while (handler_call_count < NOTIFICATIONS &&
				page_count < max_page_count) {
			void *p = valloc(ALLOC_SIZE);
			if (!p) {
				break;
			}
			bzero(p, ALLOC_SIZE);
			pages[page_count] = p;
			if (!(OSAtomicIncrement32Barrier(&page_count) % interval)) {
				log_msg("Allocated %ldMB\n", pg2mb(page_count));
				usleep(200000);
			}
		}
		if (page_count % interval) {
			log_msg("Allocated %ldMB\n", pg2mb(page_count));
		}
		if (handler_call_count < NOTIFICATIONS) {
			// Cannot allocate enough memory for test (e.g. on 32 bit)
			test_skip("Cannot allocate enough memory for test");
			dispatch_async(vm_queue, ^{cleanup();});
			return;
		}
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC),
				vm_queue, ^{
			test_long_greater_than_or_equal("VM Pressure fired",
					handler_call_count, NOTIFICATIONS);
			test_long_less_than("VM Pressure stopped firing",
					handler_call_count, 4);
			cleanup();
		});
	});
	dispatch_main();
	return 0;
}
#else //DISPATCH_SOURCE_TYPE_VM
int
main(void)
{
	dispatch_test_start("Dispatch VM Pressure test"
			" - No DISPATCH_SOURCE_TYPE_VM");
	test_stop();
	return 0;
}
#endif //DISPATCH_SOURCE_TYPE_VM


text:
#include "fennel/common/CommonPreamble.h"
#include "fennel/tuple/TupleDescriptor.h"
#include "fennel/tuple/TupleData.h"
#include "fennel/tuple/TupleAccessor.h"
#include "fennel/tuple/TuplePrinter.h"
#include "fennel/tuple/AttributeAccessor.h"
#include "fennel/tuple/StandardTypeDescriptor.h"
#include "fennel/common/TraceSource.h"

#include <boost/scoped_array.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <limits>
#include <iostream.h>

using namespace fennel;

int const bufferlen = 8;
int const num = 5;

void
tupleFiddle()
{
    bool isNullable = true;    // Can tuple contain nulls?
    int i;

    TupleDescriptor tupleDesc;
    tupleDesc.clear();

    // Build up a description of what we'd like the tuple to look like
    StandardTypeDescriptorFactory typeFactory;
    for (i = 0; i < num; i++) {
        StoredTypeDescriptor const &typeDesc =
            typeFactory.newDataType(STANDARD_TYPE_VARCHAR);
        tupleDesc.push_back(
            TupleAttributeDescriptor(
                typeDesc,
                isNullable,
                bufferlen));
    }
    for (i = 0; i < num; i++) {
        StoredTypeDescriptor const &typeDesc =
            typeFactory.newDataType(STANDARD_TYPE_INT_32);
        tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable));
    }
    for (i = 0; i < num; i++) {
        StoredTypeDescriptor const &typeDesc =
            typeFactory.newDataType(STANDARD_TYPE_UINT_8);
        tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable));
    }
    for (i = 0; i < num; i++) {
        StoredTypeDescriptor const &typeDesc =
            typeFactory.newDataType(STANDARD_TYPE_REAL);
        tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable));
    }

    // Create a tuple accessor from the description
    //
    // Note: Must use an ALL_FIXED accessor when creating a tuple out of
    // the air like this, otherwise unmarshal() does not know what to
    // do. If you need a STANDARD type tuple with variable-lengty
    // fields, it has to be built as a copy.
    TupleAccessor tupleAccessorFixed;
    tupleAccessorFixed.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED);

    // Allocate memory for the tuple
    boost::scoped_array<FixedBuffer>
        pTupleBufFixed(new FixedBuffer[tupleAccessorFixed.getMaxByteCount()]);

    // Link memory to accessor
    tupleAccessorFixed.setCurrentTupleBuf(pTupleBufFixed.get(), false);

    // Create a vector of TupleDatum objects based on the description we built
    TupleData tupleDataFixed(tupleDesc);

    // Do something mysterious. Probably binding pointers in the accessor to
    // items in the TupleData vector
    tupleAccessorFixed.unmarshal(tupleDataFixed);

    TupleData::iterator itr = tupleDataFixed.begin();

    TupleDatum pDatum;
    PBuffer pData;

    for (i = 0; i < num; i++, itr++) {
        char buf[bufferlen * 10];
        sprintf(buf, "%d-A-%d-B-%d-C-", i, i, i); // longer than buflen
        strncpy(
            (reinterpret_cast<char *>(const_cast<PBuffer>(itr->pData))),
            buf, bufferlen);
    }
    for (i = 0; i < num; i++, itr++) {
        // exploded form
        pDatum = *itr;
        pData = const_cast<PBuffer>(pDatum.pData);
        *(reinterpret_cast<int32_t *>(pData)) = i;
    }
    for (i = 0; i < num; i++, itr++) {
        // condensed form
        *(reinterpret_cast<uint8_t *>(const_cast<PBuffer>(itr->pData))) = i;
    }
    for (i = 0; i < num; i++, itr++) {
        *(reinterpret_cast<float *>(const_cast<PBuffer>(itr->pData))) = i * 0.5;
    }

    // Print out the tuple
    TuplePrinter tuplePrinter;
    tuplePrinter.print(cout, tupleDesc, tupleDataFixed);
    cout << endl;

    // Create another TupleData object that will be nullable
    TupleData tupleDataNullable = tupleDataFixed;

    // null out last element of each type
    for (i = 1; i <= 3; i++) {
        tupleDataNullable[(i*num)-1].pData = NULL;
    }

    // Print out the nullable tuple
    tuplePrinter.print(cout, tupleDesc, tupleDataNullable);
    cout << endl;

    // Re-point second string to first string
    tupleDataNullable[1].pData = tupleDataNullable[0].pData;

    // Re-point third string to part way into first string
    tupleDataNullable[2].pData = (tupleDataNullable[0].pData + 1);

    // Print out the modified nullable tuple
    tuplePrinter.print(cout, tupleDesc, tupleDataNullable);
    cout << endl;

}

int
main(int argc, char *argv[])
{
    tupleFiddle();
    return 0;
}

boost::unit_test_framework::test_suite *init_unit_test_suite(int,char **)
{
    return NULL;
}

// End tuple.cpp


text:
module TableGo
  module Renderers
    module RendererBase
      extend ActiveSupport::Concern

      included do
        attr_accessor :table, :template
        delegate :content_tag, :concat, :to => :template
      end

      def render_template
        raise ArgumentError.new('implement #render_template in concrete renderer')
      end

      private

        def label_for_column(column)
          column.label || begin
            if column.method && 1==3# reflection = table.model_klass.reflections[column.name]
              reflection.klass.human_attribute_name(column.method).html_safe
            # if column.method && reflection = table.model_klass.reflections[column.name]
            #   reflection.klass.human_attribute_name(column.method).html_safe
            else
              column.human_attribute_name
            end
          end
        end

        def html_options_for_header(column)
          {}.tap do |h|
            (column.header_html || {}).each do |k, v|
              h[k] = v.is_a?(Proc) ? v.call(column) : v
            end
          end
        end

        def html_options_for_row(record)
          {}.tap do |h|
            (table.row_html || {}).each do |k, v|
              h[k] = v.is_a?(Proc) ? v.call(record) : v
            end
          end
        end

        def html_options_for_cell(record, column, value)
          {}.tap do |h|
            (column.column_html || {}).each do |k, v|
              h[k] = v.is_a?(Proc) ? v.call(record, column, value) : v
            end
          end
        end

        def value_from_record_by_column(record, column)
          if record.respond_to?(column.name)
            value = record.send(column.name)
            column.method ? value.send(column.method) : value
          else
            ''
          end
        end

        def apply_formatter(record, column, value)
          begin
            case
              when formatter = column.as
                Formatter.apply(formatter, record, column, value)
              when formatter = column.send
                Formatter.apply_send(formatter, record, column, value)
              when formatter = column.block
                apply_formatter_for_block(formatter, record, column, value)
              else
                value
            end
          end.to_s.html_safe
        end

        def apply_formatter_for_block(formatter, record, column, value)
          # template.capture { Formatter.apply(formatter, record, column, value )}
          # template.capture_haml { Formatter.apply(formatter, record, column, value )}
          # template.send(:capture_haml) { Formatter.apply(formatter, record, column, value )}
          string = nil
          capture_view do
            string = Formatter.apply(formatter, record, column, value )
          end.presence || string # for compatibility to legacy haml "- t.column :ident"
        end

        def capture_view
          template.is_haml? ? capture_haml { yield } : template.capture { yield }
        end

        #delegate :with_haml_buffer, :to => :template

        # stripped down ripoff from Haml's capture_haml, needed for speed
        def capture_haml(*args, &block)
          # buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer
          # buffer = haml_buffer
          # with_haml_buffer(buffer) do
            position = template.send(:haml_buffer).buffer.length

          template.send(:haml_buffer).capture_position = position
            block.call(*args)

            # captured = haml_buffer.buffer.slice!(0..-1)
            captured = template.send(:haml_buffer).buffer.slice!(position..-1)
            # return captured if haml_buffer.options[:ugly]

            # debugger
            # Note that the "reject" is needed for rbx 1.2.4, which includes empty
            # strings in the returned array when splitting by /^/.
            # captured = captured.split(/^/).reject {|x| x == ""}

            # min_tabs = nil
            # captured.each do |line|
            #   tabs = line.index(/[^ ]/) || line.length
            #   min_tabs ||= tabs
            #   min_tabs = min_tabs > tabs ? tabs : min_tabs
            # end

            # captured.map do |line|
            #   line.slice(min_tabs, line.length)
            # end.join
          # end
        ensure
          template.send(:haml_buffer).capture_position = nil
        end

        # def capture_haml(*args, &block)
        #   # buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer
        #   # buffer = haml_buffer
        #   # with_haml_buffer(buffer) do
        #     position = haml_buffer.buffer.length

        #     haml_buffer.capture_position = position
        #     block.call(*args)

        #     captured = haml_buffer.buffer.slice!(position..-1)
        #     # return captured if haml_buffer.options[:ugly]

        #     # debugger
        #     # Note that the "reject" is needed for rbx 1.2.4, which includes empty
        #     # strings in the returned array when splitting by /^/.
        #     captured = captured.split(/^/).reject {|x| x == ""}

        #     # min_tabs = nil
        #     # captured.each do |line|
        #     #   tabs = line.index(/[^ ]/) || line.length
        #     #   min_tabs ||= tabs
        #     #   min_tabs = min_tabs > tabs ? tabs : min_tabs
        #     # end

        #     # captured.map do |line|
        #     #   line.slice(min_tabs, line.length)
        #     # end.join
        #   # end
        # ensure
        #   haml_buffer.capture_position = nil
        # end

        # def capture_view
        #   template.is_haml? ? template.capture_haml { yield } : template.capture { yield }
        # end

        # def capture_view
        #   template.send(capture_method) { yield }
        # end

        # def capture_method
        #   @capture_method ||= template.is_haml? ? :capture_haml : :capture
        # end

        # def capture_view(&proc)
        #   @capturer ||= template.is_haml? ? capture_haml : capture_action_view
        #   @capturer.call(proc)
        # end

        # def capture_haml(&proc)
        #   lambda { |c| template.capture_haml { c.call } }
        # end

        # def capture_action_view
        #   lambda { |c| template.capture { c.call } }
        # end

    end
  end
end


text:
<?php
require_once('abstract/WebHooksAbstract.php');
class WebHooks extends WebHooksAbstract
{
    /**
     * Returns the list of events to be created
     * @return array
     */
    function getEventList()
    {
        $eventList = array(
            xtc_href_link('../WebhookListener.php', '&action=chargeback&type='.$this->_request['type'], 'SSL', false, false) => 'chargeback.executed',
            xtc_href_link('../WebhookListener.php', '&action=refund&type='.$this->_request['type'], 'SSL', false, false) => 'refund.succeeded'
        );

        return $eventList;
    }

    /**
     * Requires the php libs webhook class
     */
    function requireWebhooks()
    {
        require_once('lib/Services/Paymill/Webhooks.php');
    }

    /**
     * Saves the web-hook into the web-hook table
     *
     * @param String $id
     * @param String $url
     * @param String $mode
     * @param String $type
     * @param String $created_at
     *
     * @throws Exception
     * @return void
     */
    function saveWebhook($id, $url, $mode, $type, $created_at)
    {
        $sql = "REPLACE INTO `pi_paymill_webhooks` (`id`, `url`, `mode`, `type`, `created_at`) VALUES('".$id."','".$url."','".$mode."','".$type."','".$created_at."')";
        $success = xtc_db_query($sql);
        if(!$success){
            throw new Exception("Webhook data could not be saved.");
        }

    }

    /**
     * Removes the web-hook from the web-hook table
     *
     * @param String $id
     *
     * @throws Exception
     * @return void
     */
    function removeWebhook($id)
    {
        $sql = "DELETE FROM `pi_paymill_webhooks` WHERE `id` = '".$id."'";
        $success = xtc_db_query($sql);
        if(!$success){
            throw new Exception("Webhook data could not be deleted.");
        }
    }

    /**
     * Returns the ids of all web-hooks from the web-hook table
     *
     * @param String $type
     *
     * @return array
     */
    function loadAllWebHooks($type)
    {
        $sql = "SELECT `id` FROM `pi_paymill_webhooks` WHERE `type` = '".$type."'";
        $store = xtc_db_query($sql);
        $result = array();
        while($row = xtc_db_fetch_array($store)){
            $result[] = $row['id'];
        }

        return $result;
    }

    /**
     * Logs parameters into the db without relying on the logging option
     * @param String $messageInfo
     * @param String $debugInfo
     */
    static function log($messageInfo, $debugInfo)
    {
        xtc_db_query("INSERT INTO `pi_paymill_logging` "
                     . "(debug, message, identifier) "
                     . "VALUES('"
                     . xtc_db_input($debugInfo) . "', '"
                     . xtc_db_input($messageInfo) . "', '"
                     . xtc_db_input($_SESSION['paymill_identifier'])
                     . "')"
        );
    }

    /**
     * Updates the order state
     */
    function updateOrderStatus()
    {
        $description = $this->_request['event_resource']['transaction']['description'];
        $eventType = $this->_request['action'];
        try{
            $orderId = $this->getOrderIdFromDescription($description);
            $orderStatus = $this->getOrderStatusId($eventType);
            if (isset($orderStatus) && isset($orderId)) {
                xtc_db_query("UPDATE " . TABLE_ORDERS . " SET orders_status='" . $orderStatus . "' WHERE orders_id='" . $orderId . "'");
            }

            $this->successAction();
        } catch (Exception $exception){
            $this->log("An error occurred during Order Update", $this->_request);
        }
    }

    /**
     * @param $statusName
     *
     * @return mixed
     */
    function getOrderStatusId($statusName)
    {
        try {
            $statusArray = xtc_db_fetch_array(xtc_db_query("select orders_status_id from " . TABLE_ORDERS_STATUS . " where orders_status_name = 'Paymill [$statusName]' limit 1"));
            $status_id = $statusArray['orders_status_id'];

            if(empty($status_id) || $status_id == ''){
                $status_id = 1;
            }

            return $status_id;
        } catch (Exception $exception) {
            $this->log("Exception in getting Paymill status $statusName", var_export($exception, true));
        }
    }

    /**
     * Returns the state of the webhook option
     * @param $type
     * @return boolean
     */
    function getWebhookState($type)
    {
        return ((constant('MODULE_PAYMENT_PAYMILL_'.$type.'_WEBHOOKS') == 'True') ? true : false);
    }

    /**
     * Required the Libs WebHooks class
     *
     * @return void
     */
    function requireTransactions()
    {
        require_once('lib/Services/Paymill/Transactions.php');
    }

    /**
     * Required the Libs WebHooks class
     *
     * @return void
     */
    function requireRefunds()
    {
        require_once('lib/Services/Paymill/Refunds.php');
    }
}


text:
import dgram, { Socket, SocketType } from "dgram";

export interface RTPProxyOptions {
  disabled: boolean;
  isIPV6?: boolean;
  outgoingAddress: string;
  outgoingPort: number;
  outgoingSSRC: number;
}

/**
 * RTPProxy to proxy unencrypted RTP and RTCP
 *
 * At early days of HomeKit camera support, HomeKit allowed for unencrypted RTP stream.
 * The proxy was created to deal with RTCP and SSRC related stuff from external streams back in that days.
 * Later HomeKit removed support for unencrypted stream so it's mostly no longer useful anymore, only really for testing
 * with a custom HAP controller.
 */
export default class RTPProxy {

  startingPort: number = 10000;
  type: SocketType;
  outgoingAddress: string;
  outgoingPort: number;
  incomingPayloadType: number;
  outgoingSSRC: number;
  incomingSSRC: number | null;
  outgoingPayloadType: number | null;
  disabled: boolean;

  incomingRTPSocket!: Socket;
  incomingRTCPSocket!: Socket;
  outgoingSocket!: Socket;
  serverAddress?: string;
  serverRTPPort?: number;
  serverRTCPPort?: number;

  constructor(public options: RTPProxyOptions) {
    this.type = options.isIPV6 ? 'udp6' : 'udp4';

    this.startingPort = 10000;

    this.outgoingAddress = options.outgoingAddress;
    this.outgoingPort = options.outgoingPort;
    this.incomingPayloadType = 0;
    this.outgoingSSRC = options.outgoingSSRC;
    this.disabled = options.disabled;
    this.incomingSSRC = null;
    this.outgoingPayloadType = null;
  }

  setup = () => {
    return this.createSocketPair(this.type)
      .then((sockets) => {
        this.incomingRTPSocket = sockets[0];
        this.incomingRTCPSocket = sockets[1];

        return this.createSocket(this.type);
      }).then((socket) => {
        this.outgoingSocket = socket;
        this.onBound();
      });
  }

  destroy = () => {
    if (this.incomingRTPSocket) {
      this.incomingRTPSocket.close();
    }

    if (this.incomingRTCPSocket) {
      this.incomingRTCPSocket.close();
    }

    if (this.outgoingSocket) {
      this.outgoingSocket.close();
    }
  }

  incomingRTPPort = () => {
    const address = this.incomingRTPSocket.address();

    if (typeof address !== 'string') {
      return address.port;
    }
  }

  incomingRTCPPort = () => {
    const address = this.incomingRTCPSocket.address();

    if (typeof address !== 'string') {
      return address.port;
    }
  }

  outgoingLocalPort = () => {
    const address = this.outgoingSocket.address();

    if (typeof address !== 'string') {
      return address.port;
    }

    return 0; // won't happen
  }

  setServerAddress = (address: string) => {
    this.serverAddress = address;
  }

  setServerRTPPort = (port: number) => {
    this.serverRTPPort = port;
  }

  setServerRTCPPort = (port: number) => {
    this.serverRTCPPort = port;
  }

  setIncomingPayloadType = (pt: number) => {
    this.incomingPayloadType = pt;
  }

  setOutgoingPayloadType = (pt: number) => {
    this.outgoingPayloadType = pt;
  }

  sendOut = (msg: Buffer) => {
    // Just drop it if we're not setup yet, I guess.
    if(!this.outgoingAddress || !this.outgoingPort)
      return;

    this.outgoingSocket.send(msg, this.outgoingPort, this.outgoingAddress);
  }

  sendBack = (msg: Buffer) => {
    // Just drop it if we're not setup yet, I guess.
    if(!this.serverAddress || !this.serverRTCPPort)
      return;

    this.outgoingSocket.send(msg, this.serverRTCPPort, this.serverAddress);
  }

  onBound = () => {
    if(this.disabled)
      return;

    this.incomingRTPSocket.on('message', msg => {
      this.rtpMessage(msg);
    });

    this.incomingRTCPSocket.on('message', msg => {
      this.rtcpMessage(msg);
    });

    this.outgoingSocket.on('message', msg => {
      this.rtcpReply(msg);
    });
  }

  rtpMessage = (msg: Buffer) => {

    if(msg.length < 12) {
      // Not a proper RTP packet. Just forward it.
      this.sendOut(msg);
      return;
    }

    let mpt = msg.readUInt8(1);
    let pt = mpt & 0x7F;
    if(pt == this.incomingPayloadType) {
      // @ts-ignore
      mpt = (mpt & 0x80) | this.outgoingPayloadType;
      msg.writeUInt8(mpt, 1);
    }

    if(this.incomingSSRC === null)
      this.incomingSSRC = msg.readUInt32BE(4);

    msg.writeUInt32BE(this.outgoingSSRC, 8);
    this.sendOut(msg);
  }

  processRTCPMessage = (msg: Buffer, transform: (pt: number, packet: Buffer) => Buffer) => {
    let rtcpPackets = [];
    let offset = 0;
    while((offset + 4) <= msg.length) {
      let pt = msg.readUInt8(offset + 1);
      let len = msg.readUInt16BE(offset + 2) * 4;
      if((offset + 4 + len) > msg.length)
        break;
      let packet = msg.slice(offset, offset + 4 + len);

      packet = transform(pt, packet);

      if(packet)
        rtcpPackets.push(packet);

      offset += 4 + len;
    }

    if(rtcpPackets.length > 0)
      return Buffer.concat(rtcpPackets);

    return null;
  }

  rtcpMessage = (msg: Buffer) => {

    let processed = this.processRTCPMessage(msg, (pt, packet) => {
      if(pt != 200 || packet.length < 8)
        return packet;

      if(this.incomingSSRC === null)
        this.incomingSSRC = packet.readUInt32BE(4);
      packet.writeUInt32BE(this.outgoingSSRC, 4);
      return packet;
    });

    if(processed)
      this.sendOut(processed);
  }

  rtcpReply = (msg: Buffer) => {

    let processed = this.processRTCPMessage(msg, (pt, packet) => {
      if(pt != 201 || packet.length < 12)
        return packet;

      // Assume source 1 is the one we want to edit.
      // @ts-ignore
      packet.writeUInt32BE(this.incomingSSRC, 8);
      return packet;
    });

    if(processed)
      this.sendOut(processed);
  }

  createSocket = (type: SocketType): Promise<Socket> => {
    return new Promise(resolve => {
      const retry = () => {
        const socket = dgram.createSocket(type);

        const bindErrorHandler = () => {
          if(this.startingPort == 65535)
            this.startingPort = 10000;
          else
            ++this.startingPort;

          socket.close();
          retry();
        };

        socket.once('error', bindErrorHandler);

        socket.on('listening', () => {
          resolve(socket);
        });

        socket.bind(this.startingPort);
      };

      retry();
    });
  }

  createSocketPair = (type: SocketType): Promise<Socket[]> => {
    return new Promise(resolve => {
      const retry = () => {
        let socket1 = dgram.createSocket(type);
        let socket2 = dgram.createSocket(type);
        let state = {socket1: 0, socket2: 0};

        const recheck = () => {
          if(state.socket1 == 0 || state.socket2 == 0)
            return;

          if(state.socket1 == 2 && state.socket2 == 2) {
            resolve([socket1, socket2]);
            return;
          }

          if(this.startingPort == 65534)
            this.startingPort = 10000;
          else
            ++this.startingPort;

          socket1.close();
          socket2.close();

          retry();
        }

        socket1.once('error', function() {
          state.socket1 = 1;
          recheck();
        });

        socket2.once('error', function() {
          state.socket2 = 1;
          recheck();
        });

        socket1.once('listening', function() {
          state.socket1 = 2;
          recheck();
        });

        socket2.once('listening', function() {
          state.socket2 = 2;
          recheck();
        });

        socket1.bind(this.startingPort);
        socket2.bind(this.startingPort + 1);
      }

      retry();
    });
  }
}


text:
zeit.cms.MessageView = zeit.cms.View.extend({

    construct: function(url, target_id) {
        var self = this;
        arguments.callee.$.construct.call(self, url, target_id);
        self.events = [];
        self.initialize();
        MochiKit.Signal.connect(
            self, 'load', self, self.initialize);
        MochiKit.Signal.connect(self, 'before-load', function(event) {
            while(self.events.length) {
                MochiKit.Signal.disconnect(self.events.pop());
            }
        });
    },

    initialize: function() {
        var self = this;
        var messages = $('messages');
        if (messages == null) {
            return;
        }
        self.connect_toggle_button();
        self.fadeout();
    },

    fadeout: function() {
        var self = this;
        var messages = $('messages');
        var errors = MochiKit.DOM.getElementsByTagAndClassName(
            'li', 'error', messages);
        var warnings = MochiKit.DOM.getElementsByTagAndClassName(
            'li', 'warning', messages);
        var timeout = 0.5;
        if (errors.length > 0 || warnings.length > 0) {
            timeout = 60;
        }

        self.fade = MochiKit.Async.callLater(timeout, function() {
            MochiKit.Visual.fade(messages, {
                afterFinish: function() {
                    MochiKit.DOM.addElementClass(messages, 'hiddenMessages');
                    // remove opacity and display from fade
                    messages.setAttribute('style', '');
                    }
                });
        });
    },

    connect_toggle_button: function() {
        var self = this;
        var messages = $('messages');
        var showtoggle = $('messages_toggle');
        self.events.push(MochiKit.Signal.connect(
            messages, 'onclick', function(event) {
            self.fade.cancel();
            MochiKit.DOM.addElementClass(messages, 'hiddenMessages');
        }));
        self.events.push(MochiKit.Signal.connect(
            showtoggle, 'onclick', function(event) {
            self.fade.cancel();
            MochiKit.DOM.toggleElementClass('hiddenMessages', messages);
        }));
    }
});

MochiKit.Signal.connect(window, 'onload', function(event) {
    zeit.cms.messages = new zeit.cms.MessageView(
        window.application_url + '/@@messages', 'messages_container');
});


text:
/*
 * JNI helper functions.
 *
 * This file may be included by C or C++ code, which is trouble because jni.h
 * uses different typedefs for JNIEnv in each language.
 */
#ifndef _NATIVEHELPER_JNIHELP_H
#define _NATIVEHELPER_JNIHELP_H

#include "jni.h"
#include "utils/Log.h"

#ifndef NELEM
# define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
#endif

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Register one or more native methods with a particular class.
 */
int jniRegisterNativeMethods(C_JNIEnv* env, const char* className,
    const JNINativeMethod* gMethods, int numMethods);

/*
 * Throw an exception with the specified class and an optional message.
 *
 * Returns 0 on success, nonzero if something failed (e.g. the exception
 * class couldn't be found).
 *
 * Currently aborts the VM if it can't throw the exception.
 */
int jniThrowException(C_JNIEnv* env, const char* className, const char* msg);

/*
 * Throw a java.IO.IOException, generating the message from errno.
 */
int jniThrowIOException(C_JNIEnv* env, int errnum);

/*
 * Create a java.io.FileDescriptor given an integer fd
 */
jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd);

/*
 * Get an int file descriptor from a java.io.FileDescriptor
 */
int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor);

/*
 * Set an int file descriptor to a java.io.FileDescriptor
 */
void jniSetFileDescriptorOfFD(C_JNIEnv* env, jobject fileDescriptor, int value);

#ifdef __cplusplus
}
#endif

/*
 * For C++ code, we provide inlines that map to the C functions.  g++ always
 * inlines these, even on non-optimized builds.
 */
#if defined(__cplusplus) && !defined(JNI_FORCE_C)
inline int jniRegisterNativeMethods(JNIEnv* env, const char* className,
    const JNINativeMethod* gMethods, int numMethods)
{
    return jniRegisterNativeMethods(&env->functions, className, gMethods,
        numMethods);
}
inline int jniThrowException(JNIEnv* env, const char* className,
    const char* msg)
{
    return jniThrowException(&env->functions, className, msg);
}
inline int jniThrowIOException(JNIEnv* env, int errnum)
{
    return jniThrowIOException(&env->functions, errnum);
}
inline jobject jniCreateFileDescriptor(JNIEnv* env, int fd)
{
    return jniCreateFileDescriptor(&env->functions, fd);
}
inline int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor)
{
    return jniGetFDFromFileDescriptor(&env->functions, fileDescriptor);
}
inline void jniSetFileDescriptorOfFD(JNIEnv* env, jobject fileDescriptor,
    int value)
{
    return jniSetFileDescriptorOfFD(&env->functions, fileDescriptor, value);
}
#endif

#endif /*_NATIVEHELPER_JNIHELP_H*/


text:
'use strict';

var request = require('request');

module.exports = function (grunt) {
  var reloadPort = 35729, files;

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    develop: {
      server: {
        file: 'app.js'
      }
    },
    watch: {
      options: {
        nospawn: true,
        livereload: reloadPort
      },
      server: {
        files: [
          'app.js',
          'routes/*.js'
        ],
        tasks: ['develop', 'delayed-livereload']
      },
      js: {
        files: ['public/javascripts/*.js'],
        options: { livereload: reloadPort},
      },
      css: {
        files: ['public/stylesheets/*.css'],
        options: { livereload: reloadPort},
      },
      jade: {
        files: ['views/*.jade'],
        options: { livereload: reloadPort},
      }
    },
    exec: {
          mocha: {
              command: 'mocha test/*.js -R spec --timeout 15000',
              stdout: true,
              stderr: true
          }
      }
  });

  grunt.config.requires('watch.server.files');
  files = grunt.config('watch.server.files');
  files = grunt.file.expand(files);

  grunt.registerTask('delayed-livereload', 'Live reload after the node server has restarted.', function () {
    var done = this.async();
    setTimeout(function () {
      request.get('http://localhost:' + reloadPort + '/changed?files=' + files.join(','),  function(err, res) {
          var reloaded = !err && res.statusCode === 200;
          if (reloaded)
            grunt.log.ok('Delayed live reload successful.');
          else
            grunt.log.error('Unable to make a delayed live reload.');
          done(reloaded);
        });
    }, 500);
  });

  grunt.registerTask('default', ['develop', 'watch']);

  grunt.registerTask('test', [
      'exec:mocha'
  ]);
};


text:
package org.chromium.content_browsertests_apk;

import android.app.Application;

import org.chromium.base.PathUtils;
import org.chromium.content.app.LibraryLoader;
import org.chromium.content.browser.ResourceExtractor;

public class ContentBrowserTestsApplication extends Application {

    private static final String NATIVE_LIBRARY = "content_browsertests";
    private static final String[] MANDATORY_PAK_FILES = new String[] {"content_shell.pak"};
    private static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "content_shell";

    @Override
    public void onCreate() {
        super.onCreate();
        initializeApplicationParameters();
    }

    public static void initializeApplicationParameters() {
        ResourceExtractor.setMandatoryPaksToExtract(MANDATORY_PAK_FILES);
        LibraryLoader.setLibraryToLoad(NATIVE_LIBRARY);
        PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX);
    }

}


text:
import { CSSProperties } from 'glamor';
import { transformStyle } from './css';

export interface IImageOptions {
  width?: number;
  height?: number;
}

export interface IBackgroundImageStyles {
  backgroundImage: string;
  width?: number;
  height?: number;
  backgroundSize: string;
  backgroundRepeat: string;
}

export type FormatImage = (
  image1x: string | undefined,
  image2x: string | undefined,
  options?: IImageOptions,
) => IBackgroundImageStyles;

export type Falsy = undefined | null | false;
export class GlamorValue {}
export interface IFormatCss {
  (...styles: Array<React.CSSProperties | GlamorValue | Falsy>): GlamorValue;
  image: FormatImage;
}

export type CssProps = CSSProperties;
export type ClassName = (...styles: Array<CssProps | undefined>) => string;

export interface IStyle extends IFormatCss {
  className: ClassName;
  transform: typeof transformStyle;
  merge: (...rules: any[]) => CssProps;
}


text:
<?php

namespace UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="UserBundle\Entity\Repository\UserRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class User implements AdvancedUserInterface, \Serializable {

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;
    /**
     * @ORM\Column(type="string", length=25, nullable=true)
     */
    private $name;
    /**
     * @ORM\Column(type="string", length=25, nullable=true)
     */
    private $surename;
    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $address;
    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $city;
    /**
     * @ORM\Column(type="string", length=20, nullable=true)
     */
    private $title;
    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $skype;
    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $google;
    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $type;
    /**
     * @ORM\Column(type="string", length=100, nullable=true)
     */
    private $companyName;
    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $companyVAT;
    /**
     * @ORM\Column(type="integer", length=11, nullable=true)
     */
    private $zip;
    /**
     * @ORM\Column(type="string", length=25, nullable=true)
     */
    private $phone;
    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;
    /**
     * @ORM\Column(type="string", length=60, unique=true)
     */
    private $email;
    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
     */
    private $roles;
    /**
     * @ORM\OneToMany(targetEntity="\AppBundle\Entity\Accommodation", mappedBy="user", cascade={"all"})
     */
    private $accommodations;
    /**
     * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\Country", inversedBy="users")
     */
    private $country;
    /**
     * @ORM\ManyToMany(targetEntity="\AppBundle\Entity\Unit", inversedBy="wishlistUsers", cascade={"all"})
     * @ORM\JoinTable(name="wishlists")
     */
    private $wishlistUnits;
    /**
     * @ORM\ManyToMany(targetEntity="\AppBundle\Entity\Language", inversedBy="users")
     */
    private $languages;
    /**
     * @ORM\OneToMany(targetEntity="\AppBundle\Entity\Booking", mappedBy="user")
     */
    private $bookings;
    /**
     * @ORM\OneToMany(targetEntity="\AppBundle\Entity\PostComment", mappedBy="user")
     */
    private $comments;
    /**
     * @ORM\OneToMany(targetEntity="\AppBundle\Entity\Review", mappedBy="tourist")
     */
    private $reviews;
    /**
     * @ORM\OneToMany(targetEntity="\AppBundle\Entity\AdditionalOffer\AdditionalOffer", mappedBy="host", cascade={"all"})
     */
    private $additionalOffer;
    /**
     * @ORM\OneToMany(targetEntity="Message", mappedBy="userTo")
     */
    private $messageTo;
    /**
     * @ORM\OneToMany(targetEntity="Message", mappedBy="userFrom")
     */
    private $messageFrom;
    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;
    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $note;
    /**
     * @ORM\Column(type="string", length=255)
     */
    private $hash;
    /**
     * created Time/Date
     * @var \DateTime
     * @ORM\Column(type="datetime", nullable=false)
     */
    private $createdAt;

    public function __construct() {
        // $this->isActive = true;
        // may not be needed, see section on salt below
        // $this->salt = md5(uniqid(null, true));
        $this->roles = new ArrayCollection();
    }

    /**
     * Set createdAt
     * @ORM\PrePersist
     */
    public function setCreatedAt() {
        $this->createdAt = new \DateTime();
    }

    public function getCreatedAt() {
        return $this->createdAt;
    }

    /**
     * Set hash
     * @ORM\PrePersist
     */
    public function setHash() {
        $newHash = password_hash(microtime() . uniqid(), PASSWORD_BCRYPT, array('cost' => 12));

        $this->hash = str_replace('/', '', $newHash);

        return $this;
    }

    public function getHash() {
        return $this->hash;
    }

    public function isAccountNonExpired() {
        return true;
    }

    public function isAccountNonLocked() {
        return true;
    }

    public function isCredentialsNonExpired() {
        return true;
    }

    public function isEnabled() {
        return $this->isActive;
    }

    /**
     * @ORM\PrePersist
     */
    public function encryptPassword() {
        $this->password = password_hash($this->password, PASSWORD_BCRYPT, array('cost' => 12));
    }

    public function getFullName() {
        return $this->name . ' ' . $this->surename;
    }

    /**
     * @return string
     */
    public function __toString() {
        return strval($this->id);
    }

    /**
     * @inheritDoc
     */
    public function getUsername() {
        return $this->username;
    }

    /**
     * @inheritDoc
     */
    public function getSalt() {
        // you *may* need a real salt depending on your encoder
        // see section on salt below
        return null;
    }

    /**
     * @inheritDoc
     */
    public function getPassword() {
        return $this->password;
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials() {
    }

    /**
     * @see \Serializable::serialize()
     */
    public function serialize() {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt,
        ));
    }

    /**
     * @see \Serializable::unserialize()
     */
    public function unserialize($serialized) {
        list (
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt
            ) = unserialize($serialized);
    }

    /**
     * Get id
     * @return integer
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set username
     * @param string $username
     * @return User
     */
    public function setUsername($username) {
        $this->username = $username;
        return $this;
    }

    /**
     * Set password
     * @param string $password
     * @return User
     */
    public function setPassword($password) {
        $this->password = $password;
        return $this;
    }

    /**
     * Set email
     * @param string $email
     * @return User
     */
    public function setEmail($email) {
        $this->email = $email;
        return $this;
    }

    /**
     * Get email
     * @return string
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Set isActive
     * @param boolean $isActive
     * @return User
     */
    public function setIsActive($isActive) {
        $this->isActive = $isActive;
        return $this;
    }

    /**
     * Get isActive
     * @return boolean
     */
    public function getIsActive() {
        return $this->isActive;
    }

    /**
     * @inheritDoc
     */
    public function getRoles() {
        return $this->roles->toArray();
    }

    /**
     * @param Collection $roles
     */
    public function setRoles(\UserBundle\Entity\Role $roles) {
        foreach ($roles as $role) {
            $this->addRole($role);
        }
    }

    /**
     * Add roles
     * @param \UserBundle\Entity\Role $roles
     * @return User
     */
    public function addRole(\UserBundle\Entity\Role $roles) {
        $this->roles[] = $roles;
        return $this;
    }

    /**
     * Remove roles
     * @param \UserBundle\Entity\Role $roles
     */
    public function removeRole(\UserBundle\Entity\Role $roles) {
        $this->roles->removeElement($roles);
    }

    /**
     * Set name
     * @param string $name
     * @return User
     */
    public function setName($name) {
        $this->name = $name;
        return $this;
    }

    /**
     * Get name
     * @return string
     */
    public function getName() {
        return $this->name;
    }

    /**
     * Set surename
     * @param string $surename
     * @return User
     */
    public function setSurename($surename) {
        $this->surename = $surename;
        return $this;
    }

    /**
     * Get surename
     * @return string
     */
    public function getSurename() {
        return $this->surename;
    }

    /**
     * Set address
     * @param string $address
     * @return User
     */
    public function setAddress($address) {
        $this->address = $address;
        return $this;
    }

    /**
     * Get address
     * @return string
     */
    public function getAddress() {
        return $this->address;
    }

    /**
     * Set phone
     * @param string $phone
     * @return User
     */
    public function setPhone($phone) {
        $this->phone = $phone;
        return $this;
    }

    /**
     * Get phone
     * @return string
     */
    public function getPhone() {
        return $this->phone;
    }

    /**
     * Set photo
     * @param string $photo
     * @return User
     */
    public function setPhoto($photo) {
        $this->photo = $photo;
        return $this;
    }

    /**
     * Get photo
     * @return string
     */
    public function getPhoto() {
        return $this->photo;
    }

    /**
     * Add accommodations
     * @param \AppBundle\Entity\Accommodation $accommodations
     * @return User
     */
    public function addAccommodation(\AppBundle\Entity\Accommodation $accommodations) {
        $this->accommodations[] = $accommodations;
        return $this;
    }

    /**
     * Remove accommodations
     * @param \AppBundle\Entity\Accommodation $accommodations
     */
    public function removeAccommodation(\AppBundle\Entity\Accommodation $accommodations) {
        $this->accommodations->removeElement($accommodations);
    }

    /**
     * Get accommodations
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAccommodations() {
        return $this->accommodations;
    }

    /**
     * Add bookings
     * @param \AppBundle\Entity\Booking $bookings
     * @return User
     */
    public function addBooking(\AppBundle\Entity\Booking $bookings) {
        $this->bookings[] = $bookings;
        return $this;
    }

    /**
     * Remove bookings
     * @param \AppBundle\Entity\Booking $bookings
     */
    public function removeBooking(\AppBundle\Entity\Booking $bookings) {
        $this->bookings->removeElement($bookings);
    }

    /**
     * Get bookings
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getBookings() {
        return $this->bookings;
    }

    /**
     * Set type
     * @param string $type
     * @return User
     */
    public function setType($type) {
        $this->type = $type;
        return $this;
    }

    /**
     * Get type
     * @return string
     */
    public function getType() {
        return $this->type;
    }

    /**
     * Set companyName
     * @param string $companyName
     * @return User
     */
    public function setCompanyName($companyName) {
        $this->companyName = $companyName;
        return $this;
    }

    /**
     * Get companyName
     * @return string
     */
    public function getCompanyName() {
        return $this->companyName;
    }

    /**
     * Set companyVAT
     * @param string $companyVAT
     * @return User
     */
    public function setCompanyVAT($companyVAT) {
        $this->companyVAT = $companyVAT;
        return $this;
    }

    /**
     * Get companyVAT
     * @return string
     */
    public function getCompanyVAT() {
        return $this->companyVAT;
    }

    /**
     * Set zip
     * @param integer $zip
     * @return User
     */
    public function setZip($zip) {
        $this->zip = $zip;
        return $this;
    }

    /**
     * Get zip
     * @return integer
     */
    public function getZip() {
        return $this->zip;
    }

    /**
     * Add languages
     * @param \AppBundle\Entity\Language $languages
     * @return User
     */
    public function addLanguage(\AppBundle\Entity\Language $languages) {
        $this->languages[] = $languages;
        return $this;
    }

    /**
     * Remove languages
     * @param \AppBundle\Entity\Language $languages
     */
    public function removeLanguage(\AppBundle\Entity\Language $languages) {
        $this->languages->removeElement($languages);
    }

    /**
     * Get languages
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getLanguages() {
        return $this->languages;
    }

    /**
     * Set title
     * @param string $title
     * @return User
     */
    public function setTitle($title) {
        $this->title = $title;
        return $this;
    }

    /**
     * Get title
     * @return string
     */
    public function getTitle() {
        return $this->title;
    }

    /**
     * Set skype
     * @param string $skype
     * @return User
     */
    public function setSkype($skype) {
        $this->skype = $skype;
        return $this;
    }

    /**
     * Get skype
     * @return string
     */
    public function getSkype() {
        return $this->skype;
    }

    /**
     * Set google
     * @param string $google
     * @return User
     */
    public function setGoogle($google) {
        $this->google = $google;
        return $this;
    }

    /**
     * Get google
     * @return string
     */
    public function getGoogle() {
        return $this->google;
    }

    /**
     * Set country
     * @param \AppBundle\Entity\Country $country
     * @return User
     */
    public function setCountry(\AppBundle\Entity\Country $country = null) {
        $this->country = $country;
        return $this;
    }

    /**
     * Get country
     * @return \AppBundle\Entity\Country
     */
    public function getCountry() {
        return $this->country;
    }

    /**
     * Set city
     * @param string $city
     * @return User
     */
    public function setCity($city) {
        $this->city = $city;
        return $this;
    }

    /**
     * Get city
     * @return string
     */
    public function getCity() {
        return $this->city;
    }

    /**
     * Add wishlistUnits
     * @param \AppBundle\Entity\Unit $wishlistUnits
     * @return User
     */
    public function addWishlistUnit(\AppBundle\Entity\Unit $wishlistUnits) {
        $this->wishlistUnits[] = $wishlistUnits;

        return $this;
    }

    /**
     * Remove wishlistUnits
     * @param \AppBundle\Entity\Unit $wishlistUnits
     */
    public function removeWishlistUnit(\AppBundle\Entity\Unit $wishlistUnits) {
        $this->wishlistUnits->removeElement($wishlistUnits);
    }

    /**
     * Get wishlistUnits
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getWishlistUnits() {
        return $this->wishlistUnits;
    }

    /**
     * Add messageTo
     * @param \UserBundle\Entity\Message $messageTo
     * @return User
     */
    public function addMessageTo(\UserBundle\Entity\Message $messageTo) {
        $this->messageTo[] = $messageTo;

        return $this;
    }

    /**
     * Remove messageTo
     * @param \UserBundle\Entity\Message $messageTo
     */
    public function removeMessageTo(\UserBundle\Entity\Message $messageTo) {
        $this->messageTo->removeElement($messageTo);
    }

    /**
     * Get messageTo
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMessageTo() {
        return $this->messageTo;
    }

    /**
     * Add messageFrom
     * @param \UserBundle\Entity\Message $messageFrom
     * @return User
     */
    public function addMessageFrom(\UserBundle\Entity\Message $messageFrom) {
        $this->messageFrom[] = $messageFrom;

        return $this;
    }

    /**
     * Remove messageFrom
     * @param \UserBundle\Entity\Message $messageFrom
     */
    public function removeMessageFrom(\UserBundle\Entity\Message $messageFrom) {
        $this->messageFrom->removeElement($messageFrom);
    }

    /**
     * Get messageFrom
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMessageFrom() {
        return $this->messageFrom;
    }

    /**
     * Add comments
     * @param \AppBundle\Entity\PostComment $comments
     * @return User
     */
    public function addComment(\AppBundle\Entity\PostComment $comments) {
        $this->comments[] = $comments;

        return $this;
    }

    /**
     * Remove comments
     * @param \AppBundle\Entity\PostComment $comments
     */
    public function removeComment(\AppBundle\Entity\PostComment $comments) {
        $this->comments->removeElement($comments);
    }

    /**
     * Get comments
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getComments() {
        return $this->comments;
    }

    /**
     * Set note
     * @param string $note
     * @return User
     */
    public function setNote($note) {
        $this->note = $note;

        return $this;
    }

    /**
     * Get note
     * @return string
     */
    public function getNote() {
        return $this->note;
    }

    /**
     * Add reviews
     * @param \AppBundle\Entity\Review $reviews
     * @return User
     */
    public function addReview(\AppBundle\Entity\Review $reviews) {
        $this->reviews[] = $reviews;

        return $this;
    }

    /**
     * Remove reviews
     * @param \AppBundle\Entity\Review $reviews
     */
    public function removeReview(\AppBundle\Entity\Review $reviews) {
        $this->reviews->removeElement($reviews);
    }

    /**
     * Get reviews
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getReviews() {
        return $this->reviews;
    }

    /**
     * Set additionalOffer
     *
     * @param \AppBundle\Entity\AdditionalOffer\AdditionalOffer $additionalOffer
     * @return User
     */
    public function setAdditionalOffer(\AppBundle\Entity\AdditionalOffer\AdditionalOffer $additionalOffer = null) {
        $this->additionalOffer = $additionalOffer;

        return $this;
    }

    /**
     * Get additionalOffer
     *
     * @return \AppBundle\Entity\AdditionalOffer\AdditionalOffer
     */
    public function getAdditionalOffer() {
        return $this->additionalOffer;
    }
}


text:
from measures.graphcreation.ForwardedMessages import ForwardedMessages

class SentFCompositionMessages(ForwardedMessages):
	"""Total number of sent collision messages"""

	def __init__(self, period, simulationTime):
		ForwardedMessages.__init__(self, 'graphsearch.forward.message.FCompositionMessage', period, simulationTime)