text:
#include "fullcolorbrushtool.h"

// TnzTools includes
#include "tools/tool.h"
#include "tools/cursors.h"
#include "tools/toolutils.h"
#include "tools/toolhandle.h"
#include "tools/tooloptions.h"

#include "bluredbrush.h"

// TnzQt includes
#include "toonzqt/dvdialog.h"

// TnzLib includes
#include "toonz/tpalettehandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/tobjecthandle.h"
#include "toonz/ttileset.h"
#include "toonz/ttilesaver.h"
#include "toonz/strokegenerator.h"
#include "toonz/tstageobject.h"
#include "toonz/palettecontroller.h"

// TnzCore includes
#include "tgl.h"
#include "tproperty.h"
#include "trasterimage.h"
#include "tenv.h"
#include "tpalette.h"
#include "trop.h"
#include "tstream.h"
#include "tstroke.h"
#include "timagecache.h"

// Qt includes
#include <QCoreApplication> // Qt translation support

//----------------------------------------------------------------------------------

TEnv::IntVar FullcolorBrushMinSize("FullcolorBrushMinSize", 1);
TEnv::IntVar FullcolorBrushMaxSize("FullcolorBrushMaxSize", 5);
TEnv::IntVar FullcolorPressureSensibility("FullcolorPressureSensibility", 1);
TEnv::DoubleVar FullcolorBrushHardness("FullcolorBrushHardness", 100);
TEnv::DoubleVar FullcolorMinOpacity("FullcolorMinOpacity", 100);
TEnv::DoubleVar FullcolorMaxOpacity("FullcolorMaxOpacity", 100);

//----------------------------------------------------------------------------------

#define CUSTOM_WSTR L"<custom>"

//----------------------------------------------------------------------------------

namespace
{

int computeThickness(int pressure, const TIntPairProperty &property, bool isPath = false)
{
	if (isPath)
		return 0.0;
	double p = pressure / 255.0;
	double t = p * p * p;
	int thick0 = property.getValue().first;
	int thick1 = property.getValue().second;
	return tround(thick0 + (thick1 - thick0) * t);
}

//----------------------------------------------------------------------------------

double computeThickness(int pressure, const TDoublePairProperty &property, bool isPath = false)
{
	if (isPath)
		return 0.0;
	double p = pressure / 255.0;
	double t = p * p * p;
	double thick0 = property.getValue().first;
	double thick1 = property.getValue().second;
	if (thick1 < 0.0001)
		thick0 = thick1 = 0.0;
	return (thick0 + (thick1 - thick0) * t);
}

//----------------------------------------------------------------------------------

class FullColorBrushUndo : public ToolUtils::TFullColorRasterUndo
{
	TPoint m_offset;
	QString m_id;

public:
	FullColorBrushUndo(TTileSetFullColor *tileSet,
					   TXshSimpleLevel *level, const TFrameId &frameId, bool isFrameCreated,
					   const TRasterP &ras, const TPoint &offset)
		: ToolUtils::TFullColorRasterUndo(tileSet, level, frameId, isFrameCreated, false, 0), m_offset(offset)
	{
		static int counter = 0;

		m_id = QString("FullColorBrushUndo") + QString::number(counter++);
		TImageCache::instance()->add(m_id.toStdString(), TRasterImageP(ras));
	}

	~FullColorBrushUndo()
	{
		TImageCache::instance()->remove(m_id);
	}

	void redo() const
	{
		insertLevelAndFrameIfNeeded();

		TRasterImageP image = getImage();
		TRasterP ras = image->getRaster();

		TRasterImageP srcImg = TImageCache::instance()->get(m_id.toStdString(), false);
		ras->copy(srcImg->getRaster(), m_offset);

		TTool::getApplication()->getCurrentXsheet()->notifyXsheetChanged();
		notifyImageChanged();
	}

	int getSize() const
	{
		return sizeof(*this) + ToolUtils::TFullColorRasterUndo::getSize();
	}

	virtual QString getToolName()
	{
		return QString("Raster Brush Tool");
	}
	int getHistoryType()
	{
		return HistoryType::BrushTool;
	}
};

} // namespace

//************************************************************************
//    FullColor Brush Tool implementation
//************************************************************************

FullColorBrushTool::FullColorBrushTool(std::string name)
	: TTool(name), m_thickness("Thickness", 1, 100, 1, 5, false), m_pressure("Pressure Sensitivity", true), m_opacity("Opacity:", 0, 100, 100, 100, true), m_hardness("Hardness:", 0, 100, 100), m_preset("Preset:"), m_styleId(0), m_oldOpacity(1), m_brush(0), m_tileSet(0), m_tileSaver(0), m_notifier(0), m_presetsLoaded(false), m_firstTime(true)
{
	bind(TTool::RasterImage | TTool::EmptyTarget);

	m_prop.bind(m_thickness);
	m_prop.bind(m_hardness);
	m_prop.bind(m_opacity);
	m_prop.bind(m_pressure);
#ifndef STUDENT
	m_prop.bind(m_preset);
	m_preset.setId("BrushPreset");
#endif
}

//---------------------------------------------------------------------------------------------------

ToolOptionsBox *FullColorBrushTool::createOptionsBox()
{
	TPaletteHandle *currPalette = TTool::getApplication()->getPaletteController()->getCurrentLevelPalette();
	ToolHandle *currTool = TTool::getApplication()->getCurrentTool();
	return new BrushToolOptionsBox(0, this, currPalette, currTool);
}

//---------------------------------------------------------------------------------------------------

void FullColorBrushTool::onCanvasSizeChanged()
{
	onDeactivate();
	setWorkAndBackupImages();
}

//---------------------------------------------------------------------------------------------------

void FullColorBrushTool::updateTranslation()
{
	m_thickness.setQStringName(tr("Thickness"));
	m_pressure.setQStringName(tr("Pressure Sensitivity"));
	m_opacity.setQStringName(tr("Opacity:"));
	m_hardness.setQStringName(tr("Hardness:"));
	m_preset.setQStringName(tr("Preset:"));
}

//---------------------------------------------------------------------------------------------------

void FullColorBrushTool::onActivate()
{
	if (!m_notifier)
		m_notifier = new FullColorBrushToolNotifier(this);

	TTool::Application *app = getApplication();

	if (app->getCurrentObject()->isSpline()) {
		m_currentColor = TPixel32::Red;
		return;
	}

	int styleIndex = app->getCurrentLevelStyleIndex();
	TPalette *plt = app->getCurrentPalette()->getPalette();
	if (plt) {
		int style = app->getCurrentLevelStyleIndex();
		TColorStyle *colorStyle = plt->getStyle(style);
		m_currentColor = colorStyle->getMainColor();
	}

	if (m_firstTime) {
		m_firstTime = false;
		m_thickness.setValue(TIntPairProperty::Value(FullcolorBrushMinSize, FullcolorBrushMaxSize));
		m_pressure.setValue(FullcolorPressureSensibility ? 1 : 0);
		m_opacity.setValue(TDoublePairProperty::Value(FullcolorMinOpacity, FullcolorMaxOpacity));
		m_hardness.setValue(FullcolorBrushHardness);
	}

	m_brushPad = ToolUtils::getBrushPad(m_thickness.getValue().second, m_hardness.getValue() * 0.01);
	setWorkAndBackupImages();
}

//--------------------------------------------------------------------------------------------------

void FullColorBrushTool::onDeactivate()
{
	m_workRaster = TRaster32P();
	m_backUpRas = TRasterP();
}

//--------------------------------------------------------------------------------------------------

void FullColorBrushTool::updateWorkAndBackupRasters(const TRect &rect)
{
	TRasterImageP ri = TImageP(getImage(false, 1));
	if (!ri)
		return;

	TRasterP ras = ri->getRaster();

	TRect _rect = rect * ras->getBounds();
	TRect _lastRect = m_lastRect * ras->getBounds();

	if (_rect.isEmpty())
		return;

	if (m_lastRect.isEmpty()) {
		m_workRaster->extract(_rect)->clear();
		m_backUpRas->extract(_rect)->copy(ras->extract(_rect));
		return;
	}

	QList<TRect> rects = ToolUtils::splitRect(_rect, _lastRect);
	for (int i = 0; i < rects.size(); i++) {
		m_workRaster->extract(rects[i])->clear();
		m_backUpRas->extract(rects[i])->copy(ras->extract(rects[i]));
	}
}

//--------------------------------------------------------------------------------------------------

bool FullColorBrushTool::preLeftButtonDown()
{
	touchImage();

	if (m_isFrameCreated)
		setWorkAndBackupImages();

	return true;
}

//---------------------------------------------------------------------------------------------------

void FullColorBrushTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e)
{
	m_brushPos = m_mousePos = pos;

	Viewer *viewer = getViewer();
	if (!viewer)
		return;

	TRasterImageP ri = (TRasterImageP)getImage(true);
	if (!ri)
		ri = (TRasterImageP)touchImage();

	if (!ri)
		return;

	TRasterP ras = ri->getRaster();
	TDimension dim = ras->getSize();

	if (!(m_workRaster && m_backUpRas))
		setWorkAndBackupImages();

	m_workRaster->lock();

	double maxThick = m_thickness.getValue().second;
	double thickness = m_pressure.getValue() ? computeThickness(e.m_pressure, m_thickness) : maxThick;
	double opacity = (m_pressure.getValue() ? computeThickness(e.m_pressure, m_opacity) : m_opacity.getValue().second) * 0.01;
	TPointD rasCenter = TPointD(dim.lx * 0.5, dim.ly * 0.5);
	TThickPoint point(pos + rasCenter, thickness);
	TPointD halfThick(maxThick * 0.5, maxThick * 0.5);
	TRectD invalidateRect(pos - halfThick, pos + halfThick);

	m_points.clear();
	m_points.push_back(point);

	m_tileSet = new TTileSetFullColor(ras->getSize());
	m_tileSaver = new TTileSaverFullColor(ras, m_tileSet);
	double hardness = m_hardness.getValue() * 0.01;

	m_brush = new BluredBrush(m_workRaster, maxThick, m_brushPad, hardness == 1.0);
	m_strokeRect = m_brush->getBoundFromPoints(m_points);
	updateWorkAndBackupRasters(m_strokeRect);
	m_tileSaver->save(m_strokeRect);
	m_brush->addPoint(point, opacity);
	m_brush->updateDrawing(ras, m_backUpRas, m_currentColor, m_strokeRect, m_opacity.getValue().second * 0.01);
	m_oldOpacity = opacity;
	m_lastRect = m_strokeRect;

	invalidate(invalidateRect.enlarge(2));
}

//-------------------------------------------------------------------------------------------------------------

void FullColorBrushTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e)
{
	m_brushPos = m_mousePos = pos;

	TRasterImageP ri = (TRasterImageP)getImage(true);
	if (!ri)
		return;

	double maxThickness = m_thickness.getValue().second;
	double thickness = m_pressure.getValue() ? computeThickness(e.m_pressure, m_thickness) : maxThickness;
	double opacity = (m_pressure.getValue() ? computeThickness(e.m_pressure, m_opacity) : m_opacity.getValue().second) * 0.01;
	TDimension size = m_workRaster->getSize();
	TPointD rasCenter = TPointD(size.lx * 0.5, size.ly * 0.5);
	TThickPoint point(pos + rasCenter, thickness);

	TThickPoint old = m_points.back();
	if (norm2(point - old) < 4)
		return;

	TThickPoint mid((old + point) * 0.5, (point.thick + old.thick) * 0.5);
	m_points.push_back(mid);
	m_points.push_back(point);

	TRect bbox;
	int m = m_points.size();
	TRectD invalidateRect;
	if (m == 3) {
		// ho appena cominciato. devo disegnare un segmento
		TThickPoint pa = m_points.front();
		std::vector<TThickPoint> points;
		points.push_back(pa);
		points.push_back(mid);
		invalidateRect = ToolUtils::getBounds(points, maxThickness);
		bbox = m_brush->getBoundFromPoints(points);
		updateWorkAndBackupRasters(bbox + m_lastRect);
		m_tileSaver->save(bbox);
		m_brush->addArc(pa, (pa + mid) * 0.5, mid, m_oldOpacity, opacity);
		m_lastRect += bbox;
	} else {
		// caso generale: disegno un arco
		std::vector<TThickPoint> points;
		points.push_back(m_points[m - 4]);
		points.push_back(old);
		points.push_back(mid);
		invalidateRect = ToolUtils::getBounds(points, maxThickness);
		bbox = m_brush->getBoundFromPoints(points);
		updateWorkAndBackupRasters(bbox + m_lastRect);
		m_tileSaver->save(bbox);
		m_brush->addArc(m_points[m - 4], old, mid, m_oldOpacity, opacity);
		m_lastRect += bbox;
	}
	m_oldOpacity = opacity;
	m_brush->updateDrawing(ri->getRaster(), m_backUpRas, m_currentColor, bbox, m_opacity.getValue().second * 0.01);
	invalidate(invalidateRect.enlarge(2) - rasCenter);
	m_strokeRect += bbox;
}

//---------------------------------------------------------------------------------------------------------------

void FullColorBrushTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e)
{
	m_brushPos = m_mousePos = pos;

	TRasterImageP ri = (TRasterImageP)getImage(true);
	if (!ri)
		return;

	if (m_points.size() != 1) {
		double maxThickness = m_thickness.getValue().second;
		double thickness = m_pressure.getValue() ? computeThickness(e.m_pressure, m_thickness) : maxThickness;
		double opacity = (m_pressure.getValue() ? computeThickness(e.m_pressure, m_opacity) : m_opacity.getValue().second) * 0.01;
		TPointD rasCenter = ri->getRaster()->getCenterD();
		TThickPoint point(pos + rasCenter, thickness);
		m_points.push_back(point);
		int m = m_points.size();
		std::vector<TThickPoint> points;
		points.push_back(m_points[m - 3]);
		points.push_back(m_points[m - 2]);
		points.push_back(m_points[m - 1]);
		TRect bbox = m_brush->getBoundFromPoints(points);
		updateWorkAndBackupRasters(bbox);
		m_tileSaver->save(bbox);
		m_brush->addArc(points[0], points[1], points[2], m_oldOpacity, opacity);
		m_brush->updateDrawing(ri->getRaster(), m_backUpRas, m_currentColor, bbox, m_opacity.getValue().second * 0.01);
		TRectD invalidateRect = ToolUtils::getBounds(points, maxThickness);
		invalidate(invalidateRect.enlarge(2) - rasCenter);
		m_strokeRect += bbox;
		m_lastRect.empty();
	}

	if (m_brush) {
		delete m_brush;
		m_brush = 0;
	}

	m_workRaster->unlock();

	if (m_tileSet->getTileCount() > 0) {
		delete m_tileSaver;
		TTool::Application *app = TTool::getApplication();
		TXshLevel *level = app->getCurrentLevel()->getLevel();
		TXshSimpleLevelP simLevel = level->getSimpleLevel();
		TFrameId frameId = getCurrentFid();
		TRasterP ras = ri->getRaster()->extract(m_strokeRect)->clone();
		TUndoManager::manager()->add(new FullColorBrushUndo(m_tileSet, simLevel.getPointer(), frameId,
															m_isFrameCreated, ras, m_strokeRect.getP00()));
	}

	notifyImageChanged();
	m_strokeRect.empty();
}

//---------------------------------------------------------------------------------------------------------------

void FullColorBrushTool::mouseMove(const TPointD &pos, const TMouseEvent &e)
{
	struct Locals {
		FullColorBrushTool *m_this;

		void setValue(TIntPairProperty &prop, const TIntPairProperty::Value &value)
		{
			prop.setValue(value);

			m_this->onPropertyChanged(prop.getName());
			TTool::getApplication()->getCurrentTool()->notifyToolChanged();
		}

		void addMinMax(TIntPairProperty &prop, double add)
		{
			const TIntPairProperty::Range &range = prop.getRange();

			TIntPairProperty::Value value = prop.getValue();
			value.second = tcrop<double>(value.second + add, range.first, range.second);
			value.first = tcrop<double>(value.first + add, range.first, range.second);

			setValue(prop, value);
		}

	} locals = {this};

	switch (e.getModifiersMask()) {
	/*-- Altキー+マウス移動で、ブラシサイズ(Min/Maxとも)を変える(CtrlやShiftでは誤操作の恐れがある) --*/
	case TMouseEvent::ALT_KEY: {
		// User wants to alter the minimum brush size
		const TPointD &diff = pos - m_mousePos;
		double add = (fabs(diff.x) > fabs(diff.y)) ? diff.x : diff.y;

		locals.addMinMax(m_thickness, int(add));
	}

	DEFAULT:
		m_brushPos = pos;
	}

	m_mousePos = pos;
	invalidate();
}

//-------------------------------------------------------------------------------------------------------------

void FullColorBrushTool::draw()
{
	if (TRasterImageP ri = TRasterImageP(getImage(false))) {
		TRasterP ras = ri->getRaster();

		glColor3d(1.0, 0.0, 0.0);

		tglDrawCircle(m_brushPos, (m_minThick + 1) * 0.5);
		tglDrawCircle(m_brushPos, (m_maxThick + 1) * 0.5);
	}
}

//--------------------------------------------------------------------------------------------------------------

void FullColorBrushTool::onEnter()
{
	TImageP img = getImage(false);
	TRasterImageP ri(img);
	if (ri) {
		m_minThick = m_thickness.getValue().first;
		m_maxThick = m_thickness.getValue().second;
	} else {
		m_minThick = 0;
		m_maxThick = 0;
	}
	Application *app = getApplication();
	if (app->getCurrentObject()->isSpline()) {
		m_currentColor = TPixel32::Red;
		return;
	}

	TPalette *plt = app->getCurrentPalette()->getPalette();
	if (!plt)
		return;

	int style = app->getCurrentLevelStyleIndex();
	TColorStyle *colorStyle = plt->getStyle(style);
	m_currentColor = colorStyle->getMainColor();
}

//----------------------------------------------------------------------------------------------------------

void FullColorBrushTool::onLeave()
{
	m_minThick = 0;
	m_maxThick = 0;
}

//----------------------------------------------------------------------------------------------------------

TPropertyGroup *FullColorBrushTool::getProperties(int targetType)
{
	if (!m_presetsLoaded)
		initPresets();

	return &m_prop;
}

//----------------------------------------------------------------------------------------------------------

void FullColorBrushTool::onImageChanged()
{
	setWorkAndBackupImages();
}

//----------------------------------------------------------------------------------------------------------

void FullColorBrushTool::setWorkAndBackupImages()
{
	TRasterImageP ri = (TRasterImageP)getImage(false, 1);
	if (!ri)
		return;

	TRasterP ras = ri->getRaster();
	TDimension dim = ras->getSize();

	if (!m_workRaster || m_workRaster->getLx() > dim.lx || m_workRaster->getLy() > dim.ly)
		m_workRaster = TRaster32P(dim);

	if (!m_backUpRas || m_backUpRas->getLx() > dim.lx || m_backUpRas->getLy() > dim.ly ||
		m_backUpRas->getPixelSize() != ras->getPixelSize())
		m_backUpRas = ras->create(dim.lx, dim.ly);

	m_strokeRect.empty();
	m_lastRect.empty();
}

//------------------------------------------------------------------

bool FullColorBrushTool::onPropertyChanged(std::string propertyName)
{
	m_minThick = m_thickness.getValue().first;
	m_maxThick = m_thickness.getValue().second;
	if (propertyName == "Hardness:" || propertyName == "Thickness") {
		m_brushPad = ToolUtils::getBrushPad(m_thickness.getValue().second, m_hardness.getValue() * 0.01);
		TRectD rect(m_brushPos - TPointD(m_maxThick + 2, m_maxThick + 2),
					m_brushPos + TPointD(m_maxThick + 2, m_maxThick + 2));
		invalidate(rect);
	}
	/*if(propertyName == "Hardness:" || propertyName == "Opacity:")
    setWorkAndBackupImages();*/
	FullcolorBrushMinSize = m_minThick;
	FullcolorBrushMaxSize = m_maxThick;
	FullcolorPressureSensibility = m_pressure.getValue();
	FullcolorBrushHardness = m_hardness.getValue();
	FullcolorMinOpacity = m_opacity.getValue().first;
	FullcolorMaxOpacity = m_opacity.getValue().second;

	if (propertyName == "Preset:") {
		loadPreset();
		getApplication()->getCurrentTool()->notifyToolChanged();
		return true;
	}

	if (m_preset.getValue() != CUSTOM_WSTR) {
		m_preset.setValue(CUSTOM_WSTR);
		getApplication()->getCurrentTool()->notifyToolChanged();
	}

	return true;
}

//------------------------------------------------------------------

void FullColorBrushTool::initPresets()
{
	if (!m_presetsLoaded) {
		//If necessary, load the presets from file
		m_presetsLoaded = true;
		m_presetsManager.load(TEnv::getConfigDir() + "brush_raster.txt");
	}

	//Rebuild the presets property entries
	const std::set<BrushData> &presets = m_presetsManager.presets();

	m_preset.deleteAllValues();
	m_preset.addValue(CUSTOM_WSTR);

	std::set<BrushData>::const_iterator it, end = presets.end();
	for (it = presets.begin(); it != end; ++it)
		m_preset.addValue(it->m_name);
}

//----------------------------------------------------------------------------------------------------------

void FullColorBrushTool::loadPreset()
{
	const std::set<BrushData> &presets = m_presetsManager.presets();
	std::set<BrushData>::const_iterator it;

	it = presets.find(BrushData(m_preset.getValue()));
	if (it == presets.end())
		return;

	const BrushData &preset = *it;

	try //Don't bother with RangeErrors
	{
		m_thickness.setValue(TIntPairProperty::Value(tmax((int)preset.m_min, 1), preset.m_max));
		m_brushPad = ToolUtils::getBrushPad(preset.m_max, preset.m_hardness * 0.01);
		m_hardness.setValue(preset.m_hardness, true);
		m_opacity.setValue(TDoublePairProperty::Value(preset.m_opacityMin, preset.m_opacityMax));
		m_pressure.setValue(preset.m_pressure);
	} catch (...) {
	}
}

//------------------------------------------------------------------

void FullColorBrushTool::addPreset(QString name)
{
	//Build the preset
	BrushData preset(name.toStdWString());

	preset.m_min = m_thickness.getValue().first;
	preset.m_max = m_thickness.getValue().second;
	preset.m_hardness = m_hardness.getValue();
	preset.m_opacityMin = m_opacity.getValue().first;
	preset.m_opacityMax = m_opacity.getValue().second;
	preset.m_pressure = m_pressure.getValue();

	//Pass the preset to the manager
	m_presetsManager.addPreset(preset);

	//Reinitialize the associated preset enum
	initPresets();

	//Set the value to the specified one
	m_preset.setValue(preset.m_name);
}

//------------------------------------------------------------------

void FullColorBrushTool::removePreset()
{
	std::wstring name(m_preset.getValue());
	if (name == CUSTOM_WSTR)
		return;

	m_presetsManager.removePreset(name);
	initPresets();

	//No parameter change, and set the preset value to custom
	m_preset.setValue(CUSTOM_WSTR);
}

//==========================================================================================================

FullColorBrushToolNotifier::FullColorBrushToolNotifier(FullColorBrushTool *tool)
	: m_tool(tool)
{
	TTool::Application *app = m_tool->getApplication();
	TXshLevelHandle *levelHandle;
	if (app)
		levelHandle = app->getCurrentLevel();
	bool ret = false;
	if (levelHandle) {
		bool ret = connect(levelHandle, SIGNAL(xshCanvasSizeChanged()), this, SLOT(onCanvasSizeChanged()));
		assert(ret);
	}
}

//==========================================================================================================

FullColorBrushTool fullColorPencil("T_Brush");


text:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

/// Global variables
Mat src, src_gray;
int thresh = 200;
int max_thresh = 255;

char* source_window = "Source image";
char* corners_window = "Corners detected";

/// Function header
void cornerHarris_demo( int, void* );

/** @function main */
int main( int argc, char** argv )
{
  /// Load source image and convert it to gray
  src = imread( argv[1], 1 );
  cvtColor( src, src_gray, CV_BGR2GRAY );

  /// Create a window and a trackbar
  namedWindow( source_window, CV_WINDOW_AUTOSIZE );
  createTrackbar( "Threshold: ", source_window, &thresh, max_thresh, cornerHarris_demo );
  imshow( source_window, src );

  cornerHarris_demo( 0, 0 );

  waitKey(0);
  return(0);
}

/** @function cornerHarris_demo */
void cornerHarris_demo( int, void* )
{

  Mat dst, dst_norm, dst_norm_scaled;
  dst = Mat::zeros( src.size(), CV_32FC1 );

  /// Detector parameters
  int blockSize = 2;
  int apertureSize = 3;
  double k = 0.04;

  /// Detecting corners
  cornerHarris( src_gray, dst, blockSize, apertureSize, k, BORDER_DEFAULT );

  /// Normalizing
  normalize( dst, dst_norm, 0, 255, NORM_MINMAX, CV_32FC1, Mat() );
  convertScaleAbs( dst_norm, dst_norm_scaled );

  /// Drawing a circle around corners
  for( int j = 0; j < dst_norm.rows ; j++ )
     { for( int i = 0; i < dst_norm.cols; i++ )
          {
            if( (int) dst_norm.at<float>(j,i) > thresh )
              {
               circle( dst_norm_scaled, Point( i, j ), 5,  Scalar(0), 2, 8, 0 );
              }
          }
     }
  /// Showing the result
  namedWindow( corners_window, CV_WINDOW_AUTOSIZE );
  imshow( corners_window, dst_norm_scaled );
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.storm.kafka.bolt;

import org.apache.storm.Config;
import org.apache.storm.Constants;
import org.apache.storm.task.GeneralTopologyContext;
import org.apache.storm.task.IOutputCollector;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.TupleImpl;
import org.apache.storm.tuple.Values;
import org.apache.storm.utils.Utils;
import org.apache.storm.utils.TupleUtils;
import com.google.common.collect.ImmutableList;
import kafka.api.OffsetRequest;
import kafka.api.FetchRequest;
import kafka.javaapi.FetchResponse;
import kafka.javaapi.OffsetResponse;
import kafka.javaapi.consumer.SimpleConsumer;
import kafka.javaapi.message.ByteBufferMessageSet;
import kafka.message.Message;
import kafka.message.MessageAndOffset;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.*;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.apache.storm.kafka.*;
import org.apache.storm.kafka.trident.GlobalPartitionInformation;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.Future;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;

public class KafkaBoltTest {

    private static final String TEST_TOPIC = "test-topic";
    private KafkaTestBroker broker;
    private KafkaBolt bolt;
    private Config config = new Config();
    private KafkaConfig kafkaConfig;
    private SimpleConsumer simpleConsumer;

    @Mock
    private IOutputCollector collector;

    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
        broker = new KafkaTestBroker();
        setupKafkaConsumer();
        config.put(KafkaBolt.TOPIC, TEST_TOPIC);
        bolt = generateStringSerializerBolt();
    }

    @After
    public void shutdown() {
        simpleConsumer.close();
        broker.shutdown();
        bolt.cleanup();
    }

    private void setupKafkaConsumer() {
        GlobalPartitionInformation globalPartitionInformation = new GlobalPartitionInformation(TEST_TOPIC);
        globalPartitionInformation.addPartition(0, Broker.fromString(broker.getBrokerConnectionString()));
        BrokerHosts brokerHosts = new StaticHosts(globalPartitionInformation);
        kafkaConfig = new KafkaConfig(brokerHosts, TEST_TOPIC);
        simpleConsumer = new SimpleConsumer("localhost", broker.getPort(), 60000, 1024, "testClient");
    }

    @Test
    public void shouldNotAcknowledgeTickTuples() throws Exception {
        // Given
        Tuple tickTuple = mockTickTuple();

        // When
        bolt.execute(tickTuple);

        // Then
        verify(collector, never()).ack(tickTuple);
    }

    @Test
    public void executeWithKey() throws Exception {
        String message = "value-123";
        String key = "key-123";
        Tuple tuple = generateTestTuple(key, message);
        bolt.execute(tuple);
        verify(collector).ack(tuple);
        verifyMessage(key, message);
    }

    /* test synchronous sending */
    @Test
    public void executeWithByteArrayKeyAndMessageSync() {
        boolean async = false;
        boolean fireAndForget = false;
        bolt = generateDefaultSerializerBolt(async, fireAndForget, null);
        String keyString = "test-key";
        String messageString = "test-message";
        byte[] key = keyString.getBytes();
        byte[] message = messageString.getBytes();
        Tuple tuple = generateTestTuple(key, message);
        bolt.execute(tuple);
        verify(collector).ack(tuple);
        verifyMessage(keyString, messageString);
    }

    /* test asynchronous sending (default) */
    @Test
    public void executeWithByteArrayKeyAndMessageAsync() {
        boolean async = true;
        boolean fireAndForget = false;
        String keyString = "test-key";
        String messageString = "test-message";
        byte[] key = keyString.getBytes();
        byte[] message = messageString.getBytes();
        final Tuple tuple = generateTestTuple(key, message);

        final ByteBufferMessageSet mockMsg = mockSingleMessage(key, message);
        simpleConsumer.close();
        simpleConsumer = mockSimpleConsumer(mockMsg);
        KafkaProducer<?, ?> producer = mock(KafkaProducer.class);
        when(producer.send(any(ProducerRecord.class), any(Callback.class))).thenAnswer(new Answer<Future>() {
            @Override
            public Future answer(InvocationOnMock invocationOnMock) throws Throwable {
                Callback cb = (Callback) invocationOnMock.getArguments()[1];
                cb.onCompletion(null, null);
                return mock(Future.class);
            }
        });
        bolt = generateDefaultSerializerBolt(async, fireAndForget, producer);
        bolt.execute(tuple);
        verify(collector).ack(tuple);
        verifyMessage(keyString, messageString);
    }

    /* test with fireAndForget option enabled */
    @Test
    public void executeWithByteArrayKeyAndMessageFire() {
        boolean async = true;
        boolean fireAndForget = true;
        bolt = generateDefaultSerializerBolt(async, fireAndForget, null);
        String keyString = "test-key";
        String messageString = "test-message";
        byte[] key = keyString.getBytes();
        byte[] message = messageString.getBytes();
        Tuple tuple = generateTestTuple(key, message);
        final ByteBufferMessageSet mockMsg = mockSingleMessage(key, message);
        simpleConsumer.close();
        simpleConsumer = mockSimpleConsumer(mockMsg);
        KafkaProducer<?, ?> producer = mock(KafkaProducer.class);
        // do not invoke the callback of send() in order to test whether the bolt handle the fireAndForget option
        // properly.
        doReturn(mock(Future.class)).when(producer).send(any(ProducerRecord.class), any(Callback.class));
        bolt.execute(tuple);
        verify(collector).ack(tuple);
        verifyMessage(keyString, messageString);
    }

    /* test bolt specified properties */
    @Test
    public void executeWithBoltSpecifiedProperties() {
        boolean async = false;
        boolean fireAndForget = false;
        bolt = defaultSerializerBoltWithSpecifiedProperties(async, fireAndForget);
        String keyString = "test-key";
        String messageString = "test-message";
        byte[] key = keyString.getBytes();
        byte[] message = messageString.getBytes();
        Tuple tuple = generateTestTuple(key, message);
        bolt.execute(tuple);
        verify(collector).ack(tuple);
        verifyMessage(keyString, messageString);
    }

    private KafkaBolt generateStringSerializerBolt() {
        Properties props = new Properties();
        props.put("acks", "1");
        props.put("bootstrap.servers", broker.getBrokerConnectionString());
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("metadata.fetch.timeout.ms", 1000);
        KafkaBolt bolt = new KafkaBolt().withProducerProperties(props);
        bolt.prepare(config, null, new OutputCollector(collector));
        bolt.setAsync(false);
        return bolt;
    }

    private KafkaBolt generateDefaultSerializerBolt(boolean async, boolean fireAndForget,
                                                    KafkaProducer<?, ?> mockProducer) {
        Properties props = new Properties();
        props.put("acks", "1");
        props.put("bootstrap.servers", broker.getBrokerConnectionString());
        props.put("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put("metadata.fetch.timeout.ms", 1000);
        props.put("linger.ms", 0);
        KafkaBolt bolt = new KafkaBolt().withProducerProperties(props);
        bolt.prepare(config, null, new OutputCollector(collector));
        bolt.setAsync(async);
        bolt.setFireAndForget(fireAndForget);
        if (mockProducer != null) {
            Whitebox.setInternalState(bolt, "producer", mockProducer);
        }
        return bolt;
    }

    private KafkaBolt defaultSerializerBoltWithSpecifiedProperties(boolean async, boolean fireAndForget) {
        Properties props = new Properties();
        props.put("acks", "1");
        props.put("bootstrap.servers", broker.getBrokerConnectionString());
        props.put("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put("metadata.fetch.timeout.ms", 1000);
        props.put("linger.ms", 0);
        KafkaBolt bolt = new KafkaBolt().withProducerProperties(props);
        bolt.prepare(config, null, new OutputCollector(collector));
        bolt.setAsync(async);
        bolt.setFireAndForget(fireAndForget);
        return bolt;
    }

    @Test
    public void executeWithoutKey() throws Exception {
        String message = "value-234";
        Tuple tuple = generateTestTuple(message);
        bolt.execute(tuple);
        verify(collector).ack(tuple);
        verifyMessage(null, message);
    }

    @Test
    public void executeWithBrokerDown() throws Exception {
        broker.shutdown();
        String message = "value-234";
        Tuple tuple = generateTestTuple(message);
        bolt.execute(tuple);
        verify(collector).fail(tuple);
    }

    private boolean verifyMessage(String key, String message) {
        long lastMessageOffset = KafkaUtils.getOffset(simpleConsumer, kafkaConfig.topic, 0, OffsetRequest.LatestTime()) - 1;
        ByteBufferMessageSet messageAndOffsets = KafkaUtils.fetchMessages(kafkaConfig, simpleConsumer,
                new Partition(Broker.fromString(broker.getBrokerConnectionString()),kafkaConfig.topic, 0), lastMessageOffset);
        MessageAndOffset messageAndOffset = messageAndOffsets.iterator().next();
        Message kafkaMessage = messageAndOffset.message();
        ByteBuffer messageKeyBuffer = kafkaMessage.key();
        String keyString = null;
        String messageString = new String(Utils.toByteArray(kafkaMessage.payload()));
        if (messageKeyBuffer != null) {
            keyString = new String(Utils.toByteArray(messageKeyBuffer));
        }
        assertEquals(key, keyString);
        assertEquals(message, messageString);
        return true;
    }

    private Tuple generateTestTuple(Object key, Object message) {
        TopologyBuilder builder = new TopologyBuilder();
        GeneralTopologyContext topologyContext = new GeneralTopologyContext(builder.createTopology(), new Config(), new HashMap<>(), new HashMap<>(), new HashMap<>(), "") {
            @Override
            public Fields getComponentOutputFields(String componentId, String streamId) {
                return new Fields("key", "message");
            }
        };
        return new TupleImpl(topologyContext, new Values(key, message), 1, "");
    }

    private Tuple generateTestTuple(Object message) {
        TopologyBuilder builder = new TopologyBuilder();
        GeneralTopologyContext topologyContext = new GeneralTopologyContext(builder.createTopology(), new Config(), new HashMap<>(), new HashMap<>(), new HashMap<>(), "") {
            @Override
            public Fields getComponentOutputFields(String componentId, String streamId) {
                return new Fields("message");
            }
        };
        return new TupleImpl(topologyContext, new Values(message), 1, "");
    }

    private Tuple mockTickTuple() {
        Tuple tuple = mock(Tuple.class);
        when(tuple.getSourceComponent()).thenReturn(Constants.SYSTEM_COMPONENT_ID);
        when(tuple.getSourceStreamId()).thenReturn(Constants.SYSTEM_TICK_STREAM_ID);
        // Sanity check
        assertTrue(TupleUtils.isTick(tuple));
        return tuple;
    }

    private static ByteBufferMessageSet mockSingleMessage(byte[] key, byte[] message) {
        ByteBufferMessageSet sets = mock(ByteBufferMessageSet.class);
        MessageAndOffset msg = mock(MessageAndOffset.class);
        final List<MessageAndOffset> msgs = ImmutableList.of(msg);
        doReturn(msgs.iterator()).when(sets).iterator();
        Message kafkaMessage = mock(Message.class);
        doReturn(ByteBuffer.wrap(key)).when(kafkaMessage).key();
        doReturn(ByteBuffer.wrap(message)).when(kafkaMessage).payload();
        doReturn(kafkaMessage).when(msg).message();
        return sets;
    }

    private static SimpleConsumer mockSimpleConsumer(ByteBufferMessageSet mockMsg) {
        SimpleConsumer simpleConsumer = mock(SimpleConsumer.class);
        FetchResponse resp = mock(FetchResponse.class);
        doReturn(resp).when(simpleConsumer).fetch(any(FetchRequest.class));
        OffsetResponse mockOffsetResponse = mock(OffsetResponse.class);
        doReturn(new long[] {}).when(mockOffsetResponse).offsets(anyString(), anyInt());
        doReturn(mockOffsetResponse).when(simpleConsumer).getOffsetsBefore(any(kafka.javaapi.OffsetRequest.class));
        doReturn(mockMsg).when(resp).messageSet(anyString(), anyInt());
        return simpleConsumer;
    }
}


text:
<?php

final class PhabricatorTokenLeaderController
  extends PhabricatorTokenController {

  public function shouldAllowPublic() {
    return true;
  }

  public function processRequest() {
    $request = $this->getRequest();
    $user = $request->getUser();

    $pager = new AphrontPagerView();
    $pager->setURI($request->getRequestURI(), 'page');
    $pager->setOffset($request->getInt('page'));

    $query = id(new PhabricatorTokenReceiverQuery());
    $objects = $query->setViewer($user)->executeWithOffsetPager($pager);
    $counts = $query->getTokenCounts();

    $handles = array();
    $phids = array();
    if ($counts) {
      $phids = mpull($objects, 'getPHID');
      $handles = id(new PhabricatorHandleQuery())
        ->setViewer($user)
        ->withPHIDs($phids)
        ->execute();
    }

    $list = new PHUIObjectItemListView();
    $list->setStackable(true);
    foreach ($phids as $object) {
      $count = idx($counts, $object, 0);
      $item = id(new PHUIObjectItemView());
      $handle = $handles[$object];

      $item->setHeader($handle->getFullName());
      $item->setHref($handle->getURI());
      $item->addAttribute(pht('Tokens: %s', $count));
      $list->addItem($item);
    }

    $title = pht('Token Leader Board');

    $box = id(new PHUIObjectBoxView())
      ->setHeaderText($title)
      ->appendChild($list);

    $nav = $this->buildSideNav();
    $nav->setCrumbs(
      $this->buildApplicationCrumbs()
        ->addTextCrumb($title));
    $nav->selectFilter('leaders/');

    $nav->appendChild($box);
    $nav->appendChild($pager);

    return $this->buildApplicationPage(
      $nav,
      array(
        'title' => $title,
      ));
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Misc. Inf. , Kew 118 (1898)

#### Original name
Hypoxylon heliscus Mont.

### Remarks
null


text:
import * as React from 'react'
import {Header} from "./Header";
import {AppContext} from "./App";
import {render, screen} from '@testing-library/react';
import userEvent from "@testing-library/user-event";

describe('<Header/>', () => {
    let appContext = {
        pairingHistoryOpen: false,
        setPairingHistoryOpen: jest.fn(),
        setSystemAlert: () => {}
    };

    it('renders a left caret when isPairingHistoryPanelOpen is false', () => {
        render(
            <AppContext.Provider value={appContext}>
                <Header/>
            </AppContext.Provider>
        );

        expect(screen.getByLabelText('open history panel')).not.toBeNull();
        expect(screen.queryByLabelText('close history panel')).toBeNull();

    });

    it('renders a right caret when isPairingHistoryPanelOpen is true', () => {
        appContext.pairingHistoryOpen = true;
        render(
            <AppContext.Provider value={appContext}>
                <Header/>
            </AppContext.Provider>
        );
        expect(screen.getByLabelText('close history panel')).not.toBeNull();
        expect(screen.queryByLabelText('open history panel')).toBeNull();

    })

    it('calls setPairingHistoryPanelOpen with true when clicking on the history label and isPairingHistoryPanelOpen is false', () => {
        appContext.pairingHistoryOpen = false;
        render(
            <AppContext.Provider value={appContext}>
                <Header/>
            </AppContext.Provider>
        );

        userEvent.click(screen.getByText('HISTORY'));
        expect(appContext.setPairingHistoryOpen).toHaveBeenCalledWith(true)
    })

    it('calls setPairingHistoryPanelOpen with false when clicking on the history label and isPairingHistoryPanelOpen is true', () => {
        appContext.pairingHistoryOpen = true;

        render(
            <AppContext.Provider value={appContext}>
                <Header/>
            </AppContext.Provider>
        );

        userEvent.click(screen.getByText('HISTORY'));
        expect(appContext.setPairingHistoryOpen).toHaveBeenCalledWith(false)
    })
})


text:
beforeEach(() => {
    jasmine.addMatchers({
        toHaveProperties(util, customEqualityMatchers): jasmine.CustomMatcher {
            function equalOnPropNames<T extends Object>(
                actual: T,
                expected: Array<keyof T>,
            ): boolean {
                return expected.every(prop => prop in actual);
            }

            function equalOnPropValues<T extends {[k: string]: any}>(
                actual: T,
                expected: Partial<T>,
            ): boolean {
                return Object.keys(expected)
                    .every(
                        key => key in actual
                            && util.equals(expected[key], actual[key], customEqualityMatchers),
                    );
            }

            return {
                compare<T extends Object>(
                    actual: T,
                    expected: Partial<T> | Array<keyof T>,
                    ...customMsgs: Array<any>
                ) {
                    let pass: boolean;
                    let name: string;
                    if (Array.isArray(expected)) {
                        pass = equalOnPropNames(actual, expected);
                        name = 'To have properties';
                    } else {
                        pass = equalOnPropValues(actual, expected);
                        name = 'To have properties equal to';
                    }

                    return {
                        pass,
                        message: util.buildFailureMessage(
                            name,
                            pass,
                            actual,
                            expected,
                            ...customMsgs,
                        ),
                    };
                },
            };
        },
        toBeInstanceOf(util): jasmine.CustomMatcher {
            return {
                compare<T>(
                    actual: T,
                    expected: Function,
                    ...customMsgs: Array<any>
                ) {
                    const pass = actual instanceof expected;
                    return {
                        pass,
                        message: util.buildFailureMessage(
                            'To be instance of',
                            pass,
                            actual,
                            expected,
                            ...customMsgs,
                        ),
                    };
                },
            };
        },
        toBeOfLength(util): jasmine.CustomMatcher {
            return {
                compare<T extends ArrayLike<T>>(
                    actual: T,
                    expected: number,
                    ...customMsgs: Array<any>
                ) {
                    const pass = actual?.length === expected;
                    return {
                        pass,
                        message: util.buildFailureMessage(
                            'To be of length',
                            pass,
                            actual,
                            expected,
                            ...customMsgs,
                        ),
                    };
                },
            };
        },
    });
    jasmine.addCustomEqualityTester((first: any, second: any): boolean | undefined => {
        const firstAsInt8Array: Int8Array | undefined = tryAsInt8Array(first);
        const secondAsInt8Array: Int8Array | undefined = tryAsInt8Array(second);

        if (firstAsInt8Array === undefined || secondAsInt8Array === undefined) {
            return;
        }

        if (firstAsInt8Array.length !== secondAsInt8Array.length) {
            return false;
        }
        return firstAsInt8Array.every((num, i) => num === secondAsInt8Array[i]);
    });
});

function tryAsInt8Array(obj: any): Int8Array | undefined {
    if (obj instanceof ArrayBuffer) {
        return new Int8Array(obj);
    } else if (ArrayBuffer.isView(obj)) {
        return new Int8Array(obj.buffer);
    }
}

// eslint-disable-next-line @typescript-eslint/no-namespace
declare namespace jasmine {
    /* eslint-disable @typescript-eslint/method-signature-style */
    interface Matchers<T> {
        toHaveProperties(
            expectation: Partial<T> | Array<keyof T>,
            ...expectationFailOutput: Array<any>,
        ): boolean;

        toBeInstanceOf(expectation: Function, ...expectationFailOutput: Array<any>): boolean;
    }

    interface ArrayLikeMatchers<T> extends Matchers<ArrayLike<T>> {
        toBeOfLength: (expectation: number, ...expectationFailOutput: Array<any>) => boolean;
    }
}


text:
REVO
===

REVO is an open platform for building, deploying and running node.js applications. It allows programmers to assemble complex apps in minutes by reusing existing components.

Install REVO
---

```
$ sudo npm install -g revo
```

Run REVO
---
```
$ sudo revo
revo 0.7.0:
```
The new prompt shows that revo is running and accepting commands.

Type `help` to get the list of available commands. If everything runs well, the command's output looks like this:

```
revo 0.7.0: help

  Commands:

    help [command]  Provides help for a given command.
    exit            Exits revo's interactive CLI.

  Command Groups:

    app *           7 sub-commands.
    recipe *        9 sub-commands.
    component *     2 sub-commands.
    web *           1 sub-command.
```
This message shows that your installation appears to be working correctly.

Let's try to create a simple application. Type `app` to get the list of application-specific sub-commands:

```
revo 0.7.0: app

  Commands:

    app create [options] <app_name> [recipe]  Create a new app <app_name> in the local repo
    app deploy <app_name> [target]            Deploy a previously created app
    app list                                  Get a list of local apps
    app start <app_name>                      Run an existing app locally
    app stop <app_name>                       Stop a running app
    app export <app_name>                     Export <app_name> from the local repo into a zip file
    app remove <app_name>                     Delete <app_name> from the local repo

```

To create an application you need a recipe. Let's switch to recipes for a second. Type `recipe` for the available recipe sub-commands:

```
revo 0.7.0: recipe

  Commands:

    recipe create <recipe_name>  Create a new empty recipe and make it current
    recipe list                  Get a list of local recipes
    recipe use <recipe>          Make <recipe> the current source for app creation, deployment, etc
    recipe load <filename>       Load a local <filename> recipe into the local repo
    recipe pull <url>            Fetch a recipe from <url> to local repo
    recipe show [recipe]         Show [recipe] or current recipe source
    recipe remove [recipe]       Delete the current or the specified [recipe] from the local repo
    recipe set <key> <value>     Set recipe metadata. Used to set recipe name, description and version

  Command Groups:

    recipe add *            1 sub-command.
```

An application recipe can be stored on any server but in order to create an application, you need a copy of the recipe in the local repo. Let's fetch a basic recipe from github:

```
revo 0.7.0: recipe pull https://raw.githubusercontent.com/clonq/revo-recipes/master/hello-world.yaml
recipe hello-world downloaded to local repo
```

Type `recipe list` to show the list of recipes avaiable in your local repository:

```
revo 0.7.0: recipe list

Recipe Name  Version  Platform  Author   Description

hello-world  1.0.0    web       revo     basic Hello World recipe

```

The "hello-world" recipe has been successfully downloaded to your local repo. Let's use it to build a new app. Type `app create myapp hello-world` to create a new application named "myapp" using the "hello-world" recipe:

```
revo 0.7.0: app create myapp hello-world
Using local recipe: hello-world
myapp app created in local repo
```

To verify the application was created, type `app list`:

```
revo 0.7.0: app list

Application Name  Repository  Status

myapp             local       stopped
```

The app is now available in the local repo. You can run myapp right from the revo prompt:

```
revo 0.7.0: app start myapp
myapp started
revo 0.7.0:
```
Revo starts the app in the background and returns to the command prompt. The hello-world recipe creates a simple web app based on the [initializr](http://www.initializr.com) bootstrap theme. The server runs by default on port 3000 and you can check the app runing at http://localhost:3000.

Executing `app list` again will reflect the new status of the app:

```
revo 0.7.0: app list

Application Name  Repository  Status

myapp             local       running
```

You can stop a running app with `app stop <applicaton_name>`.

To retrieve the app from the repository and package it as a standalone node.js application, use `app package`:

```
revo 0.7.0: app package myapp
myapp has been packaged to /revo/demo/myapp.zip
```
The app is now available as a zip file in your current directory. Exit revo, unzip the new app in the directory of your choice and run the app:

```
revo 0.7.0: exit
See you soon
MacBook:/revo/demo revo-user$ ls -al
...
-rw-r--r--   1 revo-user  staff   9.1M 22 Aug 11:42 myapp.zip
...
MacBook:/revo/demo revo-user$ tar xf myapp.zip
MacBook:/revo/demo revo-user$ cd myapp
MacBook:/revo/demo revo-user$ ./myapp

> myapp@1.0.0 start /revo/demo/myapp
> DEBUG=revo:* ./container/run

  revo:container web server v. 1.0.0 started on port 3000 +0ms
  revo:container Initializing components +6ms
  revo:container [dummy_bootstrap]	 loaded +2ms
  revo:container registering handler for revo/hello-world:load +1ms
  revo:container [dummy_bootstrap]	 initialized +0ms
  revo:container piggyback websocket server started +1ms

```

Open <http://localhost:3000> in your browser to see the Hello World web app.

Recipes
---
In the REVO world, you use recipes to create new applications. Recipes are .yaml files that describe how an application should be assembled from components. Let's have a look at the hello-world recipe. At revo prompt type `recipe show hello-world`:

```
revo 0.7.0: recipe show hello-world
{
    "name": "hello-world",
    "description": "basic Hello World recipe",
    "version": "1.0.0",
    "author": "revo",
    "platform": {
        "type": "web",
        "theme": {
            "name": "initializr/bootstrap",
            "url": "http://www.initializr.com/builder?boot-hero&jquerymin&h5bp-iecond&h5bp-chromeframe&h5bp-analytics&h5bp-favicon&h5bp-appletouchicons&modernizrrespond&izr-emptyscript&boot-css&boot-scripts",
            "zip_path": "initializr",
            "placeholders": [
                {
                    "main": ".jumbotron"
                },
                {
                    "login": "#navbar form"
                }
            ]
        }
    },
    "components": [
        {
            "clonq/revo-ui-bootstrap": {
                "type": "web",
                "repo": "github"
            }
        },
        {
            "revo/hello-world": {
                "type": "web"
            }
        }
    ],
    "config": {
        "clonq/revo-ui-bootstrap": {
            "load": "revo/hello-world",
            "remove": "nav"
        }
    }
}
```
The important sections in a recipe are: `platform`, `components` and `config`.

Platform

The `platform` key in a revo recipe describes and optionally configures some high level aspects of the application. The `type` sub-key informs the revo application generator module about the environment the generated application will run on and can have two values `cli` or `web`.

For web applications, a second `theme` sub-key defines the web theme or the web page layout. If the theme was created on developer's machine and thus already available in the local repo, a `name` key is enough to retrieve it and generate the web app page layout. The theme could be stored anywhere though and referenced via the `url` key. The hello-world recipe leverages [Initializr](http://www.initializr.com/)'s Bootstrap template.

When the `url` is present, revo downloads the theme locally, unpacks it and registers the template with the local repo for future references.

The `placeholders` key defines DOM elements that can be used by web components to inject their content into the web page. The hello-world component for example overwrites Bootstrap's original content of the .jumbotron div element.

Components

The `components` section is a list of component entries. Each entry has a `name` key, a `repo` key identifying where the component should be fetched from and optionaly a `type` key.

The component name uniquely identifies the component within the repo.

The repo can be either the keyword `github` or an url. Revo will try to download the component from the repo url. If the value of the repo key is `github`, revo will fetch the component from *https://github.com/`name`/archive/master.zip*

The type of a component can be either `common` or `web`. If no type is specified, `common` will be assumed.

Config

The `config` section holds configuration data specific to each component. For example, the hello-world recipe configures a UI bootstrap component to automatically load the revo/hello-world web component everytime the user hits application's main page and to remove the *nav* element originally present in the bootstrap html template.

Components
---
Components are the main ingredient of a revo recipe. They are regular node.js modules that follow a certain design pattern in order to communicate with the other components within a revo runtime container. Components can be of one of two types: `common` or `web`. Common components don't have a UI, web components are designed to live in a web page.

Components can be stored anywhere on the web. When declared in a recipe, the revo engine retrieves them from the specified url and caches them in the local repo. When the application is assembled, the declared components are copied to the application directory and the application configuration is updated to contain component-specific config.

Revo components are designed to be reused in any revo-generated application. The recipe for a new application simply lists the required components and their optional configuration elements. The rest is taken care by the event-based communication mechanism leveraged by the revo runtime.

Everyone is encouraged to write revo components following the [revo design principles for component development]().

Here are some components I developed for the revo platform: [config](https://github.com/clonq/revo-config),
[config-ui](https://github.com/clonq/revo-config-ui),
[ui-bootstrap](https://github.com/clonq/revo-ui-bootstrap),
[webbridge](https://github.com/clonq/revo-webbridge),
[profile-ui](https://github.com/clonq/revo-profile-ui),
[profile](https://github.com/clonq/revo-profile),
[notification](https://github.com/clonq/revo-notification).

Also check out my [revo recipes repository](https://github.com/clonq/revo-recipes).

---

![](https://travis-ci.org/clonq/revo.svg?branch=master)


text:
import cgi
from http.server import BaseHTTPRequestHandler
import io

class PostHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        # Parse the form data posted
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={
                'REQUEST_METHOD': 'POST',
                'CONTENT_TYPE': self.headers['Content-Type'],
            }
        )

        # Begin the response
        self.send_response(200)
        self.send_header('Content-Type',
                         'text/plain; charset=utf-8')
        self.end_headers()

        out = io.TextIOWrapper(
            self.wfile,
            encoding='utf-8',
            line_buffering=False,
            write_through=True,
        )

        out.write('Client: {}\n'.format(self.client_address))
        out.write('User-agent: {}\n'.format(
            self.headers['user-agent']))
        out.write('Path: {}\n'.format(self.path))
        out.write('Form data:\n')

        # Echo back information about what was posted in the form
        for field in form.keys():
            field_item = form[field]
            if field_item.filename:
                # The field contains an uploaded file
                file_data = field_item.file.read()
                file_len = len(file_data)
                del file_data
                out.write(
                    '\tUploaded {} as {!r} ({} bytes)\n'.format(
                        field, field_item.filename, file_len)
                )
            else:
                # Regular form value
                out.write('\t{}={}\n'.format(
                    field, form[field].value))

        # Disconnect our encoding wrapper from the underlying
        # buffer so that deleting the wrapper doesn't close
        # the socket, which is still being used by the server.
        out.detach()

if __name__ == '__main__':
    from http.server import HTTPServer
    server = HTTPServer(('localhost', 8080), PostHandler)
    print('Starting server, use <Ctrl-C> to stop')
    server.serve_forever()


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
     	http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd">

	<tx:annotation-driven />
	<!-- 开发 -->
	<context:property-placeholder location="classpath:settings.xml" ignore-resource-not-found="true" />
	<!-- 引入同文件夹下的redis属性配置文件 	-->
	<!-- <import resource="spring-redis.xml" /> -->

	<!-- 导入mongodb的配置文件 <import resource="spring-mongodb.xml"/> -->
	<!-- 数据源 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="${druid.initialSize:10}" />
		<property name="minIdle" value="${druid.minIdle:10}" />
		<property name="maxActive" value="${druid.maxActive:500}" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="${druid.maxWait:60000}" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenMillis:60000}" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${druid.minTimeMillis:300000}" />

		<property name="validationQuery" value="${druid.validationQuery:SELECT 'x'}" />
		<property name="testWhileIdle" value="${druid.testWhileIdle:true}" />
		<property name="testOnBorrow" value="${druid.testOnBorrow:false}" />
		<property name="testOnReturn" value="${druid.testOnReturn:false}" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。 -->
		<property name="poolPreparedStatements" value="${druid.poolPreparedStatements:false}" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPrepared:20}" />

		<!-- 配置监控统计拦截的filters <property name="filters" value="${druid.filters:stat}" /> -->
		<property name="proxyFilters">
			<list>
				<ref bean="stat-filter" />
				<ref bean="wall-filter" />
			</list>
		</property>
	</bean>

	<bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
		<property name="slowSqlMillis" value="1000" />
		<property name="logSlowSql" value="true" />
		<property name="mergeSql" value="true" />
	</bean>

	<bean id="wall-filter" class="com.alibaba.druid.wall.WallFilter">
		<property name="dbType" value="mysql" />
		<property name="config" ref="wall-filter-config" />
	</bean>

	<bean id="wall-filter-config" class="com.alibaba.druid.wall.WallConfig">
		<property name="multiStatementAllow" value="true" />
	</bean>

	<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"></bean>
	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
		<property name="patterns">
			<list>
				<value>io.school.controller.*</value>
				<value>io.school.service.*</value>
			</list>
		</property>
	</bean>
	<aop:config>
		<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
	</aop:config>

	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="io.school.dao" />
	</bean>
</beans>


text:
@interface YZZDataHelper : NSObject

+ (NSMutableArray *)JsonHelper:(NSString *)jsonString;

@end


text:
"""Create a range of logistic regression problems with varying number of parameters.
Use Tensorflow to train models to solve the logistic regression. Plot the relationship
between number of training samples and fscore of the trained models.
For a introduction to logistic regression, please refer to
  https://www.youtube.com/watch?v=tEk6ikTKGYU
"""
import tensorflow as tf
import numpy as np
import scipy.spatial as sp
import matplotlib.pyplot as plt

# The maximum number of model parameters to explore.
kMaxNumParameters = 256
# The maximum multiple of model parameters to use as number of training samples.
kMaxTrainingSamplesMultiple = 16
kMaxNumTrainingSamples = kMaxNumParameters * kMaxTrainingSamplesMultiple
# The threshold to use for classification
kLogisticClassificationThreshold = 0.5
# The regularization parameter (lambda) of cost function.
# Please refer to https://www.youtube.com/watch?v=ef2OPmANLaM
kRegularizationParameter = 0.1
# The number of explorations for a given number of model parameters. Increase this
# to smooth out the curve for a particular number of model parameters.
kNumModelIterations = 10
# Random data representing the input feature space.
xref_data = np.float32(np.random.uniform(-1, 1, [kMaxNumParameters, kMaxNumTrainingSamples]))
# Random data representing the test samples.
tref_data = np.float32(np.random.uniform(-1, 1, [kMaxNumParameters, 1000]))
# The ratio of training labels that are noisy, i.e, opposite of what they
# really should be. 0.15 indicated 15% of the training labels are noisy.
kNoisyLabelsRatio = 0.15
# Noise to be added to the training labels.
noise = np.random.uniform(0.0, 1.0, [1, kMaxNumTrainingSamples]) < kNoisyLabelsRatio
print "Noise = " , np.float32(np.sum(noise)) / kMaxNumTrainingSamples, "%"

def LogisticClassification(model, data):
  """
  Apply logistic classfication to the data according to:
    y = 1 if sigmoid(model.data) > threshold, 0 otherwise
    Reference: https://www.youtube.com/watch?v=tEk6ikTKGYU
  Args:
    model: The parameters of the logistic regression model.
    data: The instance to be classified.
  Returns:
    Classification result.
  """
  return 1 / (1 + np.exp(-np.dot(model, data))) > kLogisticClassificationThreshold

def GetFscore(truth, observed):
  """
  Computes f-score based on the differences between supplied truth and observed.
  Reference: https://en.wikipedia.org/wiki/Precision_and_recall
  Args:
    truth: The ground truth against which the f-score is computed.
    observed: The observations for which the f-score is computed.
  Returns:
    The computed f-score.
  """
  # True positives.
  tp = np.sum(np.logical_and(truth, observed))
  # False positives.
  fp = np.sum(np.logical_and(np.logical_not(truth), observed))
  # False negatives.
  fn = np.sum(np.logical_and(truth, np.logical_not(observed)))
  # True negatives.
  tn = np.sum(np.logical_and(np.logical_not(truth), np.logical_not(observed)))
  precision = np.float32(tp) / (tp + fp)
  recall = np.float32(tp) / (tp + fn)
  fscore = 2.0 * precision * recall / (precision + recall)
  return fscore

def RunModel(num_parameters, num_training_samples):
  """
  Creates a logistic regression model of size num_parameters by initializing
  the parameters randomly. Generates ground truth for the model and adds
  the specified amount of noise to the labels. Then uses gradient decent to
  train the model and determines the f-score of the trained model on a
  randomly generated test.
  Args:
    num_parameters: The number of parameters of the logistic regression model.
    num_training_samples The number of training samples used to train the model.
  Returns:
    The f-score of the trained model.
  """

  # Generate a model by randomly choosing it's parameters.
  model = np.random.uniform(-1, 1, [1, num_parameters])
  # Choose the subset of the total feature space applicable for this model.
  x_data = xref_data[0:num_parameters, 0:num_training_samples]
  # Apply the model on the input features.
  y_labels_no_noise = LogisticClassification(model, x_data)
  # Generate the training labels by adding some noise to the model output.
  # The xor function flips a fraction of the labels given.
  y_labels = np.logical_xor(y_labels_no_noise, noise[0, 0:num_training_samples])

  # Construct a logistic regression model. Alternatively, one can also use
  # tf.nn.softmax_cross_entropy_with_logits() for compactness. This version
  # makes the model explicit by exposing the basic units.
  W = tf.Variable(tf.random_uniform([1, num_parameters], -1.0, 1.0))
  y = tf.sigmoid(tf.matmul(W, x_data))
  # Contruct the regularization term.
  r = tf.mul(kRegularizationParameter, tf.reduce_sum(tf.square(W)))

  # Mimize the L2 loss against the given labels along with square of
  # the parameters for regularization.
  loss = tf.add(tf.nn.l2_loss(tf.sub(y, y_labels)), r)
  optimizer = tf.train.GradientDescentOptimizer(0.5)
  train = optimizer.minimize(loss)

  # For initializing the variables.
  init = tf.initialize_all_variables()

  # Launch the Tensorflow graph
  sess = tf.Session()
  sess.run(init)

  # Fit the plane.
  for step in xrange(0, 1000):
    sess.run(train)

  predicted_model = sess.run(W)

  # The subset of the test data used for this model.
  t_data = tref_data[0:num_parameters, :]
  # The computed test labels.
  yt_data = LogisticClassification(model, t_data)
  # The labels predicated by the model for the test data.
  predicted_data = LogisticClassification(predicted_model, t_data)
  # Return peformance of the model.
  return GetFscore(yt_data, predicted_data)

# Generate model with number of parameters as 10, 40, 70,..
N = kMaxNumParameters
plots = []
legends = []
for n in [N/8, N/4, N/2, N]:
  if (n < 4):
    continue
  # Collect the performance data for the plot
  data = []
  # Vary the samples as 1x, 2x, 3x.. of parameters
  for samples in range(n, kMaxTrainingSamplesMultiple * n, n):
    score_sum = 0.0
    # Number of times each model is repeated.
    for iter in range(0, kNumModelIterations):
      score = RunModel(n, samples)
      print "Params=", n, " Samples=", samples, " Iter=", iter, " Score=", score
      score_sum += score
    # Average the score over multiple iterations to smooth out the curves
    data.append(score_sum / kNumModelIterations)
  p, = plt.plot(data, label=str(n))
  plots.append(p)
  legends.append(str(n))
plt.legend(plots, legends)
plt.ylabel("f-score")
plt.xlabel("num-training-samples / num-model-parameters")
plt.show()


text:
package exnihiloadscensio.registries;

import lombok.AllArgsConstructor;
import lombok.Getter;
import net.minecraft.item.ItemStack;

@AllArgsConstructor
public class HammerReward {

	@Getter
	private ItemStack stack;
	@Getter
	private int miningLevel;
	@Getter
	private float chance;
	@Getter
	private float fortuneChance;
}


text:
package org.apache.flink.table.planner.operations;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.OperationUtils;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.operations.QueryOperationVisitor;
import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
import org.apache.flink.table.runtime.types.LogicalTypeDataTypeConverter;
import org.apache.flink.table.types.DataType;

import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.type.RelDataType;

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

/**
 * Wrapper for valid logical plans generated by Planner.
 */
@Internal
public class PlannerQueryOperation implements QueryOperation {

	private final RelNode calciteTree;
	private final TableSchema tableSchema;

	public PlannerQueryOperation(RelNode calciteTree) {
		this.calciteTree = calciteTree;

		RelDataType rowType = calciteTree.getRowType();
		String[] fieldNames = rowType.getFieldNames().toArray(new String[0]);
		DataType[] fieldTypes = rowType.getFieldList()
				.stream()
				.map(field ->
						LogicalTypeDataTypeConverter.fromLogicalTypeToDataType(
								FlinkTypeFactory.toLogicalType(field.getType())))
				.toArray(DataType[]::new);

		this.tableSchema = TableSchema.builder().fields(fieldNames, fieldTypes).build();
	}

	public RelNode getCalciteTree() {
		return calciteTree;
	}

	@Override
	public TableSchema getTableSchema() {
		return tableSchema;
	}

	@Override
	public String asSummaryString() {
		return OperationUtils.formatWithChildren(
				"PlannerNode",
				Collections.emptyMap(),
				getChildren(),
				Operation::asSummaryString);
	}

	@Override
	public List<QueryOperation> getChildren() {
		return Collections.emptyList();
	}

	@Override
	public <T> T accept(QueryOperationVisitor<T> visitor) {
		return visitor.visit(this);
	}
}


text:
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Osu.Objects
{
    /// <summary>
    /// Note that this should not be used for timing correctness.
    /// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information.
    /// </summary>
    public class SliderTailCircle : SliderEndCircle
    {
        public SliderTailCircle(Slider slider)
            : base(slider)
        {
        }

        public override Judgement CreateJudgement() => new SliderTailJudgement();

        public class SliderTailJudgement : OsuJudgement
        {
            public override HitResult MaxResult => HitResult.SmallTickHit;
        }
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Microsoft.Azure.WebJobs.Extensions.Files.Listener
{
    /// <summary>
    /// Represents a single status entry in the status file.
    /// </summary>
    internal class StatusFileEntry
    {
        /// <summary>
        /// Gets or sets the current <see cref="ProcessingState"/>
        /// </summary>
        [JsonConverter(typeof(StringEnumConverter))]
        public ProcessingState State { get; set; }

        /// <summary>
        /// Gets or sets the timestamp of the entry.
        /// </summary>
        public DateTime Timestamp { get; set; }

        /// <summary>
        /// Gets or sets the timestamp of the last write to the target file.
        /// </summary>
        public DateTime LastWrite { get; set; }

        /// <summary>
        /// Gets or sets the <see cref="WatcherChangeTypes"/> enumeration value indicating
        /// which type of file operation this entry is for.
        /// </summary>
        [JsonConverter(typeof(StringEnumConverter))]
        public WatcherChangeTypes ChangeType { get; set; }

        /// <summary>
        /// Gets or sets the ID of the instance that created this entry.
        /// </summary>
        public string InstanceId { get; set; }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Axis2/C: thread mutex routines</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Classes

Files

Directories

Related Pages

Examples

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

thread mutex routines

[utilities]

Defines

#define 	AXIS2_THREAD_MUTEX_DEFAULT   0x0

#define 	AXIS2_THREAD_MUTEX_NESTED   0x1

#define 	AXIS2_THREAD_MUTEX_UNNESTED   0x2

Typedefs

typedef struct

axutil_thread_mutex_t 	axutil_thread_mutex_t

Functions

AXIS2_EXTERN

axutil_thread_mutex_t * 	axutil_thread_mutex_create (axutil_allocator_t *allocator, unsigned int flags)

AXIS2_EXTERN

axis2_status_t 	axutil_thread_mutex_lock (axutil_thread_mutex_t *mutex)

AXIS2_EXTERN

axis2_status_t 	axutil_thread_mutex_trylock (axutil_thread_mutex_t *mutex)

AXIS2_EXTERN

axis2_status_t 	axutil_thread_mutex_unlock (axutil_thread_mutex_t *mutex)

AXIS2_EXTERN

axis2_status_t 	axutil_thread_mutex_destroy (axutil_thread_mutex_t *mutex)

Define Documentation

          #define AXIS2_THREAD_MUTEX_DEFAULT   0x0

platform-optimal lock behavior

          #define AXIS2_THREAD_MUTEX_NESTED   0x1

enable nested (recursive) locks

          #define AXIS2_THREAD_MUTEX_UNNESTED   0x2

disable nested locks

Typedef Documentation

          typedef struct axutil_thread_mutex_t axutil_thread_mutex_t

Opaque thread-local mutex structure

Function Documentation

          AXIS2_EXTERN axutil_thread_mutex_t* axutil_thread_mutex_create
          (
          axutil_allocator_t *
           allocator,

          unsigned int
           flags

          )

Create and initialize a mutex that can be used to synchronize threads.

Parameters:

	flags 	Or'ed value of:

           AXIS2_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
           AXIS2_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
           AXIS2_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).

	allocator 	the allocator from which to allocate the mutex.

Returns:

mutex the memory address where the newly created mutex will be stored.

Warning:

Be cautious in using AXIS2_THREAD_MUTEX_DEFAULT. While this is the most optimial mutex based on a given platform's performance charateristics, it will behave as either a nested or an unnested lock.

          AXIS2_EXTERN axis2_status_t axutil_thread_mutex_destroy
          (
          axutil_thread_mutex_t *
           mutex
           )

Destroy the mutex and free the memory associated with the lock.

Parameters:

	mutex 	the mutex to destroy.

          AXIS2_EXTERN axis2_status_t axutil_thread_mutex_lock
          (
          axutil_thread_mutex_t *
           mutex
           )

Acquire the lock for the given mutex. If the mutex is already locked, the current thread will be put to sleep until the lock becomes available.

Parameters:

	mutex 	the mutex on which to acquire the lock.

          AXIS2_EXTERN axis2_status_t axutil_thread_mutex_trylock
          (
          axutil_thread_mutex_t *
           mutex
           )

Attempt to acquire the lock for the given mutex. If the mutex has already been acquired, the call returns immediately

Parameters:

	mutex 	the mutex on which to attempt the lock acquiring.

          AXIS2_EXTERN axis2_status_t axutil_thread_mutex_unlock
          (
          axutil_thread_mutex_t *
           mutex
           )

Release the lock for the given mutex.

Parameters:

	mutex 	the mutex from which to release the lock.

<address style="text-align: right;">Generated on Fri Apr 17 11:49:45 2009 for Axis2/C by

 1.5.3 </address>