text:
<?php

declare(strict_types=1);

namespace Oppa;

/**
 * @package Oppa
 * @object  Oppa\Mapper
 * @author  Kerem Güneş <k-gun@mail.com>
 */
final class Mapper
{
    /**
     * Type constants.
     * @const string
     */
    public const
        // ints
        DATA_TYPE_INT        = 'int',
        DATA_TYPE_BIGINT     = 'bigint',
        DATA_TYPE_TINYINT    = 'tinyint',
        DATA_TYPE_SMALLINT   = 'smallint',
        DATA_TYPE_MEDIUMINT  = 'mediumint',
        DATA_TYPE_INTEGER    = 'integer',
        DATA_TYPE_SERIAL     = 'serial',
        DATA_TYPE_BIGSERIAL  = 'bigserial',
        // floats
        DATA_TYPE_FLOAT      = 'float',
        DATA_TYPE_DECIMAL    = 'decimal',
        DATA_TYPE_DOUBLE     = 'double',
        DATA_TYPE_DOUBLEP    = 'double precision',
        DATA_TYPE_REAL       = 'real',
        DATA_TYPE_NUMERIC    = 'numeric',
        // boolean
        DATA_TYPE_BOOLEAN    = 'boolean',
        // bit
        DATA_TYPE_BIT        = 'bit';

    /**
     * Map.
     * @var array
     */
    protected $map = [];

    /**
     * Map options.
     * @var array
     */
    protected $mapOptions = [
        'bool' => false, // converts bits & tinyints to booleans
    ];

    /**
     * Constructor.
     * @param array $mapOptions
     */
    public function __construct(array $mapOptions = [])
    {
        $this->setMapOptions($mapOptions);
    }

    /**
     * Set map.
     * @param  array $map
     * @return void
     */
    public function setMap(array $map): void
    {
        $this->map = $map;
    }

    /**
     * Get map.
     * @return array
     */
    public function getMap(): array
    {
        return $this->map;
    }

    /**
     * Set map options.
     * @param  array $mapOptions
     * @return void
     */
    public function setMapOptions(array $mapOptions): void
    {
        $this->mapOptions = array_merge($this->mapOptions, $mapOptions);
    }

    /**
     * Get map options.
     * @return array
     */
    public function getMapOptions(): array
    {
        return $this->mapOptions;
    }

    /**
     * Map (given data by key).
     * @param  string $key Table name actually, @see Oppa\Query\Result\Mysql:process()
     * @param  array  $data
     * @return array
     */
    public function map(string $key, array $data): array
    {
        $fields = $this->map[$key] ?? null;
        if (empty($fields) || empty($data)) {
            return $data;
        }

        foreach ($fields as $fieldName => $fieldProperties) {
            foreach ($data as &$dat) {
                foreach ($dat as $name => $value) {
                    if ($name == $fieldName) { // match field?
                        if (is_array($dat)) {
                            $dat[$name] = $this->cast($value, $fieldProperties);
                        } elseif (is_object($dat)) {
                            $dat->{$name} = $this->cast($value, $fieldProperties);
                        }
                    }
                }
            }
        }

        return $data;
    }

    /**
     * Cast (type-cast by data type).
     * @param  scalar|null $value
     * @param  array       $properties
     * @return scalar|null
     */
    public function cast($value, array $properties)
    {
        [$type, $length, $nullable] = $properties;

        // nullable?
        if ($value === null && $nullable) {
            return $value;
        }

        // int, float, bool
        switch ($type) {
            case 'int': return (int) $value;
            case 'float': return (float) $value;
            case 'bool': return ($value === 't') ? true : false;
        }

        // bit
        if ($this->mapOptions['bool'] && $type == 'bit' && $length == 1) {
            // bool cast
            $value = (string) $value;
            if ($value === '0' || $value === '1') { // @important
                return (bool) $value;
            }
        }

        return $value;
    }

    /**
     * Normalize type.
     * @param  string $type
     * @return string
     */
    public static function normalizeType(string $type): string
    {
        switch ($type) {
            case self::DATA_TYPE_INT:
            case self::DATA_TYPE_BIGINT:
            case self::DATA_TYPE_TINYINT:
            case self::DATA_TYPE_SMALLINT:
            case self::DATA_TYPE_MEDIUMINT:
            case self::DATA_TYPE_INTEGER:
            case self::DATA_TYPE_SERIAL:
            case self::DATA_TYPE_BIGSERIAL:
                return 'int';
            case self::DATA_TYPE_FLOAT:
            case self::DATA_TYPE_DECIMAL:
            case self::DATA_TYPE_DOUBLE:
            case self::DATA_TYPE_DOUBLEP:
            case self::DATA_TYPE_REAL:
            case self::DATA_TYPE_NUMERIC:
                return 'float';
            case self::DATA_TYPE_BOOLEAN:
                return 'bool';
            case self::DATA_TYPE_BIT:
                return 'bit';
        }

        // all others
        return 'string';
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <data xmlns="http://www.netbeans.org/ns/make-project-private/1">
        <activeConfTypeElem>1</activeConfTypeElem>
        <activeConfIndexElem>0</activeConfIndexElem>
    </data>
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/media/kuzko/Data/Hubic/github/Cours/C/TP3/main.c</file>
        </group>
    </open-files>
</project-private>

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <QWidget>
#include <vector>
#include <QDebug>
#include <iostream>

// QT Includes
#include <QWidget>
#include <QLayout>
#include <QPainter>
#include <QDebug>
#include <QRect>
#include <QPaintEvent>
#include <QTableWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>

// Std Includes
#include <map>
#include <vector>
#include <tuple>

#include <iostream>
#include <cstdlib>

// project includes
#include "datastore.h"
#include "qrangeslider.h"

#include "qrangeslider.h"
#include "parallelcoordinatesglobals.h"
#include "datastore.h"

#include "qrangesliderobserver.h"

#include "parallelcoordinatesworker.h"
#include "parallelcoordinatesworker.cpp" // <- As this is a template class
#include "parallelcoordinatesworkerobserver.h"

using namespace std;

template<class T>
class ParallelCoordinatesWidget : public QWidget,
                                  public QRangeSliderObserver,
                                  public ParallelCoordinatesWorkerObserver
{
private:
    const int marginBottom = 50;

    std::vector<double> sliderRangeDiffs;

    ParallelCoordinatesWorker<T> worker;

    vector<QRangeSlider*> slidersUnordered;

    DataStore<T>* dataStorePtr=NULL;
    vector<int> dataOrder;

    T* minValPtr;
    T* maxValPtr;

    bool minMaxValInitialized = false;
    bool minMaxGUISet = false;

    vector<QRangeSlider*> sliders;
    vector<std::size_t> sliderOrdersNrs;

    QPixmap pm;

    void reorderSliders();
    // void reduceDrawingDataSet();
    // void renderLines();

protected:
    void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
    void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
    void resizeEvent(QResizeEvent* event) Q_DECL_OVERRIDE;
    void parallelCoordinatesWorkerCalculationDone() Q_DECL_OVERRIDE;

public:
    ParallelCoordinatesWidget(QWidget *parent = nullptr);

    void clearDataSet();
    void recalculateDrawingLines();
    void setMinMaxGUI();
    void setDataStorePtr(DataStore<T>* dataStore);

    void setDrawNotInRange(bool drawNotInRange);
    void calcDataInBackground();

    void qrangeSliderTextboxFocused(QRangeSlider* source);
    void qrangeSliderMinMaxValChanged(QRangeSlider* source);

};

template <class T>
ParallelCoordinatesWidget<T>::ParallelCoordinatesWidget(QWidget *parent): QWidget(parent)
{
    srand (time(NULL));

    this->setMouseTracking(true);

    int singleWidth = (parent->width()/nrOfDimensions);

    for (int i=0; i<nrOfDimensions; i++) {
        QRangeSlider* aSlider = new QRangeSlider(this);
        this->slidersUnordered.push_back(aSlider);

        aSlider->setGeometry(QRect(0+ singleWidth*i,0,singleWidth,parent->height()-marginBottom));

        //hLayout->addWidget(aSlider);

        // define data order
        dataOrder.push_back(i);
    }

    for (size_t j=0; j<this->slidersUnordered.size();j++) {
        QRangeSlider* aSlider = this->slidersUnordered.at(j);
        aSlider->registerQRangeSliderObserver(this);
    }

    //vLayout->addLayout(hLayout);
    //this->setLayout(vLayout);

    this->reorderSliders();

    int xPositionSliders[nrOfDimensions];
    for (size_t i=0; i<sliders.size(); i++) {
        QRangeSlider* slider = sliders.at(i);
        xPositionSliders[i] = slider->x()+
                              slider->getXPositionBar()+
                              slider->getSliderWidth()/2;
    }

    worker.initialize(xPositionSliders, this->width(), this->height(), &this->palette(), this->backgroundRole());
    worker.registerParallelCoordinatesWorkerObserver(this);
}

template <class T>
void ParallelCoordinatesWidget<T>::setDataStorePtr(DataStore<T>* dataStore) {
    this->dataStorePtr = dataStore;

    // Set Label Texts
    std::vector<std::string> labelTexts = dataStore->getLabelTexts();

    for (std::size_t idx=0; idx<labelTexts.size(); idx++) {
      sliders[idx]->setLabel(labelTexts[idx]);
    }

    minValPtr = dataStore->getMinValPtr();
    maxValPtr = dataStore->getMaxValPtr();

    this->setMinMaxGUI();

    // Set dataSets also in worker thread...
    worker.setDataStorePtr(dataStore);
}

template <class T>
void ParallelCoordinatesWidget<T>::clearDataSet() {
    dataStorePtr->clearData();
    this->update();
}

template <class T>
void ParallelCoordinatesWidget<T>::setMinMaxGUI() {

    reorderSliders();

    for (int i=0; i<this->sliders.size(); i++) {
        sliders[i]->setMinVal(minValPtr[i]);
        sliders[i]->setMaxVal(maxValPtr[i]);
    }

    minMaxGUISet = true;

    calcDataInBackground();
}

template <class T>
void ParallelCoordinatesWidget<T>::mouseMoveEvent(QMouseEvent *event) {
    //if (!moveSlider) return;

    int mouseX =  event->pos().x();
    int mouseY  = event->pos().y();

    // Unset highlight as events are not always fired in control...

    foreach (QRangeSlider* slider, findChildren<QRangeSlider*>()) {
        if (slider->shallMove()) {
            std::cout << "ShallMove" << std::endl;
/*        if (
            (mouseX >= slider->pos().x() &&
             mouseX <  slider->pos().x() + slider->width()) &&
            (mouseY >= slider->pos().y() &&
             mouseY < slider->pos().y() + slider->height())
            ) {
*/
            slider->move(mouseX, mouseY);
            this->update();
            //slider->unsetHighlights();
        }
    }

    // Remember diffs

    sliderRangeDiffs.clear();
    for (int i=0; i<nrOfDimensions; i++) {
        sliderOrdersNrs[i];
        sliderRangeDiffs.push_back(static_cast<double>(sliders[sliderOrdersNrs[i]]->pos().x())/static_cast<double>(this->parentWidget()->width()));
    }

}

template <class T>
void ParallelCoordinatesWidget<T>::qrangeSliderTextboxFocused(QRangeSlider* source) {
    for (int i=0; i<this->slidersUnordered.size();i++) {
        QRangeSlider* aSlider = this->slidersUnordered.at(i);
        if (source!=aSlider) aSlider->deselect();
    }
}

template <class T>
void ParallelCoordinatesWidget<T>::qrangeSliderMinMaxValChanged(QRangeSlider* source) {
    calcDataInBackground();
}

template <class T>
void ParallelCoordinatesWidget<T>::paintEvent(QPaintEvent *evt) {

    if (this->sliders.size()==0) return;
    QRangeSlider* first = sliders.at(0);
    QRangeSlider* last = sliders.at(sliders.size()-1);

    int startX =  first->x()+first->getXPositionBar()+first->getSliderWidth()/2;
    int endX = last->x()+last->getXPositionBar()+last->getSliderWidth()/2;

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    //std::cout << "Drawing from " << startX << " " << first->getSlideBarStartY() << " to:" << endX-startX << " " <<first->getSlideBarHeight() << std::endl;

    painter.drawPixmap(startX,first->getSlideBarStartY(),endX-startX, first->getSlideBarHeight(), pm);
    //pm.save("/home/wolfgang/test.png");
}

template <class T>
void ParallelCoordinatesWidget<T>::reorderSliders() {

    // Find QRange sliders in children and sort them according to their Xorder in a vector
    multimap<int, QRangeSlider*> rangeSlidersOrdered;

    std::cout << "Slider Unordered Positions:";

    for (vector<QRangeSlider*>::iterator it = slidersUnordered.begin(); it!=slidersUnordered.end(); ++it) {
        QRangeSlider* slider = *it;
        rangeSlidersOrdered.insert(pair<int, QRangeSlider*>(slider->pos().x(), slider));
        std::cout << slider->pos().x() << " ";
    }

    std::cout << std::endl;

    this->sliders.clear();
    this->sliderOrdersNrs.clear();

    for (multimap<int, QRangeSlider*>::iterator it = rangeSlidersOrdered.begin(); it!=rangeSlidersOrdered.end(); ++it) {
         QRangeSlider* slider = (*it).second;

        this->sliders.push_back(slider);

         for (int idx=0; idx<slidersUnordered.size(); ++idx) {
             if (slidersUnordered[idx]->pos().x()==(*it).first) {
                 sliderOrdersNrs.push_back(idx);
                 break;
             }
         }
    }

    /*
    // Replace widget order so that a window resize event will trigger the layout mechanism to work in correct order

    QHBoxLayout* hBoxLayout = (QHBoxLayout*) this->layout()->children().at(0);

    for (QRangeSlider* slider : slidersUnordered) {
        hBoxLayout->removeWidget(slider);
    }

    for (std::size_t idx = 0; idx<sliderOrdersNrs.size(); ++idx) {
        hBoxLayout->addWidget(slidersUnordered[sliderOrdersNrs[idx]]);
    }
    */

}

template<class T>
void ParallelCoordinatesWidget<T>::setDrawNotInRange(bool drawNotInRange) {
    worker.drawNotInRange = drawNotInRange;
}

template<class T>
void ParallelCoordinatesWidget<T>::calcDataInBackground() {
    // cout << "Widget Size: " << this->width() << " " << this->height() << endl;

    // Order slider along x-Axis
    this->reorderSliders();

    if (this->sliders.size()==0) return;

    // Determine dimensions of Image to calculate...
    int imageHeight = this->sliders.at(0)->getSlideBarHeight();

    std::cout << "Image Height:" << imageHeight << std::endl;

    QRangeSlider* first = this->sliders.at(0);
    QRangeSlider* last = this->sliders.at(this->sliders.size()-1);

    int startX = first->x()+
                 first->getXPositionBar()+
                 first->getSliderWidth()/2;
    int endX = last->x()+
            last->getXPositionBar()+
            last->getSliderWidth()/2;

    int imageWidth = endX-startX;

    worker.resize(imageWidth, imageHeight);

    // Determine positions of dimensions...
    int xPositionSliders[nrOfDimensions];

    for (size_t i=0; i<sliders.size(); i++) {

        QRangeSlider* slider = sliders.at(i);
        xPositionSliders[i] = slider->x()+
                              slider->getXPositionBar()+
                              slider->getSliderWidth()/2 -startX;

       // cout << "XPos set is " <<  xPositionSliders[i]  << endl;
    }

    worker.setXPositionDimensions(xPositionSliders);

    T minValSliders[nrOfDimensions];
    T maxValSliders[nrOfDimensions];

    for (size_t i=0; i<sliders.size(); i++) {
        QRangeSlider* slider = sliders.at(i);
        minValSliders[i] = slider->getCurrentSetMinVal();
        maxValSliders[i] = slider->getCurrentSetMaxVal();
    }
    worker.setMinMaxValScope(minValSliders, maxValSliders);

    bool minValDisplayedOnTop[nrOfDimensions];
    for (size_t i=0; i<sliders.size(); i++) {
        QRangeSlider* slider = sliders.at(i);
        minValDisplayedOnTop[sliderOrdersNrs[i]] = slider->getMinValDisplayedOnTop();
    }

    worker.setMinValDisplayedOnTop(minValDisplayedOnTop);

    /*
    if (worker.isRunning()) {
        worker.terminate();
    }*/

    std::cout << std::endl;

    worker.setSliderOrders(sliderOrdersNrs);

    worker.start();
}

template<class T>
void ParallelCoordinatesWidget<T>::parallelCoordinatesWorkerCalculationDone() {
    cout << "Calculation done" << endl;
    pm = QPixmap::fromImage(worker.getImage());
    update();

    for (QRangeSlider* slider : sliders) {
        slider->recalcPositions();
        slider->update();
    }

}

template<class T>
void ParallelCoordinatesWidget<T>::resizeEvent(QResizeEvent* event) {

//    QHBoxLayout* hBoxLayout = (QHBoxLayout*)this->layout()->children().at(0);

    /*
    // Redorder QRange Sliders as after a resize the order seems to be restored from the sequence....
    QHBoxLayout* hBoxLayout = (QHBoxLayout*)this->layout()->children().at(0);

    for (QRangeSlider* slider : slidersUnordered) {
        hBoxLayout->removeWidget(slider);
    }

    for (std::size_t idx = 0; idx<sliderOrdersNrs.size(); ++idx) {
        hBoxLayout->addWidget(slidersUnordered[sliderOrdersNrs[idx]]);
    }*/

    int singleWidth = this->parentWidget()->width() / nrOfDimensions;

    std::vector<double> xVals;
    std::vector<double> diffs;

    if (sliderRangeDiffs.size()==nrOfDimensions)
    for (int i=0; i<nrOfDimensions; i++) {
        this->slidersUnordered[i]->setGeometry(QRect(sliderRangeDiffs[i]*this->parentWidget()->width(),0,singleWidth,parentWidget()->height()-marginBottom));

    }

    calcDataInBackground();
}


text:
package com.linkedin.drelephant.spark.fetchers

import scala.async.Async
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration.{Duration, SECONDS}
import scala.util.{Try, Success, Failure}
import scala.util.control.NonFatal

import com.linkedin.drelephant.analysis.{AnalyticJob, ElephantFetcher}
import com.linkedin.drelephant.configurations.fetcher.FetcherConfigurationData
import com.linkedin.drelephant.spark.data.SparkApplicationData
import com.linkedin.drelephant.util.SparkUtils
import org.apache.hadoop.conf.Configuration
import org.apache.log4j.Logger
import org.apache.spark.SparkConf

/**
  * A fetcher that gets Spark-related data from a combination of the Spark monitoring REST API and Spark event logs.
  */
class SparkFetcher(fetcherConfigurationData: FetcherConfigurationData)
    extends ElephantFetcher[SparkApplicationData] {
  import SparkFetcher._
  import Async.{async, await}
  import ExecutionContext.Implicits.global

  private val logger: Logger = Logger.getLogger(classOf[SparkFetcher])

  val eventLogUri = Option(fetcherConfigurationData.getParamMap.get(LOG_LOCATION_URI_XML_FIELD))
  logger.info("The event log location of Spark application is set to " + eventLogUri)

  private[fetchers] lazy val hadoopConfiguration: Configuration = new Configuration()

  private[fetchers] lazy val sparkUtils: SparkUtils = SparkUtils

  private[fetchers] lazy val sparkConf: SparkConf = {
    val sparkConf = new SparkConf()
    sparkUtils.getDefaultPropertiesFile() match {
      case Some(filename) => sparkConf.setAll(sparkUtils.getPropertiesFromFile(filename))
      case None => throw new IllegalStateException("can't find Spark conf; please set SPARK_HOME or SPARK_CONF_DIR")
    }
    sparkConf
  }

  private[fetchers] lazy val eventLogSource: EventLogSource = {
    val eventLogEnabled = sparkConf.getBoolean(SPARK_EVENT_LOG_ENABLED_KEY, false)
    val useRestForLogs = Option(fetcherConfigurationData.getParamMap.get("use_rest_for_eventlogs"))
      .exists(_.toBoolean)
    if (!eventLogEnabled) {
      EventLogSource.None
    } else if (useRestForLogs) EventLogSource.Rest else EventLogSource.WebHdfs
  }

  private[fetchers] lazy val shouldProcessLogsLocally = (eventLogSource == EventLogSource.Rest) &&
    Option(fetcherConfigurationData.getParamMap.get("should_process_logs_locally")).exists(_.toLowerCase == "true")

  private[fetchers] lazy val sparkRestClient: SparkRestClient = new SparkRestClient(sparkConf)

  private[fetchers] lazy val sparkLogClient: SparkLogClient = {
    new SparkLogClient(hadoopConfiguration, sparkConf, eventLogUri)
  }

  override def fetchData(analyticJob: AnalyticJob): SparkApplicationData = {
    doFetchData(analyticJob) match {
      case Success(data) => data
      case Failure(e) => throw e
    }
  }

  private def doFetchData(analyticJob: AnalyticJob): Try[SparkApplicationData] = {
    val appId = analyticJob.getAppId
    logger.info(s"Fetching data for ${appId}")
    Try {
      Await.result(doFetchSparkApplicationData(analyticJob), DEFAULT_TIMEOUT)
    }.transform(
      data => {
        logger.info(s"Succeeded fetching data for ${appId}")
        Success(data)
      },
      e => {
        logger.error(s"Failed fetching data for ${appId}", e)
        Failure(e)
      }
    )
  }

  private def doFetchSparkApplicationData(analyticJob: AnalyticJob): Future[SparkApplicationData] = {
    if (shouldProcessLogsLocally) {
      async {
        sparkRestClient.fetchEventLogAndParse(analyticJob.getAppId)
      }
    } else {
      doFetchDataUsingRestAndLogClients(analyticJob)
    }
  }

  private def doFetchDataUsingRestAndLogClients(analyticJob: AnalyticJob): Future[SparkApplicationData] = async {
    val appId = analyticJob.getAppId
    val restDerivedData = await(sparkRestClient.fetchData(appId, eventLogSource == EventLogSource.Rest))

    val logDerivedData = eventLogSource match {
      case EventLogSource.None => None
      case EventLogSource.Rest => restDerivedData.logDerivedData
      case EventLogSource.WebHdfs =>
        val lastAttemptId = restDerivedData.applicationInfo.attempts.maxBy { _.startTime }.attemptId
        Some(await(sparkLogClient.fetchData(appId, lastAttemptId)))
    }

    SparkApplicationData(appId, restDerivedData, logDerivedData)
  }

}

object SparkFetcher {

  sealed trait EventLogSource

  object EventLogSource {
    /** Fetch event logs through REST API. */
    case object Rest extends EventLogSource
    /** Fetch event logs through WebHDFS. */
    case object WebHdfs extends EventLogSource
    /** Event logs are not available. */
    case object None extends EventLogSource
  }

  val SPARK_EVENT_LOG_ENABLED_KEY = "spark.eventLog.enabled"
  val DEFAULT_TIMEOUT = Duration(60, SECONDS)
  val LOG_LOCATION_URI_XML_FIELD = "event_log_location_uri"
}


text:
class Shape {
    public:
        using REAL = mtao::geometry::mesh::triangle::REAL;
        using Mesh = mtao::geometry::mesh::triangle::Mesh;
        virtual Mesh boundary_geometry() = 0;

        void set_vert_indices(const std::map<int,int>& map);
        virtual int get_vert_index(int i) const;
        void set_edge_indices(const std::map<int,int>& map);
        virtual int get_edge_index(int i) const;
        void apply_edge_markers(mtao::VectorX<int>& V) const;
        void apply_vert_markers(mtao::VectorX<int>& V) const;
        virtual ~Shape();
    private:
        std::map<int,int> vert_marker_map;
        std::map<int,int> edge_marker_map;
};

class Transform: public Shape {

    public:
        Transform(const std::shared_ptr<Shape>& s);
        int get_vert_index(int i) const override;
        int get_edge_index(int i) const override;

    protected:
        std::shared_ptr<Shape> shape = nullptr;
};

class Translate: public Transform {
    public:
        Translate(const std::shared_ptr<Shape>& s, REAL tx, REAL ty);
        Mesh boundary_geometry() override;
    private:
        mtao::Vector<REAL,2> t;
};
class Scale: public Transform {
    public:
        Scale(const std::shared_ptr<Shape>& sh, REAL sx, REAL sy);
        Scale(const std::shared_ptr<Shape>& sh, REAL s);
        Mesh boundary_geometry() override;
    private:
        mtao::Vector<REAL,2> s;
};

class Square: public Shape {
    public:
        Mesh boundary_geometry() override;

        //vert marker: interior: 0, boundary: 1
        //edge indices: interior: 0, left: 1, bottom: 2, right: 3, top: 4
        Square(REAL r, int nx=2, int ny=2);
        Square() = default;
        Square(const Square&) = default;
        Square(Square&&) = default;
        Square& operator=(const Square&) = default;
        Square& operator=(Square&&) = default;
    private:
        REAL radius = 1;
        int nx=2, ny=2;
};

class Sphere: public Shape {
        //vert marker: interior: 0, boundary: 1
        //edge marker: interior: 0, boundary: 1
    public:
        Mesh boundary_geometry() override;
        Sphere() = default;
        Sphere(REAL r, int vertcount = 10);
        Sphere(const Sphere&) = default;
        Sphere(Sphere&&) = default;
        Sphere& operator=(const Sphere&) = default;
        Sphere& operator=(Sphere&&) = default;
    private:
        REAL radius = 1;
        int vertcount = 10;
};


text:
{% extends "admin/base.html" %}
{% import "macros/form.html" as form %}

{% block primary_content_inner %}

新增使用者

  {% set data = c.data %}
  <form class="form-horizontal" action="" method="post">
    {{ form.errors(c.error_summary) }}
    {{ form.input("name", id="field-username", label=_("Username"), placeholder="username", value=data.name, error=c.errors.name, classes=["control-medium"]) }}
    {{ form.input("fullname", id="field-fullname", label=_("Full Name"), placeholder="Joe Bloggs", value=data.fullname, error=c.errors.fullname, classes=["control-medium"]) }}
    {{ form.input("email", id="field-email", label=_("Email"), type="email", placeholder="joe@example.com", value=data.email, error=c.errors.email, classes=["control-medium"]) }}
    {{ form.input("password1", id="field-password", label=_("Password"), type="password", placeholder="••••••••", value=data.password1, error=c.errors.password1, classes=["control-medium"]) }}
    {{ form.input("password2", id="field-confirm-password", label=_("Confirm"), type="password", placeholder="••••••••", value=data.password2, error=c.errors.password1, classes=["control-medium"]) }}

    {% if g.recaptcha_publickey %}
      {% snippet "user/snippets/recaptcha.html", public_key=g.recaptcha_publickey %}
    {% endif %}

      <button class="btn btn-primary" type="submit" name="save">{{ _("Create Account") }}</button>

  </form>

{% endblock %}

{% block secondary_content %}

      {{ _('What are sysadmins?') }}

      {% set docs_url = "http://docs.ckan.org/en/{0}/paster.html#sysadmin-give-sysadmin-rights".format(g.ckan_doc_version) %}
      {% trans %}

A sysadmin is someone that has full control over a CKAN instance.
          You can only add CKAN sysadmins via the sysadmin paster
          command.

      {% endtrans %}

{{ _('Read the documentation') }}

{% endblock %}


text:
from activations import *
from data_sources import *
from poolings import *
from evaluators import *
from layers import *
from networks import *
from optimizers import *
from attrs import *


text:
class AddSubscriptionIdToLineItem < ActiveRecord::Migration
  def change
    add_column :spree_line_items, :subscription_id, :integer

    # allow for fast lookups of a subscription's items
    add_index :spree_line_items, :subscription_id
  end
end


text:
INCLUDE(SimFind)

SIM_FIND(Spacenav
  RELEASELIBNAMES spnav
  DEBUGLIBNAMES spnav
  INCLUDEFILE spnav.h
  INCLUDE_DIR_SUFFIXES include
  LIB_DIR_SUFFIXES lib
  NO_PKGCONFIG)

IF(Spacenav_FOUND)
  ADD_DEFINITIONS(-DHAVE_SPACENAV_LIB)
ENDIF(Spacenav_FOUND)


text:
<?php

namespace Communicator;

/**
 * A message that can be sent over a transport.
 */
final class Message
{
    /**
     * @var string
     */
    private $channel;

    /**
     * @var array
     */
    private $params;

    /**
     * @var array
     */
    private $options;

    /**
     * Initializes a new instance of this class.
     *
     * @param string $channel The name of the channel to broadcast the message to.
     * @param array $params The parameters that belong to the message.
     * @param array $options Options that can be passed along to the transport.
     */
    public function __construct(string $channel, array $params, array $options)
    {
        $this->channel = $channel;
        $this->params = $params;
        $this->options = $options;

        if (!array_key_exists('locale', $this->options)) {
            $this->options['locale'] = class_exists('Locale') ? \Locale::getDefault() : 'en-US';
        }
    }

    /**
     * Gets the value of field "channel".
     *
     * @return string
     */
    public function getChannel(): string
    {
        return $this->channel;
    }

    /**
     * Gets the value of field "params".
     *
     * @return array
     */
    public function getParams(): array
    {
        return $this->params;
    }

    /**
     * Gets the parameter with the given name.
     *
     * @param string $name
     * @param mixed $default
     * @return mixed
     */
    public function getParam(string $name, $default = null)
    {
        if (array_key_exists($name, $this->params)) {
            return $this->params[$name];
        }

        return $default;
    }

    /**
     * Gets the value of field "options".
     *
     * @return array
     */
    public function getOptions(): array
    {
        return $this->options;
    }

    /**
     * Gets the option with the given name.
     *
     * @param string $name
     * @param mixed $default
     * @return mixed
     */
    public function getOption(string $name, $default = null)
    {
        if (array_key_exists($name, $this->options)) {
            return $this->options[$name];
        }

        return $default;
    }
}


text:
cd "$( dirname "${BASH_SOURCE[0]}" )"
cp slua.c luasocket-mini/* luajit-2.1.0-beta3/src/

echo "Building Slua-Linux-32...."
cd luajit-2.1.0-beta3
make clean
make CC="gcc -m32" BUILDMODE=dynamic
cp src/libluajit.so ../../Assets/Plugins/x86/slua.so

echo "Building SLua-Linux-64....."
make clean
make CC="gcc" BUILDMODE=dynamic
cp src/libluajit.so ../../Assets/Plugins/x64/slua.so
echo "Build Slua Linux success!"


text:
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from './reducers';
import thunk from 'redux-thunk';
import parse from 'xml-parser';
import { fetchArticles } from './actions/articles';

const users = {};
const local = window.localStorage._infoAgg ?
  JSON.parse(window.localStorage._infoAgg) : {};

if (local.users) {
  Object.keys(local.users).forEach(u => {
    users[u] = local.users[u].pass;
  });
}

const INITIAL_STATE = {
  sourceFilters: {
    US_NEWS: true,
    WORLD_NEWS: false,
    SPORTS: false,
    TECH: false,
  },
  users: users,
};

window.articles = {};

const store = createStore(
  reducer,
  INITIAL_STATE,
  compose(
    applyMiddleware(thunk),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  )
)

store.dispatch(fetchArticles('US_NEWS'));

export default store;


text:
<?php

include APPLICATION_PATH . 'config.php';
include 'Functions.php';
include 'Router.php';
include 'Application.php';
include 'Ajax.php';

$router = new Router();
$application = new Application();

if( isset( $_GET['lang'] ) )
{
    setcookie('lang', $_GET['lang'], time() + (3600 * 24 * 30), '/');
}

if( $router->fragment(0) === 'ajax' )
{
    $ajax = new Ajax();

    $action = $router->fragment(1);

    if( $action != false && method_exists( $ajax, $action ) ) echo json_encode( $ajax->{$action}() );
    else json_encode(array('status' => 'error'));
}
elseif( $router->fragment(0) === 'channel' )
{
	$cache_expire = 60*60*24*365;
	header("Pragma: public");
	header("Cache-Control: maxage=".$cache_expire);
	header('Expires: '.gmdate('D, d M Y H:i:s', time()+$cache_expire).' GMT');
	echo '<script src="//connect.facebook.net/en_US/all.js"></script>';
}
else
{
	include APPLICATION_PATH . 'templates/layout/template.php';
}


text:
from __future__ import unicode_literals, print_function

import operator

import numpy as np
import pandas as pd

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import LabelBinarizer
from sklearn.preprocessing import MultiLabelBinarizer

def _vectorize(vectorizer, series):
    vectorizer.fit(series)

    # Vectorize the input
    vector = vectorizer.transform(series)

    try:
        vector = vector.todense()
        vector = list(np.squeeze(vector))
        vector = list(map(lambda x: np.array(x)[0], vector))
    except AttributeError:
        pass

    # Get vocabulary, ordered by id
    if hasattr(vectorizer, 'vocabulary_'):
        vocabulary = sorted(vectorizer.vocabulary_.items(), key=operator.itemgetter(1))
        vocabulary = [word[0] for word in vocabulary]
    elif hasattr(vectorizer, 'classes_'):
        vocabulary = vectorizer.classes_
    else:
        raise ValueError("Wrong type of vectorizer given! Excepting one with attribute 'vocabulary_' or 'classes_'")

    # Encapsulate new columns inside a meta column, and put each word to its own column
    new_columns = pd.DataFrame(vector)
    new_columns.columns = pd.Series(vocabulary)

    return new_columns

def vectorize_text(series, min_df=1, max_df=1.0, binary=False):
    """
    Vectorize a text column.

    Tokenization of the input and vectorization is done
    through a CountVectorizer.

    :param series: series to vectorize
    :param min_df: float in range [0.0, 1.0] or int, default=1
    :param max_df: float in range [0.0, 1.0] or int, default=1.0
    :param binary: If True, all non zero counts are set to 1, else to count.

    :return: vectorized series as a dataframe, vectorizer
    """
    vectorizer = CountVectorizer(min_df=min_df, max_df=max_df, binary=binary)
    dataframe = _vectorize(vectorizer, series)

    return dataframe, vectorizer

def vectorize_mono_label(series):
    """
    Vectorize a mono-label column.

    :param series: series to vectorize
    :return: vectorized series as a dataframe, vectorizer
    """
    vectorizer = LabelBinarizer()
    dataframe = _vectorize(vectorizer, series)

    return dataframe, vectorizer

def vectorize_multi_label(series):
    """
    Vectorize a multi-label column.

    :param series: series to vectorize
    :return: vectorized series as a dataframe, vectorizer
    """
    vectorizer = MultiLabelBinarizer()
    dataframe = _vectorize(vectorizer, series)

    return dataframe, vectorizer


text:
java ShapesProgram

pause


text:
This folder contains configuration files for Office365 installation. The configurations will install Office365, Visio 2019 and Project 2019 and automatically activate them.

To use these configurations, you will have to download the Office365 setup executable from the Microsoft Partnerzone and run it with the command:

    setup.exe /configure PATH_TO_CONFIGURATION_FILE

Before running them, remember to replace the INSERT_KEY_HERE string with actual valid activation code or to remove the AUTOACTIVATE property along with the PIDKEY attributes on the products to use manual activation instead.


text:
using Implem.Pleasanter.Interfaces;
using Implem.Pleasanter.Libraries.Requests;
using Implem.Pleasanter.Libraries.Responses;
using Implem.Pleasanter.Libraries.Settings;
using Implem.Pleasanter.Libraries.Utilities;
using Implem.Pleasanter.Libraries.Views;
using Implem.Pleasanter.Models;
using System.Collections.Generic;
using System.Data;
namespace Implem.Pleasanter.Libraries.DataTypes
{
    public class Title : IConvertable
    {
        public long Id;
        public string Value = string.Empty;
        public string DisplayValue;
        public List<string> PartCollection;

        public Title()
        {
        }

        public Title(DataRow dataRow, string name)
        {
            Id = dataRow.Long(name);
            Value = dataRow.String("Title");
        }

        public Title(long id, string value)
        {
            Id = id;
            Value = value;
        }

        public Title(string value)
        {
            Value = value;
        }

        public string ToControl(Column column)
        {
            return Value;
        }

        public string ToResponse()
        {
            return Value;
        }

        public override string ToString()
        {
            return Value;
        }

        public virtual HtmlBuilder Td(HtmlBuilder hb, Column column)
        {
            return hb.Td(action: () => hb
                .Div(css: "grid-title-body", action: () => hb
                    .P(action: () => TdTitle(hb, column))));
        }

        protected void TdTitle(HtmlBuilder hb, Column column)
        {
            switch (Url.RouteData("action").ToLower())
            {
                case "gethistories":
                    hb.Text(text: DisplayValue);
                    break;
                default:
                    hb.A(
                        href: Navigations.ItemEdit(Id),
                        text: DisplayValue);
                    break;
            }
        }

        public virtual string ToExport(Column column)
        {
            return Value;
        }
    }

    public class TitleBody : Title, IConvertable
    {
        public string Body = string.Empty;

        public TitleBody()
        {
        }

        public TitleBody(long id, string title, string displayValue, string body)
        {
            Id = id;
            Value = title;
            DisplayValue = displayValue;
            Body = body;
        }

        public override string ToString()
        {
            return Value + "\r\n" + Body;
        }

        public override HtmlBuilder Td(HtmlBuilder hb, Column column)
        {
            return hb.Td(action: () => hb
                .Div(css: "grid-title-body", action: () => hb
                    .P(action: () => TdTitle(hb, column))
                    .P(css: "body markup", action: () => hb
                         .Text(text: Body))));
        }

        public override string ToExport(Column column)
        {
            return ToString();
        }
    }

    public static class TitleUtility
    {
        public static string DisplayValue(SiteSettings siteSettings, DataRow dataRow)
        {
            switch (siteSettings.ReferenceType)
            {
                case "Issues": return IssuesUtility.TitleDisplayValue(siteSettings, dataRow);
                case "Results": return ResultsUtility.TitleDisplayValue(siteSettings, dataRow);
                case "Wikis": return WikisUtility.TitleDisplayValue(siteSettings, dataRow);
                default: return string.Empty;
            }
        }
    }
}


text:
<!doctype html>

		<title>Zabuun - Learn Arabic for English Speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

						Modern Standard Arabic (MSA) | Egyptian Colloquial Arabic (ECA) | Both

Sports

I Love Baseball

  A: Baseball is fun.
 B: I like to hit the ball.
 A: I like to run around the bases.
 B: I like to slide into the bases.
 A: Yeah. It's a lot of fun to slide

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
package com.quickblox.sample.chat.java.fcm;

import android.util.Log;

import com.google.firebase.messaging.RemoteMessage;
import com.quickblox.messages.services.fcm.QBFcmPushListenerService;
import com.quickblox.sample.chat.java.App;
import com.quickblox.sample.chat.java.R;
import com.quickblox.sample.chat.java.ui.activity.SplashActivity;
import com.quickblox.sample.chat.java.utils.ActivityLifecycle;
import com.quickblox.sample.chat.java.utils.NotificationUtils;

import java.util.Map;

public class PushListenerService extends QBFcmPushListenerService {
    private static final String TAG = PushListenerService.class.getSimpleName();
    private static final int NOTIFICATION_ID = 1;

    protected void showNotification(String message) {
        NotificationUtils.showNotification(App.getInstance(), SplashActivity.class,
                App.getInstance().getString(R.string.notification_title), message,
                R.drawable.ic_logo_vector, NOTIFICATION_ID);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }

    @Override
    protected void sendPushMessage(Map data, String from, String message) {
        super.sendPushMessage(data, from, message);
        Log.v(TAG, "From: " + from);
        Log.v(TAG, "Message: " + message);
        if (ActivityLifecycle.getInstance().isBackground()) {
            showNotification(message);
        }
    }
}


text:
<refentry xmlns="http://docbook.org/ns/docbook"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:xi="http://www.w3.org/2001/XInclude"
          xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          version="5.0" xml:id="toc.html">
<refmeta>
<refentrytitle>toc.html</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">filename</refmiscinfo>
</refmeta>
<refnamediv>
<refname>toc.html</refname>
<refpurpose>Name of ToC HTML file</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment xml:id="toc.html.frag">
<xsl:param name="toc.html" select="concat('toc', $html.ext)"/>
</src:fragment>
</refsynopsisdiv>

<refsection><info><title>Description</title></info>

<para>Sets the filename used for the table of contents page.</para>

</refsection>
</refentry>


text:
package com.incomb.server.content.loader;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.incomb.server.content.parsing.ContentParser;
import com.incomb.server.content.parsing.rss.RssContentParserFactory;
import com.incomb.server.content.parsing.rss.RssDocument;
import com.incomb.server.model.Content;
import com.incomb.server.model.ContentSource;
import com.incomb.server.model.FetchHistory;

public class RssContentReader implements IContentReader {

	/**
	 *
The {@link Logger} for this class.

	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(RssContentReader.class);

	/**
	 * {@link ContentSource} of the the content will be read.
	 */
	private final ContentSource contentSource;

	/**
	 * Creates a new {@link RssContentReader}.
	 * @param contentSource of the the content will be read.
	 */
	public RssContentReader(final ContentSource contentSource) {
		this.contentSource = contentSource;
	}

	/**
	 * Reads, parses and returns the content form the content-source if it has changed since the given Date.
	 * @return read content.
	 */
	@Override
	public Content[] read(final FetchHistory lastFetch) {
		RssDocument doc = null;

		final Date lastFetchDate = lastFetch == null ? null : lastFetch.getFetchTime();

		try {
			LOGGER.debug("Reading rss feed from '{}' of content source '{}'.", contentSource.getUrl(), contentSource.getId());

			final RssContentParserFactory factory = RssContentParserFactory.getInstance();

			final URLConnection con = new URL(contentSource.getUrl()).openConnection();
			con.setConnectTimeout(2000);
			con.setReadTimeout(30000);

			final ContentParser<RssDocument> parser = factory.get(contentSource, con.getInputStream());

			if (parser.parse()) {
				doc = parser.getParsedObject();

				if(lastFetch != null && doc != null && !doc.hasChangedSince(lastFetchDate)) {
					LOGGER.debug("RSS content of content source {} hasn't changed since {}.",
							contentSource.getId(), lastFetch.getFetchTime());

					return new Content[0];
				}
			}

		} catch (final IOException e) {
			LOGGER.warn("Cannot connect to: {}", contentSource.getUrl(), e);
		}
		return doc != null ? doc.getContent(lastFetchDate) : new Content[0];
	}

}


text:
#region Using Directives
using System;
using System.ComponentModel;
using System.Collections;
using System.Xml.Serialization;
using System.Data;
using System.ServiceModel;

using Nettiers.AdventureWorks.Entities;
using Nettiers.AdventureWorks.Entities.Validation;

using Nettiers.AdventureWorks.Data;
using Microsoft.Practices.EnterpriseLibrary.Logging;

#endregion

namespace Nettiers.AdventureWorks.Contracts.Services
{
	/// <summary>
	/// An interface type implementation of the 'StoreContact' table.
	/// </summary>
	/// <remarks>
	/// All custom implementations should be done here.
	/// </remarks>
	[ServiceContract]
	public partial interface IStoreContactService : Nettiers.AdventureWorks.Contracts.Services.IStoreContactServiceBase
	{

	}//End Class

} // end namespace


text:
package org.apache.cassandra.dht;

import java.util.Collections;
import java.util.List;

import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.Pair;

/**
 * AbstractBounds containing both its endpoints: [left, right].  Used by "classic" by-key range scans.
 */
public class Bounds<T extends RingPosition> extends AbstractBounds<T>
{
    public Bounds(T left, T right)
    {
        this(left, right, StorageService.getPartitioner());
    }

    Bounds(T left, T right, IPartitioner partitioner)
    {
        super(left, right, partitioner);
        // unlike a Range, a Bounds may not wrap
        assert left.compareTo(right) <= 0 || right.isMinimum(partitioner) : "[" + left + "," + right + "]";
    }

    public boolean contains(T position)
    {
        // Range.contains doesnt work correctly if left == right (unless both
        // are minimum) because for Range that means a wrapping range that select
        // the whole ring. So we must explicitely handle this case
        return left.equals(position) || ((right.isMinimum(partitioner) || !left.equals(right)) && Range.contains(left, right, position));
    }

    public Pair<AbstractBounds<T>, AbstractBounds<T>> split(T position)
    {
        assert contains(position);
        // Check if the split would have no effect on the range
        if (position.equals(right))
            return null;

        AbstractBounds<T> lb = new Bounds<T>(left, position, partitioner);
        AbstractBounds<T> rb = new Range<T>(position, right, partitioner);
        return Pair.create(lb, rb);
    }

    public boolean intersects(Bounds<T> that)
    {
        // We either contains one of the that bounds, or we are fully contained into that.
        return contains(that.left) || contains(that.right) || that.contains(left);
    }

    public List<? extends AbstractBounds<T>> unwrap()
    {
        // Bounds objects never wrap
        return Collections.<AbstractBounds<T>>singletonList(this);
    }

    @Override
    public boolean equals(Object o)
    {
        if (!(o instanceof Bounds))
            return false;
        Bounds<T> rhs = (Bounds<T>)o;
        return left.equals(rhs.left) && right.equals(rhs.right);
    }

    @Override
    public String toString()
    {
        return "[" + left + "," + right + "]";
    }

    /**
     * Compute a bounds of keys corresponding to a given bounds of token.
     */
    public static Bounds<RowPosition> makeRowBounds(Token left, Token right, IPartitioner partitioner)
    {
        return new Bounds<RowPosition>(left.minKeyBound(partitioner), right.maxKeyBound(partitioner), partitioner);
    }

    public AbstractBounds<RowPosition> toRowBounds()
    {
        return (left instanceof Token) ? makeRowBounds((Token)left, (Token)right, partitioner) : (Bounds<RowPosition>)this;
    }

    public AbstractBounds<Token> toTokenBounds()
    {
        return (left instanceof RowPosition) ? new Bounds<Token>(((RowPosition)left).getToken(), ((RowPosition)right).getToken(), partitioner) : (Bounds<Token>)this;
    }
}


text:
namespace Google.Cloud.Dialogflow.V2.Snippets
{
    // [START dialogflow_v2_generated_EntityTypes_BatchUpdateEntityTypes_sync]
    using Google.Cloud.Dialogflow.V2;
    using Google.LongRunning;
    using Google.Protobuf.WellKnownTypes;

    public sealed partial class GeneratedEntityTypesClientSnippets
    {
        /// <summary>Snippet for BatchUpdateEntityTypes</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void BatchUpdateEntityTypesRequestObject()
        {
            // Create client
            EntityTypesClient entityTypesClient = EntityTypesClient.Create();
            // Initialize request argument(s)
            BatchUpdateEntityTypesRequest request = new BatchUpdateEntityTypesRequest
            {
                ParentAsAgentName = AgentName.FromProject("[PROJECT]"),
                EntityTypeBatchUri = "",
                LanguageCode = "",
                UpdateMask = new FieldMask(),
            };
            // Make the request
            Operation<BatchUpdateEntityTypesResponse, Struct> response = entityTypesClient.BatchUpdateEntityTypes(request);

            // Poll until the returned long-running operation is complete
            Operation<BatchUpdateEntityTypesResponse, Struct> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            BatchUpdateEntityTypesResponse result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<BatchUpdateEntityTypesResponse, Struct> retrievedResponse = entityTypesClient.PollOnceBatchUpdateEntityTypes(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                BatchUpdateEntityTypesResponse retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END dialogflow_v2_generated_EntityTypes_BatchUpdateEntityTypes_sync]
}


text:
<?php

defined('KAZINDUZI_PATH') or exit('No direct script access allowed');

// Send Powered By Header.
header("X-Powered-By: Kazinduzi framework ver." . Kazinduzi::VERSION . ' (' . Kazinduzi::CODENAME . ')', false);
// Init the Application
Kazinduzi::init();


text:
package org.todss.algorithm.model;

import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;

/**
 * A class representing serving as result of a demarcation process.
 * @author Displee
 */
public class DemarcateResult {

	/**
	 * The path.
	 */
	private final org.todss.algorithm.path.Path path;

	/**
	 * If we have to add the current intake inside the algorithm main loop.
	 */
	private final boolean addCurrent;

	/**
	 * A map containing new intakes with their indices.
	 */
	private final Map<Integer, Intake> map;

	/**
	 * Create a new {@code DemarcateResult} {@code Object}.
	 * @param path The path.
	 * @param addCurrent If we have to add the current intake.
	 * @param map The map with our new intakes.
	 */
	public DemarcateResult(org.todss.algorithm.path.Path path, boolean addCurrent, Map<Integer, Intake> map) {
		this.path = path;
		this.addCurrent = addCurrent;
		this.map = map;
	}

	/**
	 * Check if any intake is planned between the travel departure and arrival.
	 * @param travel The travel.
	 * @return If a intake is planned between the travel.
	 */
	public boolean betweenTravel(Travel travel) {
		for(Map.Entry<Integer, Intake> entry : map.entrySet()) {
			final ZonedDateTime date = entry.getValue().getDate();
			if (date.isAfter(travel.getDeparture()) && date.isBefore(travel.getArrival())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Get the first intake.
	 * @return The first intake.
	 */
	public Intake getFirst() {
		return map.entrySet().iterator().next().getValue();
	}

	/**
	 * Get the last intake.
	 * @return The last intake.
	 */
	public Intake getLast() {
		Intake[] array = map.values().toArray(new Intake[0]);
		return array[array.length - 1];
	}

	/**
	 * Populate the {@code list} with our new intakes.
	 * @param list The list to populate.
	 */
	public void populate(List<Intake> list) {
		for(Map.Entry<Integer, Intake> entry : map.entrySet()) {
			list.set(entry.getKey(), entry.getValue());
		}
	}

	/**
	 * Check if this result is a valid result.
	 * @return If it has no invalid intakes.
	 */
	public boolean isValid() {
		return getInvalidIntakes() == 0;
	}

	/**
	 * Get the amount of invalid intakes.
	 * @return The amount of invalid intakes.
	 */
	public int getInvalidIntakes() {
		int count = 0;
		for(Map.Entry<Integer, Intake> entry : map.entrySet()) {
			final ZonedDateTime date = entry.getValue().getDate();
			if (date.getHour() > 22 || date.getHour() < 8) {
				count++;
			}
		}
		return count;
	}

	/**
	 * Compares the amount of invalid intakes with another {@code other}.
	 * @param hour The hour of a default intake moment.
	 * @param other The other intake to compare with.
	 * @return Returns true if the {@code other} intake contains less invalid intakes or contains less invalid hours.
	 */
	public boolean compareInvalidIntakes(int hour, DemarcateResult other) {
		final int currentInvalid = getInvalidIntakes();
		final int otherInvalid = other.getInvalidIntakes();
		if (otherInvalid < currentInvalid) {
			return true;
		} else if (otherInvalid > currentInvalid) {
			return false;
		}
		for(int key : map.keySet()) {
			final Intake intake = map.get(key);
			final Intake otherIntake = other.map.get(key);
			//System.out.println(intake + " - " + otherIntake);
			if (otherIntake == null) {
				return false;
			}
			if (hour - intake.getDate().getHour() < hour - otherIntake.getDate().getHour()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Get the path.
	 * @return {@code path}
	 */
	public org.todss.algorithm.path.Path getPath() {
		return path;
	}

	/**
	 * If we have to add the current date inside the algorithm loop.
	 * @return {@code addCurrent}
	 */
	public boolean addCurrent() {
		return addCurrent;
	}

}


text:
package unitTest;

import static org.junit.Assert.*;

import model.Expression;
import model.Pi;
import org.junit.Before;
import org.junit.Test;

public class PiTest {
	Expression pi;

	@Before
	public void setUp() throws Exception {
		pi = new Pi();
	}

	@Test
	public void testCalc() throws Exception {
		assertEquals(Math.PI, pi.calc(), 0.0000001);
	}

	@Test
	public void testderiv() throws Exception {
		assertEquals(0.0, pi.derivative(null).calc(), 0.0000001);
	}

}


text:
import axios from 'axios'
import lodash from 'lodash'
import log from 'middleware/logger'

import config from 'config'

function _buildUrl (endpoint, params) {
  let url = config.API_URL
  let finalParams = ''

  if (endpoint.charAt(0) !== '/') {
    url += '/'
  }

  if (params) {
    finalParams += '?'
    lodash.each(params, (p, k) => {
      finalParams = finalParams + '&' + k + '=' + p
    })
  }

  url += endpoint + finalParams
  return url
}

export const handleErrors = (response) => {
  if (response.status >= 200 && response.status <= 300) {
    return response
  } else if (response.status === 401 || response.status === 403) {
    throw response
  }
}

const Api = {
  get: function (route, params) {
    return new Promise(function (resolve, reject) {
      const url = _buildUrl(route, params)
      log.debug('Api::get::initial', url, params)
      return axios(url)
      .then(handleErrors)
      .then((response) => {
        const json = response.json()
        log.debug('Api::post::response', url)
        resolve(json)
      }).catch((err) => {
        return reject(err)
      })
    })
  },
  post: function (route, payload) {
    return new Promise(function (resolve, reject) {
      const url = _buildUrl(route)
      log.debug('Api::post::initial', url, payload)
      return axios({
        url,
        method: 'POST',
        data: payload
      })
      .then(handleErrors)
      .then((response) => {
        log.debug('Api::post::response', url, response)
        resolve(response)
      }).catch((err) => {
        return reject(err)
      })
    })
  }
}
export default Api


text: Slides for a talk about unrealized problems in C++.


text:
from re import search
import paho.mqtt.client as mqtt

control_action = "uisgroup/control_action"
plant_state = "uisgroup/plant_state"
pubQosLevel = 1
subQosLevel = 1
state = ""

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_log(mosq, obj, level, string):
    print(string)

def on_connect(mosq, obj, rc):
    print("Subscribing")
    mosq.subscribe(plant_state, subQosLevel)
    print("rc: " + str(rc))

def on_message(mosq, obj, msg):
    global state
    state = msg.payload
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

def on_publish(mosq, obj, mid):
    #print("mid: " + str(mid))
    pass

def on_disconnect(pahoClient, obj, rc):
    print "Disconnected"

try:
    controllerclient = mqtt.Client()
    # Assign event callbacks
    controllerclient.on_message = on_message
    controllerclient.on_connect = on_connect
    controllerclient.on_log = on_log
    controllerclient.on_publish = on_publish
    controllerclient.on_subscribe = on_subscribe
    controllerclient.on_disconnect = on_disconnect
except Exception, err:
    print("Device connection failed", "Error thrown: %s\n" % err)

def initialize_handshake(HOST, PORT):
    #connect to a [public] MQTT broker
    controllerclient.connect(HOST, PORT, 60);print "connected",HOST, PORT

def process(HOST, PORT, GET,client_socketport=None):
    global controllerclient
    try:
        controllerclient.loop();
        controllerclient.publish(control_action, GET, pubQosLevel);
        response = state
        m = search('\[(.+?)\]', response);
        if m:
            response = m.groups()[-1];
        data = response.split()
    except Exception, err:
        print("Error thrown: %s\n" % err)
        response = (GET.split("time=")[1]).split("&")[0]
    return response

if __name__ == '__main__':
	initialize_handshake(None, None)
	print process(None, None, "/init")


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("TfsCmdlets.Tests.Integration.PSDesktop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TfsCmdlets.Tests.Integration.PSDesktop")]
[assembly: AssemblyCopyright("Copyright ©  2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("0a52a2c0-75eb-438a-ba6f-8fc28faebfdf")]

// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
@interface MOBProjectionEPSG2251 : MOBProjection

@end


text:
Tests that editing sourcecode which is referred by multiple stylesheets (via sourceURL comment) updates all stylesheets.

Inspected node

#inspected {
    font-size: 100px;
}
/*# sourceURL=stylesheet.css */


text:
require 'openssl'
require 'digest/sha2'

module Hubtime
  class HubConfig
    def self.instance
      @config ||= HubConfig.new
    end

    def self.auth(user, password)
      store(user, password)
    end

    def self.store(user, password)
      instance.store(user, password)
    end

    def self.user
      instance.user
    end

    def self.password
      instance.password
    end

    def self.display_password
      '*' * (password || "").size
    end

    def self.ignore
      instance.ignore
    end

    def self.add_ignore(repo_name)
      instance.add_ignore(repo_name)
    end

    def self.threads
      8
    end

    attr_reader :user, :password, :ignore
    def initialize
      @file_name = "config"
      hash = read_file
      @user = hash["user"]
      @password = Stuff.decrypt(hash["password"])
      @ignore = hash["ignore"] || []
    end

    def read_file
      YAML.load_file(file)
    end

    def write_file!
      hash = {}
      ["user", "password", "ignore"].each do |key|
        hash[key] = instance_variable_get("@#{key}")
      end

      hash["password"] = Stuff.encrypt(hash["password"])

      File.open(file, 'w' ) do |out|
        YAML.dump(hash, out)
      end
    end

    def file
      file = File.join(File.expand_path("."), "hubtime_config.yml")

      unless File.exists?(file)
        File.open(file, 'w' ) do |out|
          YAML.dump({}, out )
        end
      end
      file
    end

    def add_ignore(repo_name)
      @ignore << repo_name
      @ignore.uniq!
      write_file!
    end

    def store(user, password)
      @user = user
      @password = password
      write_file!
    end

    class Stuff
      def self.key
        sha256 = Digest::SHA2.new(256)
        sha256.digest("better than plain text")
      end
      def self.iv
        "kjfdhkkkjkjhfdskljghfkdjhags"
      end
      def self.encrypt(payload)
        return nil if payload == nil
        aes = OpenSSL::Cipher.new("AES-256-CFB")
        aes.encrypt
        aes.key = key
        aes.iv = iv

        aes.update(payload) + aes.final
      end

      def self.decrypt(encrypted)
        return nil if encrypted == nil

        aes = OpenSSL::Cipher.new("AES-256-CFB")
        aes.decrypt
        aes.key = key
        aes.iv = iv
        aes.update(encrypted) + aes.final
      end
    end
  end
end


text:
<?xml version="1.0"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <artifactId>portletbridge</artifactId>
    <groupId>org.portletbridge</groupId>
    <version>1.3-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.portletbridge</groupId>
  <artifactId>portletbridge-portlet</artifactId>
  <packaging>war</packaging>
  <name>PortletBridge Generic Portlet</name>
  <version>1.3-SNAPSHOT</version>
  <properties>
    <!-- Change this for a new Pluto version -->
    <portlet-api.version>1.0</portlet-api.version>
    <servlet-api.version>2.4</servlet-api.version>
    <junit.version>3.8.1</junit.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.portletbridge</groupId>
      <artifactId>portletbridge-core</artifactId>
      <version>1.3-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>javax.portlet</groupId>
      <artifactId>portlet-api</artifactId>
      <version>${portlet-api.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet-api.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
static ItemCacheOptions item_cache_options;
static ItemCache *item_cache;
static int free_when_done;

static void setup(void) {
  item_cache_options.cache_update_wait_time = 1;
  setup_fixture_path();
  system("rm -Rf /tmp/valid-copy && cp -R fixtures/valid /tmp/valid-copy && chmod -R 755 /tmp/valid-copy");
  item_cache_create(&item_cache, "/tmp/valid-copy", &item_cache_options);
  item_cache_load(item_cache);
}

static void teardown(void) {
  teardown_fixture_path();
  free_item_cache(item_cache);
}

START_TEST (create_pool) {
  Pool *pool = new_pool();
  assert_not_null(pool);
  free_pool(pool);
} END_TEST

START_TEST (new_pool_is_empty) {
  Pool *pool = new_pool();
  assert_equal(0, pool_num_tokens(pool));
  assert_equal(0, pool_total_tokens(pool));
  free_pool(pool);
} END_TEST

START_TEST (add_1_item) {
  Pool *pool = new_pool();
  pool_add_item(pool, item_cache_fetch_item(item_cache, (unsigned char *) "urn:peerworks.org:entry#878944", &free_when_done));
  assert_equal(186, pool_num_tokens(pool));
  assert_equal(336, pool_total_tokens(pool));
  assert_equal(9, pool_token_frequency(pool, 7982));
  assert_equal(1, pool_token_frequency(pool, 7967));
  assert_equal(0, pool_token_frequency(pool, 10));
  free_pool(pool);
} END_TEST

START_TEST (add_2_items_with_same_tokens) {
  Pool *pool = new_pool();
  pool_add_item(pool, item_cache_fetch_item(item_cache, (unsigned char *) "urn:peerworks.org:entry#709254", &free_when_done));
  pool_add_item(pool, item_cache_fetch_item(item_cache, (unsigned char *) "urn:peerworks.org:entry#753459", &free_when_done));
  assert_equal(196, pool_num_tokens(pool));
  assert_equal(323, pool_total_tokens(pool));
  assert_equal(3, pool_token_frequency(pool, 665));
  assert_equal(3, pool_token_frequency(pool, 1179));
  assert_equal(1, pool_token_frequency(pool, 1222));
  assert_equal(0, pool_token_frequency(pool, 10));
  free_pool(pool);
} END_TEST

START_TEST (token_iteration) {
  int ret_val;
  Pool *pool = new_pool();
  pool_add_item(pool, item_cache_fetch_item(item_cache, (unsigned char *) "urn:peerworks.org:entry#709254", &free_when_done));
  pool_add_item(pool, item_cache_fetch_item(item_cache, (unsigned char *) "urn:peerworks.org:entry#753459", &free_when_done));

  Token token;
  token.id = 0;

  ret_val = pool_next_token(pool, &token);
  assert_true(ret_val);
  assert_equal(1, token.id);
  assert_equal(1, token.frequency);

  ret_val = pool_next_token(pool, &token);
  assert_true(ret_val);
  assert_equal(13, token.id);
  assert_equal(2, token.frequency);

  free_pool(pool);
} END_TEST

START_TEST (token_iteration_with_null_pool_doesnt_crash) {
  Token token;
  token.id = 0;
  int ret_val;

  ret_val = pool_next_token(NULL, &token);
  assert_false(ret_val);
} END_TEST

Suite *
pool_suite(void) {
  Suite *s = suite_create("Pool");

  TCase *tc_pool = tcase_create("Pool");
  tcase_add_checked_fixture (tc_pool, setup, teardown);
  tcase_add_test(tc_pool, create_pool);
  tcase_add_test(tc_pool, new_pool_is_empty);
  tcase_add_test(tc_pool, add_1_item);
  tcase_add_test(tc_pool, add_2_items_with_same_tokens);
  tcase_add_test(tc_pool, token_iteration);
  tcase_add_test(tc_pool, token_iteration_with_null_pool_doesnt_crash);
  suite_add_tcase(s, tc_pool);

  return s;
}

int main(void) {
  initialize_logging("test.log");
  int number_failed;

  SRunner *sr = srunner_create(pool_suite());
  srunner_run_all(sr, CK_NORMAL);
  number_failed = srunner_ntests_failed(sr);
  srunner_free(sr);
  close_log();
  return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}


text:
import React from 'react'
import ConnectionManager from './../services/ConnectionManager'
import { browserHistory } from 'react-router'

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.connectionManager = new ConnectionManager();

        this.login = this.login.bind(this);
    }

    async   isLoggedIn() {
        try {
            this.setState({ isLoggedIn: await this.connectionManager.isLoggedIn() });
            if (this.state.isLoggedIn)
                browserHistory.push('/')
        } catch (exception) {
            console.error(exception)
        } finally {
            this.setState({
                isLoading: false
            })
        }
    }

    componentWillMount() {
        this.isLoggedIn()
    }

    async  login() {
        try {
            await this.connectionManager.login('facebook')
            this.isLoggedIn()
        } catch (exception) {
            console.error(exception)
        }
    }

    render() {
        return (

Login

                <button className="" onClick={this.login} >  Login with Facebook </button>

        )
    }
}

export default Login;


text:
from unittest import TestCase
import subprocess, os, shutil, tempfile

# Load git-shadow as a module for functional unit tests. Le Hack. Sacrebleu!!1
import imp
git_shadow = imp.load_source("git_shadow", os.path.join(os.getcwd(), "git-shadow"))

def rm_r(path):
    if os.path.isdir(path):
        shutil.rmtree(path)
    elif os.path.exists(path):
        os.remove(path)

def num_commits(repo_dir):
    print "num_commits", subprocess.check_output(["git", "log"], cwd=repo_dir)
    out = subprocess.check_output(["git", "log", "--format=%H"], cwd=repo_dir)
    return len(out.strip().splitlines())

class UnitTests(TestCase):

    def setUp(self):
        # create dummy repo for testing
        self.repo_dir = os.path.realpath(tempfile.mkdtemp())
        subprocess.check_call(["git", "init", self.repo_dir])

        # add cwd to path to support execution of "git-shadow" in tests
        os.environ["PATH"] = ":".join(os.environ["PATH"].split(":") + [os.getcwd()])
        self.env = os.environ

    def tearDown(self):
        rm_r(self.repo_dir)

    def test_get_shadow_path(self):
        '''
        Verify the shadow repo path is constructed properly and that an
        Exception is raised if the func is called outside a git repo.
        '''
        p = git_shadow.get_shadow_path(self.repo_dir)
        self.assertEqual(p, os.path.join(self.repo_dir, ".shadow"))

        tdir = tempfile.mkdtemp()
        try:
            with self.assertRaises(subprocess.CalledProcessError):
                git_shadow.get_shadow_path(tdir)
        finally:
            rm_r(tdir)

    def test_get_current_path(self):
        '''
        Verify the urrent repo path is constructed properly and that an
        Exception is raised if the func is called outside a git repo.
        '''
        p = git_shadow.get_current_path(self.repo_dir)
        self.assertEqual(p, os.path.join(self.repo_dir, ".shadow", "current"))

        tdir = tempfile.mkdtemp()
        try:
            with self.assertRaises(subprocess.CalledProcessError):
                git_shadow.get_current_path(tdir)
        finally:
            rm_r(tdir)

    def test_create_current(self):
        '''
        Verify the function creates/overwrites repos properly
        '''
        git_shadow.create_current(cwd=self.repo_dir)
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir,
            ".shadow", "current", ".git")))
        with self.assertRaises(OSError):
            git_shadow.create_current(cwd=self.repo_dir)

    def test_create_current_shadow(self):
        '''
        Verify the function shadows controlled files
        '''
        fp_a = os.path.join(self.repo_dir, "a")
        open(fp_a, "wt").write("test_a")

        dir_b = os.path.join(self.repo_dir, "db")
        os.mkdir(dir_b)
        fp_b = os.path.join(dir_b, "b")
        open(fp_b, "wt").write("test_b")

        subprocess.call(["git", "add", fp_a, fp_b], cwd=self.repo_dir)
        subprocess.call(["git", "commit", "-m", "'message'"], cwd=self.repo_dir)

        git_shadow.create_current(cwd=self.repo_dir)
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir,
            ".shadow", "current", fp_a)))
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir,
            ".shadow", "current", fp_b)))

    def test_add_hooks(self):
        # verify hooks are installed in parent repository
        git_shadow.add_hooks(self.repo_dir)
        subprocess.call(["git", "shadow", "add-hooks", self.repo_dir], env=self.env)
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir, ".git", "hooks", "post-commit")))
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir, ".git", "hooks", "post-checkout")))

    def test_add_hooks_merge(self):
        hook_path = os.path.join(self.repo_dir, ".git", "hooks", "post-commit")
        open(hook_path, "wt").write("echo test")
        git_shadow.add_hooks(self.repo_dir)
        self.assertEqual(open(hook_path, "rt").read(),
            "echo test\ngit shadow post-commit\n")

    def test_remove_hooks(self):
        # verify hooks are removed from parent repository
        git_shadow.add_hooks(self.repo_dir)
        git_shadow.remove_hooks(self.repo_dir)
        self.assertFalse(os.path.exists(os.path.join(self.repo_dir, ".git", "hooks", "post-commit")))
        self.assertFalse(os.path.exists(os.path.join(self.repo_dir, ".git", "hooks", "post-checkout")))

    def test_remove_hooks_merge(self):
        # verify git-shadow hooks are removed without clobbering existing hook file
        filetext = "foobaz"
        filepath = os.path.join(self.repo_dir, ".git", "hooks", "post-commit")
        open(filepath, "wt").write(filetext)

        git_shadow.add_hooks(self.repo_dir)
        git_shadow.remove_hooks(self.repo_dir)

        self.assertTrue(os.path.exists(os.path.join(self.repo_dir, ".git", "hooks", "post-commit")))
        self.assertEqual(filetext, open(filepath, "rt").read())
        self.assertFalse(os.path.exists(os.path.join(self.repo_dir, ".git", "hooks", "post-checkout")))

    def test_activate(self):
        git_shadow.activate(self.repo_dir)
        path = os.path.join(self.repo_dir, ".shadow", "current")
        self.assertTrue(os.path.exists(path))
        self.assertTrue(git_shadow.is_active(self.repo_dir))

        git_shadow.deactivate(self.repo_dir)
        path = os.path.join(self.repo_dir, ".shadow", "current")
        self.assertFalse(os.path.exists(path))
        self.assertFalse(git_shadow.is_active(self.repo_dir))

    def test_shadow_controlled_files_moves(self):
        '''
        Verify the function shadows controlled files when git mv, rm are used
        '''
        '''
        TODO
        fp_a = os.path.join(self.repo_dir, "a")
        open(fp_a, "wt").write("test_a")

        dir_b = os.path.join(self.repo_dir, "db")
        os.mkdir(dir_b)
        fp_b = os.path.join(dir_b, "b")
        open(fp_b, "wt").write("test_b")

        subprocess.call(["git", "add", fp_a, fp_b], cwd=self.repo_dir)
        subprocess.call(["git", "commit", "-m", "'message'"], cwd=self.repo_dir)

        git_shadow.create_current(cwd=self.repo_dir)
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir,
            ".shadow", "current", fp_a)))
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir,
            ".shadow", "current", fp_b)))
        '''
        pass

    def test_shadow_file(self):
        # add some files to a test repo
        test_filepath = os.path.join(self.repo_dir, "foobar")
        open(test_filepath, "wt").write("some file contents")
        subprocess.check_call(["git", "add", test_filepath], cwd=self.repo_dir, env=self.env)

        os.mkdir(os.path.join(self.repo_dir, "foobaz"))
        test_filepath = os.path.join(self.repo_dir, "foobaz", "foomanchu")
        open(test_filepath, "wt").write("some other file contents")

        subprocess.check_call(["git", "add", test_filepath], cwd=self.repo_dir, env=self.env)
        subprocess.check_call(["git", "commit", "-m", "'message'"], cwd=self.repo_dir, env=self.env)

        git_shadow.activate(self.repo_dir)

        # verify adding an unchanged file results in creation of .shadow/current,
        # but doesn't make an additional commit
        shadow_repo_path = git_shadow.get_current_path(self.repo_dir)
        print "self.repo_dir", self.repo_dir
        git_shadow.shadow_file(test_filepath, test_filepath)
        self.assertEqual(1, num_commits(shadow_repo_path))

        # verify adding a changed file *does* result in a commit to the shadow repo
        with tempfile.NamedTemporaryFile() as tf:
            tf.write("new contents..\nare here!")
            tf.flush()
            git_shadow.shadow_file(test_filepath, tf.name)
            self.assertEqual(2, num_commits(shadow_repo_path))

"""

class IntegrationTests(TestCase):

    def setUp(self):
        # create dummy repo for testing
        self.repo_dir = os.path.realpath(tempfile.mkdtemp())
        subprocess.check_call(["git", "init", self.repo_dir])

        # add cwd to path to support execution of "git-shadow" in tests
        self.env = os.environ
        self.env["PATH"] = ":".join(self.env["PATH"].split(":") + [os.getcwd()])

    def tearDown(self):
        rm_r(self.repo_dir)

    def test_shadow_file(self):
        # add some files to a test repo
        test_filepath = os.path.join(self.repo_dir, "foobar")
        open(test_filepath, "wt").write("some file contents")
        subprocess.check_call(["git", "add", test_filepath], cwd=self.repo_dir, env=self.env)

        os.mkdir(os.path.join(self.repo_dir, "foobaz"))
        test_filepath = os.path.join(self.repo_dir, "foobaz", "foomanchu")
        open(test_filepath, "wt").write("some other file contents")

        subprocess.check_call(["git", "add", test_filepath], cwd=self.repo_dir, env=self.env)
        subprocess.check_call(["git", "commit", "-m", "'message'"], cwd=self.repo_dir, env=self.env)

        # create shadow repo
        git_shadow.create_shadow_repo(self.repo_dir)
        git_shadow.shadow_controlled_files(self.repo_dir)
        git_shadow.add_hooks(self.repo_dir)

        # simulate two modifications to a file
        with tempfile.NamedTemporaryFile() as tf:
            tf.write("new contents..\nare here!")
            tf.flush()
            git_shadow.shadow_file(test_filepath, tf.name)

            tf.write("new contents..\nare here now!")
            tf.flush()
            git_shadow.shadow_file(test_filepath, tf.name)

            # simulate a save
            shutil.copyfile(tf.name, test_filepath)

        # simulate an add/commit to the enclosing repo
        subprocess.check_call(["git", "add", test_filepath], cwd=self.repo_dir, env=self.env)
        subprocess.check_call(["git", "commit", "-m", "'message'"], cwd=self.repo_dir, env=self.env)

        # make sure: new shadow repo was initialized in HEAD, and it is empty:
        #  - only a single commit -- all tracked files being added
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir, ".shadow", ".git")))
        self.assertEqual(num_commits(os.path.join(self.repo_dir, ".shadow")), 1)

        # make sure: old shadow repo was committed with last commit
        subprocess.check_call(["git", "checkout", "HEAD^"], cwd=self.repo_dir, env=self.env)
        self.assertTrue(os.path.exists(os.path.join(self.repo_dir, ".shadow", "git")))
        self.assertEqual(num_commits(os.path.join(self.repo_dir, ".shadow")), 2)
"""


text:
package cosmos.sql.impl;

public class LogicVisitorTest {

}


text:
package org.zalando.nakadi.exceptions.runtime;

public class EventTypeUnavailableException extends NakadiBaseException {

    public EventTypeUnavailableException(final String message) {
        super(message);
    }

    public EventTypeUnavailableException(final String message, final Throwable cause) {
        super(message, cause);
    }
}


text:
#import "RFAPI.h"

@interface LocalPlaylist : NSObject {
    NSArray *contents;
}

+ (LocalPlaylist *)sharedPlaylist;

@property (nonatomic, readonly) NSUInteger count;

- (void)addToPlaylist:(Media *)media;
- (void)removeFromPlaylist:(Media *)media;
- (void)removeAtIndex:(NSUInteger)index;
- (Media *)mediaAtIndex:(NSUInteger)index;
- (BOOL)existsInPlaylist:(Media *)media;
- (void)clear;

@end


text:
<?php

// SionModel/View/Helper/Email.php

namespace SionModel\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\Validator\EmailAddress;
use Zend\Filter\StringTrim;

class Email extends AbstractHelper
{
    public function __invoke($email, $onlyGlyph = false)
    {
        $trimFilter = new StringTrim();
        $emailValidator = new EmailAddress();
        $email = $trimFilter->filter($email);
        if ($emailValidator->isValid($email)) {
            $return = 'getView()->escapeHtml($email) . '">';
            if ($onlyGlyph) {
                $return .= '';
            } else {
                $return .= $this->getView()->escapeHtml($email);
            }
            return $return . '';
        } else {
            return '';
        }
    }
}


text:
var http=require('http');
var fs=require('fs');
http.createServer(function(req,res){
  if(req.url=='/'){
     fs.createReadStream('./post.html').pipe(res);
  }else if(req.url=='/ajax'){
   res.end('ajax');
  }
}).listen(8010);


text:
    <form novalidate class="simple-form">

        <input type="search" ng-model="findLocation.search" class="form-control" ng-autocomplete details="findLocation.details" options="findLocation.options" placeholder="Find a location" ng-keyup="$event.keyCode == 13 ? recenterMap() : null"/>

          <button class="btn btn-primary" ng-click="recenterMap()" type="button"></button>

    </form>

        Draw a circle with a radius of:

          <input type="number" ng-model="radius" class="form-control" />

            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">{{unit}} </button>

{{u}}

          <button ng-click="addCircles()">Draw circle</button>
          <button ng-click="clearCircles()">Clear circles</button>

    Datasets{{ datasets.length }}

          <button id="refresh-but" class="btn btn-primary btn-sm" ng-click="refreshMap()"></button>
          <button id="stop-but" class="btn btn-primary btn-sm"type="button" ng-click="stopStart()"></button>

        <input type="checkbox" ng-model="dataset.active" ng-change="toggleActivatedDataset(getDataset($index))">{{ dataset.name }}{{ dataset.count }}</input>

    Filter

        <form novalidate class="simple-form form-inline">

            <tags-input ng-model="tags" placeholder="Filter by Tag" >
              <auto-complete source="getActiveTags()" min-length="1"></auto-complete>
            </tags-input>

              <button class="btn btn-primary" type="button" ng-click="runFilter();applyFilter()"></button>
              <button class="btn btn-primary" type="button" ng-click="clearTags();applyFilter()" ></button>

            <input type="radio" ng-model="matchAll" ng-value="false" checked>Match Any
            <input type="radio" ng-model="matchAll" ng-value="true" checked>Match All

        </form>


text:
from .client import ClientError
from .client import DryRun
from .client import MarathonClient
from .deployment import DeploymentFailed
from .deployment import DeploymentNotFound
from .deployment import MarathonDeployment

__all__ = [
    'ClientError',
    'DeploymentFailed',
    'DeploymentNotFound',
    'DryRun',
    'MarathonClient',
    'MarathonDeployment',
]


text:
""" Utilities to manipulate numpy arrays """

import sys
from distutils.version import LooseVersion

import numpy as np

from nibabel.volumeutils import endian_codes, native_code, swapped_code

NUMPY_LESS_1_8 = LooseVersion(np.version.short_version) < '1.8'

def as_native_array(arr):
    """ Return `arr` as native byteordered array

    If arr is already native byte ordered, return unchanged.  If it is opposite
    endian, then make a native byte ordered copy and return that

    Parameters
    ----------
    arr : ndarray

    Returns
    -------
    native_arr : ndarray
        If `arr` was native order, this is just `arr`. Otherwise it's a new
        array such that ``np.all(native_arr == arr)``, with native byte
        ordering.
    """
    if endian_codes[arr.dtype.byteorder] == native_code:
        return arr
    return arr.byteswap().newbyteorder()

def pinv(a, rcond=1e-15):
    """Vectorized version of `numpy.linalg.pinv`

    If numpy version is less than 1.8, it falls back to iterating over
    `np.linalg.pinv` since there isn't a vectorized version of `np.linalg.svd`
    available.

    Parameters
    ----------
    a : array_like (..., M, N)
        Matrix to be pseudo-inverted.
    rcond : float
        Cutoff for small singular values.

    Returns
    -------
    B : ndarray (..., N, M)
        The pseudo-inverse of `a`.

    Raises
    ------
    LinAlgError
        If the SVD computation does not converge.

    See Also
    --------
    np.linalg.pinv
    """
    a = np.asarray(a)
    if NUMPY_LESS_1_8:
        if a.ndim <= 2:
            # properly handle the case of a single 2D array
            return np.linalg.pinv(a, rcond)
        shape = a.shape[:-2]
        a = a.reshape(-1, a.shape[-2], a.shape[-1])
        result = np.empty((a.shape[0], a.shape[2], a.shape[1]))
        for i, item in enumerate(a):
            result[i] = np.linalg.pinv(item, rcond)
        return result.reshape(shape + (a.shape[2], a.shape[1]))
    else:
        swap = np.arange(a.ndim)
        swap[[-2, -1]] = swap[[-1, -2]]
        u, s, v = np.linalg.svd(a, full_matrices=False)
        cutoff = np.maximum.reduce(s, axis=-1, keepdims=True) * rcond
        mask = s > cutoff
        s[mask] = 1. / s[mask]
        s[~mask] = 0
        return np.einsum('...ij,...jk',
                         np.transpose(v, swap) * s[..., None, :],
                         np.transpose(u, swap))

def eigh(a, UPLO='L'):
    """Iterate over `np.linalg.eigh` if it doesn't support vectorized operation

    Parameters
    ----------
    a : array_like (..., M, M)
        Hermitian/Symmetric matrices whose eigenvalues and
        eigenvectors are to be computed.
    UPLO : {'L', 'U'}, optional
        Specifies whether the calculation is done with the lower triangular
        part of `a` ('L', default) or the upper triangular part ('U').

    Returns
    -------
    w : ndarray (..., M)
        The eigenvalues in ascending order, each repeated according to
        its multiplicity.
    v : ndarray (..., M, M)
        The column ``v[..., :, i]`` is the normalized eigenvector corresponding
        to the eigenvalue ``w[..., i]``.

    Raises
    ------
    LinAlgError
        If the eigenvalue computation does not converge.

    See Also
    --------
    np.linalg.eigh
    """
    a = np.asarray(a)
    if a.ndim > 2 and NUMPY_LESS_1_8:
        shape = a.shape[:-2]
        a = a.reshape(-1, a.shape[-2], a.shape[-1])
        evals = np.empty((a.shape[0], a.shape[1]))
        evecs = np.empty((a.shape[0], a.shape[1], a.shape[1]))
        for i, item in enumerate(a):
            evals[i], evecs[i] = np.linalg.eigh(item, UPLO)
        return (evals.reshape(shape + (a.shape[1], )),
                evecs.reshape(shape + (a.shape[1], a.shape[1])))
    return np.linalg.eigh(a, UPLO)


text:
/***************************************************************************
 * INCLUDES
 ***************************************************************************/

#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>
#include <errno.h>
#include <math.h>
#include <string.h>

#include <iostream>

#include "zmdpCommonDefs.h"
#include "LifeSurvey.h"

using namespace std;
using namespace zmdp;

bool verboseG = false;

struct TraceEntry {
  int a;
  int o;
};

void readTrace(std::vector<TraceEntry>& result,
	       const char* fname)
{
  FILE* f = fopen(fname, "r");
  if (NULL == f) {
    fprintf(stderr, "ERROR: couldn't open %s for reading: %s\n",
	    fname, strerror(errno));
    exit(EXIT_FAILURE);
  }

  char buf[256];
  TraceEntry e;
  int lnum = 0;
  result.clear();
  while (fgets(buf,sizeof(buf),f)) {
    lnum++;
    if (0 == strlen(buf) || '#' == buf[0]) continue;
    if (2 != sscanf(buf, "%d %d", &e.a, &e.o)) {
      fprintf(stderr, "%s:%d: syntax error, expected integers '<a> <o>' on each line\n",
	      fname, lnum);
      exit(EXIT_FAILURE);
    }
    result.push_back(e);
  }
  fclose(f);
}

void doit(const char* lifeSurveyFileName,
	  const char* targetListFileName,
	  const char* traceFileName)
{
  const double lookaheadCost = 5.0;
  printf("LOOKAHEAD COST=%lf\n", lookaheadCost);

  LSModel m;
  m.init(lifeSurveyFileName);
  const LSModelFile& f = m.mfile;

  std::vector<LSPos> targetList;
  LSModel::readTargetList(targetList, targetListFileName);

  std::vector<TraceEntry> trace;
  readTrace(trace, traceFileName);

  // initialize state and regionRewards
  LSPos pos(f.startX, f.startY);
  std::vector<int> regionRewards(f.regionPriors.size(), 0);
  int r = f.grid.getCell(pos);
  regionRewards[r] = 1;

  // replay actions and determine relevant rewards
  int step = 0;
  int numLooks = 0;
  int numIllegalActions = 0;
  int numGoodSamples = 0;
  int numSamples = 0;
  double netSum = 0.0;
  LSGrid debugGrid = f.grid;
  FOR_EACH (entryP, trace) {
    if (verboseG) {
      printf("%d x%dy%dr", step, pos.x, pos.y);
      FOR (r, regionRewards.size()) {
	printf("%d", regionRewards[r]);
      }
      printf(" a=%d", entryP->a);
      int o = entryP->o;
      if (27 != o) {
	printf(" o=%d (%d,%d,%d)", o, o/9, (o/3)%3, o%3);
      }
      printf("\n");
    }

    LSAction a(entryP->a);
    double reward = 0;
    double cost;
    double penalty = 0;
    if (LS_ACT_LOOK == a.type) {
      numLooks++;
      cost = lookaheadCost;
    } else {
      cost = a.useSample ? 5 : 1;

      LSPos nextPos = m.getNeighbor(pos, a.moveDirection);

      unsigned char cellType = f.grid.getCellBounded(nextPos);
      if (LS_OBSTACLE == cellType) {
	penalty = 100;
	if (verboseG) {
	  printf("  ILLEGAL ACTION!\n");
	}
	numIllegalActions++;
      } else {
	bool isTarget = LSModel::getInTargetList(nextPos, targetList);
	int oldRewardLevel = regionRewards[cellType];
	int newRewardLevel = isTarget ? (a.useSample ? 3 : 2) : 1;
	if (newRewardLevel > oldRewardLevel) {
	  reward = m.getReward(oldRewardLevel, newRewardLevel);
	  regionRewards[cellType] = newRewardLevel;
	}
	if (a.useSample) {
	  if (isTarget) {
	    if (verboseG) {
	      printf("  good sample!\n");
	    }
	    numGoodSamples++;
	    debugGrid.setCell(nextPos, debugGrid.getCell(nextPos)+13);
	  } else {
	    if (verboseG) {
	      printf("  bad sample!\n");
	    }
	    debugGrid.setCell(nextPos, 23);
	  }
	  numSamples++;
	} else {
	  debugGrid.setCell(nextPos, 25);
	}

	pos = nextPos;
      }
    }
    double net = reward - cost - penalty;
    netSum += net * pow(0.999, step);

    if (verboseG) {
      printf("  reward=%lf cost=%lf penalty=%lf\n", reward, cost, penalty);
    }
    step++;
  }
  printf("\n");
  debugGrid.writeToFile(stdout, /* showCoords = */ true);
  printf("\n");

  printf("ACTIONS_LOOK_TOTAL %d %d\n", numLooks, (int)trace.size());
  printf("SAMPLES_GOOD_TOTAL %d %d\n", numGoodSamples, numSamples);
  printf("ILLEGAL_ACTIONS %d\n", numIllegalActions);
  printf("REWARD %.3lf\n", netSum);
}

void usage(const char* binaryName)
{
  cerr <<
    "usage: " << binaryName << " OPTIONS <foo.lifeSurvey> <foo.targetList> <foo.actions>\n"
    "  -h or --help    Display this help\n"
    "  -v or --verbose Print debug information\n";
  exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
  static char shortOptions[] = "hv";
  static struct option longOptions[]={
    {"help",          0,NULL,'h'},
    {"verbose",       0,NULL,'v'},
    {NULL,0,0,0}
  };

  while (1) {
    char optchar = getopt_long(argc,argv,shortOptions,longOptions,NULL);
    if (optchar == -1) break;

    switch (optchar) {
    case 'h': // help
      usage(argv[0]);
      break;

    case 'v': // verbose
      verboseG = true;
      break;

    case '?': // unknown option
    case ':': // option with missing parameter
      // getopt() prints an informative error message
      cerr << endl;
      usage(argv[0]);
      break;
    default:
      abort(); // never reach this point
    }
  }
  if (3 != argc-optind) {
    cerr << "ERROR: wrong number of arguments (should be 2)" << endl << endl;
    usage(argv[0]);
  }

  const char* lifeSurveyFileName = argv[optind++];
  const char* targetListFileName = argv[optind++];
  const char* traceFileName = argv[optind++];

  doit(lifeSurveyFileName, targetListFileName, traceFileName);
}

/***************************************************************************
 * REVISION HISTORY:
 * $Log: not supported by cvs2svn $
 * Revision 1.3  2006/08/04 22:33:38  trey
 * changed lookaheadCost to match modified LifeSurvey models
 *
 * Revision 1.2  2006/07/10 19:33:35  trey
 * moved some functions to LifeSurvey.cc
 *
 * Revision 1.1  2006/07/10 02:21:35  trey
 * initial check-in
 *
 *
 ***************************************************************************/


text:
package nlp;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.google.common.collect.Sets;
import com.google.common.io.Files;

public class SpecialPrefixes {
	File resourcesDirectory = new File("src/main/resources");
	private static String sPrefixesFileName = "specialPrefixes.txt";
	private static Set<String> specialPrefixes = new HashSet<>();
	private static String[] specialPrefixList;

	SpecialPrefixes(){
		try {
			File sPrefixesFile = new File(resourcesDirectory.getAbsolutePath() + File.separator + sPrefixesFileName);
			SpecialPrefixes.setSpecialPrefixes(Sets.newHashSet(Files.readLines(sPrefixesFile, Charset.forName("UTF-8"))));
			specialPrefixList = specialPrefixes.toArray(new String[specialPrefixes.size()]);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Set<String> getSpecialPrefixes() {
		return specialPrefixes;
	}

	public static void setSpecialPrefixes(Set<String> specialPrefixes) {
		SpecialPrefixes.specialPrefixes = specialPrefixes;
	}

	// Given a sentence and a prefix list, checks whether sentence starts with any of prefixes
	public boolean hasSpecialPrefix(String sentence) {
		return StringUtils.startsWithAny(sentence, specialPrefixList);
	}
}


text:
<!doctype html>

    <title>Code coverage report for core\admin\public\controllers\users.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../../prettify.css" />
    <link rel="stylesheet" href="../../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / core/admin/public/controllers/ users.js

        2.94%
        Statements
        1/34

        0%
        Branches
        0/15

        0%
        Functions
        0/10

        3.13%
        Lines
        1/32

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

1×

'use strict';

angular.module('mean.admin').controller('UsersController', ['$scope', 'Global', 'Menus', '$rootScope', '$http', 'Users', 'Circles',
    function($scope, Global, Menus, $rootScope, $http, Users, Circles) {

        $scope.global = Global;
        $scope.user = {};

        Circles.mine(function(acl) {

            var circles = acl.allowed;

            $scope.userSchema = [{
                title: 'Email',
                schemaKey: 'email',
                type: 'email',
                inTable: true
            }, {
                title: 'Name',
                schemaKey: 'name',
                type: 'text',
                inTable: true
            }, {
                title: 'Username',
                schemaKey: 'username',
                type: 'text',
                inTable: true
            }, {
                title: 'Roles',
                schemaKey: 'roles',
                type: 'select',
                options: circles,
                inTable: true
            }, {
                title: 'Password',
                schemaKey: 'password',
                type: 'password',
                inTable: false
            }, {
                title: 'Repeat password',
                schemaKey: 'confirmPassword',
                type: 'password',
                inTable: false
            }];

        });

        $scope.init = function() {
            Users.query({}, function(users) {
                $scope.users = users;
            });
        };

        $scope.add = function(valid) {
            if (!valid) return;
            if (!$scope.users) $scope.users = [];

            var user = new Users({
                email: $scope.user.email,
                name: $scope.user.name,
                username: $scope.user.username,
                password: $scope.user.password,
                confirmPassword: $scope.user.confirmPassword,
                roles: $scope.user.roles
            });

            user.$save(function(data, headers) {
                $scope.user = {};
                $scope.users.push(user);
                $scope.userError = null;
            }, function(data, headers) {
                $scope.userError = data.data;
            });
        };

        $scope.remove = function(user) {
            for (var i in $scope.users) {
                if ($scope.users[i] === user) {
                    $scope.users.splice(i, 1);
                }
            }

            user.$remove();
        };

        $scope.update = function(user, userField) {
            if (userField && userField === 'roles' && user.roles.indexOf('admin') === -1) {
                if (confirm('Are you sure you want to remove "admin" role?')) {
                    user.$update();
                } else {
                    user.roles = user.tmpRoles;
                }
            } else
                user.$update();
        };

        $scope.beforeSelect = function(userField, user) {
            if (userField === 'roles') {
                user.tmpRoles = user.roles;
            }
        };
    }
]);

  Code coverage
  generated by istanbul at Sun Dec 13 2015 21:30:20 GMT+0200 (FLE Standard Time)


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tutorial: Hello Dojo!</title>

Hello


text:
class MyCoolClass {
public:
  void foo() {
    // Do nothing.
  }
};

int main(int argc, char const *argv[]) {
  MyCoolClass cool_class;
  cool_class.foo();
  return 0;
}