answer stringlengths 15 1.25M |
|---|
var searchData=
[
['canvas_2ehpp',['Canvas.hpp',['../Canvas_8hpp.html',1,'']]],
['checkbutton_2ehpp',['CheckButton.hpp',['../CheckButton_8hpp.html',1,'']]],
['combobox_2ehpp',['ComboBox.hpp',['../ComboBox_8hpp.html',1,'']]],
['config_2ehpp',['Config.hpp',['../Config_8hpp.html',1,'']]],
['container_2ehpp',['Container.hpp',['../Container_8hpp.html',1,'']]],
['context_2ehpp',['Context.hpp',['../Context_8hpp.html',1,'']]]
]; |
#include "inlinefield.h"
InlineField::InlineField(Sounds *sounds, QWidget *parent) :
TextField(sounds, parent)
{
m_width = 620;
m_height = 32;
m_rightSymbols = 0;
m_countSymbols = 0;
m_wrongSymbols = 0;
m_layout = new QHBoxLayout(this);
m_layout->setContentsMargins(0,0,0,0);
m_layout->setSpacing(0);
m_newText = new QLabel(this);
m_oldText = new QLabel(this);
m_layout->addWidget(m_oldText);
m_layout->addWidget(m_newText);
m_oldText->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
m_newText->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
QFont font = m_newText->font();
font.setPixelSize(16);
font.setStyleHint(QFont::Monospace);
font.setFamily("monospace");
m_oldText->setFont(font);
m_newText->setFont(font);
m_oldText->setStyleSheet("border: 0px; Background: #ccc");
m_newText->setStyleSheet("border: 1px Solid #ccc; padding: 0;");
this->setMinimumHeight(m_height);
this->setMinimumWidth(m_width);
//parent->setMinimumHeight(m_height);
//parent->setMinimumWidth(m_width);
m_newText->setMinimumHeight(m_height);
m_newText->setMinimumWidth((int) (m_width / 2));
m_oldText->setMinimumHeight(m_height);
m_oldText->setMinimumWidth((int) (m_width / 2));
m_newText->setContentsMargins(-3,0,0,0);
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
}
void InlineField::keyPressed(QString key)
{
//qDebug()<<"InlineField::keyPressed: "<<key;
if( key == "Backspace")
{
} else {
if( key == "Space" )
key = " ";
if (m_newText->text().left(1) == key)
{
m_sounds->play("type");
m_oldText->setText(m_oldText->text()+key);
m_newText->setText(m_newText->text().right(m_newText->text().size()-1));
m_rightSymbols++;
if( m_newText->text().length() == 0 )
{
m_sounds->play("finish");
emit noMoreText();
}
} else {
m_sounds->play("error");
m_wrongSymbols++;
}
}
}
void InlineField::setText(QString text)
{
//qDebug()<<"InlineField::setText: "<<text;
m_text = text;
reset();
}
QString InlineField::nextSymbol()
{
//qDebug()<<"InlineField::getNextSymbol: ";
return m_newText->text().left(1);
}
void InlineField::reset()
{
m_oldText->setText("");
m_newText->setText(m_text);
m_countSymbols = m_text.size();
m_rightSymbols = 0;
m_wrongSymbols = 0;
}
void InlineField::setFontPixelSize(int size)
{
m_fontPixelSize = size;
m_height = size * 2;
this->setMinimumHeight(m_height);
QFont font = m_newText->font();
font.setPixelSize(m_fontPixelSize);
m_newText->setMinimumHeight(m_height);
m_newText->setFont(font);
font = m_oldText->font();
font.setPixelSize(m_fontPixelSize);
m_oldText->setMinimumHeight(m_height);
m_oldText->setFont(font);
}
void InlineField::resizeEvent(QResizeEvent *event)
{
m_width = event->size().width();
m_height = event->size().height();
int newTextWidth = (int) m_width / 2;
int oldTextWidth = m_width - newTextWidth;
m_newText->setMinimumWidth(newTextWidth);
m_oldText->setMinimumWidth(oldTextWidth);
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebTool.Controllers
{
public class <API key> : Controller
{
private <API key> db = new <API key>();
// GET: /Enrollment/
public ActionResult Index()
{
var enrollments = db.Enrollments.Include(e => e.Course).Include(e => e.Person);
return View(enrollments.ToList());
}
// GET: /Enrollment/Details/5
public ActionResult Details(int id = 0)
{
Enrollment enrollment = db.Enrollments.Find(id);
if (enrollment == null)
{
return HttpNotFound();
}
return View(enrollment);
}
// GET: /Enrollment/Create
public ActionResult Create()
{
ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title");
ViewBag.StudentID = new SelectList(db.People, "ID", "LastName");
return View();
}
// POST: /Enrollment/Create
[HttpPost]
[<API key>]
public ActionResult Create(Enrollment enrollment)
{
if (ModelState.IsValid)
{
db.Enrollments.Add(enrollment);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
ViewBag.StudentID = new SelectList(db.People, "ID", "LastName", enrollment.StudentID);
return View(enrollment);
}
// GET: /Enrollment/Edit/5
public ActionResult Edit(int id = 0)
{
Enrollment enrollment = db.Enrollments.Find(id);
if (enrollment == null)
{
return HttpNotFound();
}
ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
ViewBag.StudentID = new SelectList(db.People, "ID", "LastName", enrollment.StudentID);
return View(enrollment);
}
// POST: /Enrollment/Edit/5
[HttpPost]
[<API key>]
public ActionResult Edit(Enrollment enrollment)
{
if (ModelState.IsValid)
{
db.Entry(enrollment).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
ViewBag.StudentID = new SelectList(db.People, "ID", "LastName", enrollment.StudentID);
return View(enrollment);
}
// GET: /Enrollment/Delete/5
public ActionResult Delete(int id = 0)
{
Enrollment enrollment = db.Enrollments.Find(id);
if (enrollment == null)
{
return HttpNotFound();
}
return View(enrollment);
}
// POST: /Enrollment/Delete/5
[HttpPost, ActionName("Delete")]
[<API key>]
public ActionResult DeleteConfirmed(int id)
{
Enrollment enrollment = db.Enrollments.Find(id);
db.Enrollments.Remove(enrollment);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
} |
if(a==b){
c=0;
}else{
d=1;
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CS430_FinalPractice
{
public partial class Step3 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Local
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedIndex == 0)
{
int input = Convert.ToInt32(txtInput.Text.ToString());
txtOutput.Text = (input / 1532).ToString();
}
if (RadioButtonList1.SelectedIndex == 1)
{
int input = Convert.ToInt32(txtInput.Text.ToString());
txtOutput.Text = (input * 1532).ToString();
}
}
//WCF Calls
// Use default name when adding the service reference, and just change stuff in here
protected void btnWCF_Click(object sender, EventArgs e)
{
ServiceReference1.Service1Client client = new
ServiceReference1.Service1Client();
int returnString;
if (RadioButtonList1.SelectedIndex == 0)
{
returnString = client.dollars2Dublons(Convert.ToInt32(txtInput.Text.ToString()));
txtOutput.Text = returnString.ToString();
}
if (RadioButtonList1.SelectedIndex == 1)
{
returnString = client.dublons2Dollars(Convert.ToInt32(txtInput.Text.ToString()));
txtOutput.Text = returnString.ToString();
}
}
}
} |
/**
* @author Elahe Jalalpour
*/
package me.elahe.riverrider;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
public class Drawing extends JPanel {
int[][] map;
int[][] p;
public static int[][] m = new int[7][10];
private BufferedImage grass;
private BufferedImage myPlane;
private BufferedImage enemy;
private BufferedImage ground;
private BufferedImage fuel;
private BufferedImage missile;
private BufferedImage lost;
private BufferedImage stop;
private BufferedImage win;
public static int t;
public static int k = 1000;
public static int he = 3;
public static int enemyCount;
public static ArrayList<missiles> missiles;
public Drawing(int[][] map, int[][] p) {
Timer timer = new Timer(800, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
missiles ma;
ma = new missiles(Drawing.he, 9);
new Thread(ma).start();
missiles.add(ma);
}
});
timer.start();
missiles = new ArrayList<>();
this.map = map;
this.p = p;
try {
win = ImageIO.read(ClassLoader.<API key>("win.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
try {
stop = ImageIO.read(ClassLoader.<API key>("stop.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
try {
lost = ImageIO.read(ClassLoader.<API key>("lost.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
try {
grass = ImageIO.read(ClassLoader.<API key>("grass.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
try {
myPlane = ImageIO.read(ClassLoader.<API key>("myPlane.png"));
} catch (IOException e) {
e.printStackTrace();
}
try {
enemy = ImageIO.read(ClassLoader.<API key>("enemy_1.png"));
} catch (IOException e) {
e.printStackTrace();
}
try {
ground = ImageIO.read(ClassLoader.<API key>("ground.png"));
} catch (IOException e) {
e.printStackTrace();
}
try {
fuel = ImageIO.read(ClassLoader.<API key>("fuel.png"));
} catch (IOException e) {
e.printStackTrace();
}
try {
missile = ImageIO.read(ClassLoader.<API key>("Rocket.png"));
} catch (IOException e) {
e.printStackTrace();
}
setVisible(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
if (p[he][k - 1] != 1 && map[1][k - 1] != 9 && Manager.fuel > 0 && Drawing.enemyCount < 10) {
for (int i = 0; i < 7; i++) {
for (int j = k - 10; j < k; j++) {
if (map[i][j] == 0) {
g2d.drawImage(grass, 64 * i, 64 * (j - (k - 9)) + Drawing.t, 64, 64, null);
} else if (map[i][j] == 1) {
g2d.drawImage(ground, 64 * i, 64 * (j - (k - 9)) + Drawing.t, 64, 64, null);
}
}
}
for (int i = 0; i < 7; i++) {
for (int j = k - 10; j < k; j++) {
if (p[i][j] == 1) {
g2d.drawImage(enemy, 64 * i, 64 * (j - (k - 9)) + Drawing.t, 64, 64, null);
} else if (p[i][j] == 2) {
g2d.drawImage(fuel, 64 * i, 64 * (j - (k - 9)) + Drawing.t, 30, 30, null);
}
}
}
for (missiles mi : missiles) {
g2d.drawImage(missile, mi.xLocation * 64 + 28, mi.ylLocation * 64 - 10, 10, 64, this);
if (p[mi.xLocation][Drawing.k - 1 - mi.ylLocation + 1] == 1) {
p[mi.xLocation][Drawing.k - 1 - mi.ylLocation + 1] = 0;
Drawing.enemyCount++;
}
}
g2d.drawImage(myPlane, 64 * he, 64 * (8), 64, 64, null);
} else if (map[1][k - 1] == 9) {
g2d.clearRect(0, 0, 1000, 1000);
g2d.drawImage(stop, 100, 100, 300, 300, null);
} else if (Drawing.enemyCount >= 10) {
g2d.clearRect(0, 0, 1000, 1000);
g2d.drawImage(win, 100, 100, 300, 300, null);
} else {
g2d.clearRect(0, 0, 1000, 1000);
g2d.setBackground(Color.blue);
g2d.drawImage(lost, 100, 100, 300, 300, null);
}
}
} |
#include <glibmm.h>
#include "sharp/directory.hpp"
#include "sharp/fileinfo.hpp"
#include "sharp/string.hpp"
namespace sharp {
void <API key>(const std::string & dir,
const std::string & ext,
std::list<std::string> & list)
{
if (!Glib::file_test(dir, Glib::FILE_TEST_EXISTS))
return;
if (!Glib::file_test(dir, Glib::FILE_TEST_IS_DIR))
return;
Glib::Dir d(dir);
for (Glib::Dir::iterator itr = d.begin(); itr != d.end(); ++itr) {
const std::string file(dir + "/" + *itr);
const sharp::FileInfo file_info(file);
const std::string & extension = file_info.get_extension();
if (Glib::file_test(file, Glib::<API key>)
&& (ext.empty() || (sharp::string_to_lower(extension) == ext))) {
list.push_back(file);
}
}
}
void directory_get_files(const std::string & dir, std::list<std::string> & files)
{
<API key>(dir, "", files);
}
bool directory_exists(const std::string & dir)
{
return Glib::file_test(dir, Glib::FILE_TEST_EXISTS) && Glib::file_test(dir, Glib::FILE_TEST_IS_DIR);
}
void directory_copy(const Glib::RefPtr<Gio::File> & src,
const Glib::RefPtr<Gio::File> & dest)
throw(Gio::Error)
{
if (false == dest->query_exists()
|| Gio::FILE_TYPE_DIRECTORY
!= dest->query_file_type(Gio::<API key>))
return;
if (Gio::FILE_TYPE_REGULAR
== src->query_file_type(Gio::<API key>)) {
src->copy(dest->get_child(src->get_basename()),
Gio::FILE_COPY_OVERWRITE);
}
else if (Gio::FILE_TYPE_DIRECTORY
== src->query_file_type(Gio::<API key>)) {
const Glib::RefPtr<Gio::File> dest_dir
= dest->get_child(src->get_basename());
if (false == dest_dir->query_exists())
dest_dir-><API key>();
Glib::Dir src_dir(src->get_path());
for (Glib::Dir::iterator it = src_dir.begin();
src_dir.end() != it; it++) {
const Glib::RefPtr<Gio::File> file = src->get_child(*it);
if (Gio::FILE_TYPE_DIRECTORY == file->query_file_type(
Gio::<API key>))
directory_copy(file, dest_dir);
else
file->copy(dest_dir->get_child(file->get_basename()),
Gio::FILE_COPY_OVERWRITE);
}
}
}
bool directory_create(const std::string & dir)
{
return Gio::File::create_for_path(dir)-><API key>();
}
} |
#!/bin/sh
# This file is part of WeeChat, the extensible chat client.
# WeeChat is free software; you can redistribute it and/or modify
# (at your option) any later version.
# WeeChat is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
common stuff
DIR=$(cd "$(dirname "$0")" || exit 1; pwd)
cd "$DIR" || exit 1
AUTOGEN_LOG=autogen.log
err ()
{
echo "
echo "Error :"
echo "
cat $AUTOGEN_LOG
echo "
exit 1
}
run ()
{
printf "Running \"%s\"..." "$@"
if eval "$@" >$AUTOGEN_LOG 2>&1 ; then
echo " OK"
else
echo " FAILED"
err
fi
}
# remove autotools stuff
run "rm -f config.h.in"
run "rm -f aclocal.m4 configure config.log config.status"
run "rm -rf autom4te*.cache"
# remove libtool stuff
run "rm -f libtool"
# remove gettext stuff
run "rm -f ABOUT-NLS"
run "rm -rf intl"
# execute autoreconf cmds
run "autoreconf -vi"
# ending
rm -f $AUTOGEN_LOG |
package mediathek.javafx;
import javafx.beans.property.IntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.StackPane;
/**
* Displays the number of currently selected entries
*/
public class SelectedItemsLabel extends StackPane {
public SelectedItemsLabel(IntegerProperty <API key>) {
super();
Label textLabel = new Label();
textLabel.setTooltip(new Tooltip("Ausgewählte Einträge der aktiven Tabelle"));
textLabel.textProperty().bind(<API key>.asString());
setMargin(textLabel,new Insets(0,4,0,4));
getChildren().add(textLabel);
}
} |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Mozzi: WaveShaper< int > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="<API key>.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Mozzi
 <span id="projectnumber">alpha 0.01.1m</span>
</div>
<div id="projectbrief">sound synthesis library for Arduino</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.8.0 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> </div>
<div class="headertitle">
<div class="title">WaveShaper< int > Class Template Reference</div> </div>
</div><!--header
<div class="contents">
<p>int specialisation of <a class="el" href="class_wave_shaper.html" title="WaveShaper maps values from its input to values in a table, which are returned as output...">WaveShaper</a> template
<a href="<API key>.html#details">More...</a></p>
<p><a href="<API key>.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">WaveShaper</a> (const int __attribute__((progmem))*TABLE_NAME)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Constructor. <a href="#<API key>"></a><br/></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">next</a> (int in)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Maps input to output, transforming it according to the table being used. <a href="#<API key>"></a><br/></td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><h3>template<><br/>
class WaveShaper< int ></h3>
<p>int specialisation of <a class="el" href="class_wave_shaper.html" title="WaveShaper maps values from its input to values in a table, which are returned as output...">WaveShaper</a> template </p>
<p>Definition at line <a class="el" href="<API key>.html#l00076">76</a> of file <a class="el" href="<API key>.html">WaveShaper.h</a>.</p>
</div><hr/><h2>Constructor & Destructor Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="class_wave_shaper.html">WaveShaper</a>< int >::<a class="el" href="class_wave_shaper.html">WaveShaper</a> </td>
<td>(</td>
<td class="paramtype">const int __attribute__((progmem))* </td>
<td class="paramname"><em>TABLE_NAME</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Constructor. </p>
<p>Use the template parameter to set type of numbers being mapped. For example, <a class="el" href="class_wave_shaper.html" title="WaveShaper maps values from its input to values in a table, which are returned as output...">WaveShaper</a> <int> myWaveShaper; makes a <a class="el" href="class_wave_shaper.html" title="WaveShaper maps values from its input to values in a table, which are returned as output...">WaveShaper</a> which uses ints. </p>
<dl class=""><dt><b>Template Parameters:</b></dt><dd>
<table class="">
<tr><td class="paramname">TABLE_NAME</td><td>the name of the table being used, which can be found in the ".h" file containing the table. </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="<API key>.html#l00084">84</a> of file <a class="el" href="<API key>.html">WaveShaper.h</a>.</p>
</div>
</div>
<hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="class_wave_shaper.html">WaveShaper</a>< int >::<a class="el" href="<API key>.html#<API key>">next</a> </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>in</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Maps input to output, transforming it according to the table being used. </p>
<dl class=""><dt><b>Template Parameters:</b></dt><dd>
<table class="">
<tr><td class="paramname">in</td><td>the input signal. For flexibility, it's up to you to give the correct offset to your input signal. So if you'r mapping a signed 9-bit signal (such as the sum of 2 8-bit Oscils) into a 512 cell table centred around cell 256, add 256 to offset the input value. With a sigmoid table, this may be useful for compressing a bigger signal into the -244 to 243 output range of Mozzi, rather than dividing the signal and returning a char from <a class="el" href="group__core.html#<API key>" title="This is where you put your audio code.">updateAudio()</a>. </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns:</dt><dd>the shaped signal. </dd></dl>
<p>Definition at line <a class="el" href="<API key>.html#l00101">101</a> of file <a class="el" href="<API key>.html">WaveShaper.h</a>.</p>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="<API key>.html">WaveShaper.h</a></li>
</ul>
</div><!-- contents -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Nov 9 2012 22:43:00 for Mozzi by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.0
</small></address>
</body>
</html> |
double* <API key> ( double a, double b, int n, int fnty);
double* <API key> ( double a, double b, int n, double c[], int m, double x[]);
double* chebyshev_zeros ( int n );
void updateSolution(int n, double a, double b, double* x); |
ceph pg dump --format json | json_pp | grep 'deep_scrub_stamp' | cut -c-50 | sort | uniq -c |
package net.lightbody.bmp.proxy.util;
import java.util.logging.*;
public class Log {
static {
Logger logger = Logger.getLogger("");
Handler[] handlers = logger.getHandlers();
for (Handler handler : handlers) {
logger.removeHandler(handler);
}
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new StandardFormatter());
handler.setLevel(Level.FINE);
logger.addHandler(handler);
}
static {
// tell commons-logging to use the JDK logging (otherwise it would default to log4j
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
}
protected Logger logger;
private String className;
public Log() {
Exception e = new Exception();
className = e.getStackTrace()[1].getClassName();
logger = Logger.getLogger(className);
}
public Log(Class clazz) {
className = clazz.getName();
logger = Logger.getLogger(className);
}
public void severe(String msg, Throwable e) {
log(Level.SEVERE, msg, e);
}
public void severe(String msg, Object... args) {
log(Level.SEVERE, msg, args);
}
public void severe(String msg, Throwable e, Object... args) {
log(Level.SEVERE, msg, e, args);
}
public RuntimeException severeAndRethrow(String msg, Throwable e, Object... args) {
log(Level.SEVERE, msg, e, args);
//noinspection <API key>
return new RuntimeException(new java.util.Formatter().format(msg, args).toString());
}
public void warn(String msg, Throwable e) {
log(Level.WARNING, msg, e);
}
public void warn(String msg, Object... args) {
log(Level.WARNING, msg, args);
}
public void warn(String msg, Throwable e, Object... args) {
log(Level.WARNING, msg, e, args);
}
public void info(String msg, Throwable e) {
log(Level.INFO, msg, e);
}
public void info(String msg, Object... args) {
log(Level.INFO, msg, args);
}
public void info(String msg, Throwable e, Object... args) {
log(Level.INFO, msg, e, args);
}
public void fine(String msg, Throwable e) {
log(Level.FINE, msg, e);
}
public void fine(String msg, Object... args) {
log(Level.FINE, msg, args);
}
public void fine(String msg, Throwable e, Object... args) {
log(Level.FINE, msg, e, args);
}
private void log(Level level, String msg, Throwable e) {
logger.log(level, msg, e);
}
private void log(Level level, String msg, Object... args) {
logger.log(level, msg, args);
}
private void log(Level level, String msg, Throwable e, Object... args) {
LogRecord lr = new LogRecord(level, msg);
lr.setThrown(e);
lr.setParameters(args);
lr.setSourceMethodName("");
lr.setSourceClassName(className);
lr.setLoggerName(className);
logger.log(lr);
}
} |
<script src="<?php echo STYLE_URL; ?>js/modules/l10n/phrases.js"></script> |
#ifndef <API key>
#define <API key>
#include <string>
namespace Color {
enum Color {
Unknown = ~0,
Default = -1,
Black = 0,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
Silver,
Gray,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
White
};
static Color Inverse(Color color) {
return (Color)(color + 16);
}
static Color Pure(Color color) {
return (Color)((int)color & 0xF);
}
static Color FromString(std::string color) {
if (color == "default") return Default;
if (color == "black") return Black;
if (color == "red") return Red;
if (color == "green") return Green;
if (color == "yellow") return Yellow;
if (color == "blue") return Blue;
if (color == "magenta") return Magenta;
if (color == "cyan") return Cyan;
if (color == "silver") return Silver;
if (color == "gray") return Gray;
if (color == "brightRed") return BrightRed;
if (color == "brightGreen") return BrightGreen;
if (color == "brightYellow") return BrightYellow;
if (color == "brightBlue") return BrightBlue;
if (color == "brightMagenta") return BrightMagenta;
if (color == "brightCyan") return BrightCyan;
if (color == "white") return White;
return Unknown;
}
}
#endif //<API key> |
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <ctype.h>
#include <getopt.h>
#include <fcntl.h>
#include <poll.h>
#include <pcap.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "shared.h"
#include "ipc.h"
#include "drone.h"
#include "database.h"
#include "main.h"
extern struct global_informations global;
/* constructor(s) */
void drone::initialize(void)
{
this->socket = 0;
bzero(&this->my_addr, sizeof(struct in_addr));
bzero(&this->my_stats, sizeof(struct ipc_sender_stats));
bzero(this->my_addr_str, MAX_DIRNAME_LEN);
bzero(this->drone_id, UUID_LEN);
this->my_port = 0;
this->my_type = 0;
this->my_pass = NULL;
this->debug = false;
this->local = false;
this->scan_pps = 0;
this->scan_sport = 0;
this->scan_secret = 0;
this->scan_timeout = 0;
this->scan_retry = 1;
this->scan_tcpops = 0;
this->port_workunit.clear();
this->target_workunit.clear();
}
drone::drone()
{
this->initialize();
return;
}
drone::drone(uint32_t addr)
{
this->initialize();
this->my_addr.s_addr = addr;
return;
}
drone::drone(uint32_t addr, uint16_t port)
{
this->initialize();
this->my_addr.s_addr = addr;
this->my_port = port;
if (!port) {
this->local = true;
snprintf(this->my_addr_str, MAX_DIRNAME_LEN - 1, "%s", addr == IDENT_LISTENER ? <API key> : SOCKET_PATH_SENDER);
} else {
snprintf(this->my_addr_str, MAX_DIRNAME_LEN - 1, "%s", inet_ntoa(this->my_addr));
}
return;
}
drone::drone(uint32_t addr, uint16_t port, char *pass)
{
this->initialize();
this->my_addr.s_addr = addr;
this->my_port = port;
if (!port) {
this->local = true;
snprintf(this->my_addr_str, MAX_DIRNAME_LEN - 1, "%s", addr == IDENT_LISTENER ? <API key> : SOCKET_PATH_SENDER);
} else {
snprintf(this->my_addr_str, MAX_DIRNAME_LEN - 1, "%s", inet_ntoa(this->my_addr));
}
this->my_pass = strdup(pass);
return;
}
/* destructor */
drone::~drone()
{
return;
}
/* add a new host workunit to the drone (struct targets) */
void drone::add_host_workunit(struct targets *tt)
{
this->target_workunit.push_back(*tt);
return;
}
/* add a new port workunit to the drone (struct ports) */
void drone::add_port_workunit(struct ports *pp)
{
this->port_workunit.push_back(*pp);
return;
}
void drone::add_redist_workunit(struct targets *tt)
{
this->redist_workunit.push_back(*tt);
return;
}
/* ipc connect to drone */
uint32_t drone::connect(void)
{
if (this->local) this->socket = connect_ipc_socket(this->my_addr.s_addr == IDENT_LISTENER ? strdup(<API key>) : strdup(SOCKET_PATH_SENDER), this->my_port);
else this->socket = connect_ipc_socket(inet_ntoa(this->my_addr), this->my_port);
if (this->socket == 0) {
return 0;
} else {
/* nonblocking sockets are used */
unblock_socket(this->socket);
}
return this->socket;
}
/* CRAM-MD5 authentication */
uint32_t drone::authenticate(void)
{
char *digest;
char *msg;
char *challenge;
char *auth_str;
struct ipc_message *ipc_m;
bool save_cred = false;
ipc_send_helo(this->socket);
if (get_ipc_message(this->socket, &msg) == 0) {
return 0;
}
ipc_m = (struct ipc_message *) msg;
if (ipc_m->msg_type != MSG_CHALLENGE) {
return 0;
}
/* get uuid */
memcpy(this->drone_id, msg + sizeof(struct ipc_message), UUID_LEN);
char uuid_str[UUID_STR_LEN], *p;
int i;
for (i=0, p = uuid_str; i < UUID_LEN; i++, p += 2) {
sprintf(p, "%02x", this->drone_id[i]);
}
MSG(MSG_DBG, "[uuid] %s\n", uuid_str);
/* get drone challenge */
challenge = strndup(msg + sizeof(struct ipc_message) + UUID_LEN, ipc_m->msg_len - (sizeof(struct ipc_message) + UUID_LEN));
MSG(MSG_DBG, "[auth] got challenge: %s\n", challenge);
if (!this->local) {
/* check for drone credentials in database */
char **drone_credentials;
if (drone_credentials = <API key>(this->drone_id)) {
this->my_user = drone_credentials[0];
this->my_pass = drone_credentials[1];
} else {
/* get username and password from stdin */
this->my_user = (char *) safe_zalloc (MAX_USERNAME_LEN + 1);
this->my_pass = (char *) safe_zalloc (MAX_PASSWORD_LEN + 1);
fprintf(stderr, "[*] Username for drone %s:%d (max. %d characters) : ", this->my_addr_str, this->my_port, MAX_USERNAME_LEN);
fgets(this->my_user, MAX_USERNAME_LEN, stdin);
/* remove newline */
if(this->my_user[strlen(this->my_user) - 1] == '\n')
this->my_user[strlen(this->my_user) - 1] = 0;
fprintf(stderr, "[*] Password for drone %s:%d (max. %d characters) :", this->my_addr_str, this->my_port, MAX_PASSWORD_LEN);
strncpy(this->my_pass, getpass(" "), MAX_PASSWORD_LEN);
save_cred = true;
}
/* generate HMAC-MD5 digest */
digest = generate_digest(challenge, strlen(challenge), this->my_pass, strlen(this->my_pass));
auth_str = (char *)safe_zalloc (strlen(digest) + strlen(this->my_user) + 2);
sprintf(auth_str, "%s %s", this->my_user, digest);
} else {
/* generate HMAC-MD5 digest */
digest = generate_digest(challenge, strlen(challenge), this->my_pass, strlen(this->my_pass));
auth_str = (char *)safe_zalloc(strlen(digest) + strlen(DEFAULT_USER) + 2);
sprintf(auth_str, "%s %s", DEFAULT_USER, digest);
}
ipc_send_auth(this->socket, auth_str);
if (get_ipc_message(this->socket, &msg) == 0) {
return 0;
}
ipc_m = (struct ipc_message *) msg;
if (ipc_m->msg_type != MSG_READY) {
return 0;
}
/* write informations into database */
if (save_cred)
<API key> (this->drone_id, this->my_user, this->my_pass);
return 1;
}
/* initialise drone and check drone type */
uint32_t drone::init(void)
{
char *msg;
struct ipc_message *ipc_m;
<API key>(this->socket);
if (get_ipc_message(this->socket, &msg) == 0) {
return 0;
}
ipc_m = (struct ipc_message *) msg;
if (ipc_m->msg_type != MSG_IDENT_REPLY) {
return 0;
}
this->my_type = (uint8_t) *(msg + sizeof(struct ipc_message));
MSG(MSG_DBG, "drone type: %d\n", this->my_type);
if (this->my_type == IDENT_LISTENER) {
msg += + sizeof(struct ipc_message) + 1;
this->listener_addr = *((uint32_t *)msg);
return IDENT_LISTENER;
} else if (this->my_type == IDENT_SENDER) {
return IDENT_SENDER;
} else { /* WTF? */
return 0;
}
return 0;
}
/* start drone */
uint32_t drone::start(void)
{
char *msg;
struct ipc_message *ipc_m;
ipc_send_start(this->socket);
if (get_ipc_message(this->socket, &msg) == 0) {
return 0;
}
ipc_m = (struct ipc_message *) msg;
switch(ipc_m->msg_type) {
case MSG_BUSY:
/* store drone in database */
db_add_drone(this->my_addr.s_addr, this->my_port, this->my_type);
MSG(MSG_DBG, "[ipc in] BUSY (drone is working)\n");
break;
case MSG_ERROR:
this->print_error(msg);
return 0;
break;
default:
return 0;
break;
}
return 1;
}
/* stop drone */
uint32_t drone::stop(void)
{
/* FIXME */
return 0;
}
/* print IPC error message */
void drone::print_error(char *msg)
{
printf("*** [drone error: '%s' from %s:%d ] ***\n", (msg + sizeof(struct ipc_message)),this->my_addr_str, this->my_port);
return;
}
uint32_t drone::send_workload(void)
{
char *payload;
char *p;
char *msg = NULL; /* IPC Response Message */
struct ipc_message *ipc_m;
struct ipc_sendunit *ipc_s;
struct ipc_listenunit *ipc_l;
struct ports *pp;
struct targets *tt;
uint32_t port_data_len=0;
uint32_t ip_data_len=0;
uint32_t payload_size=0;
uint32_t r_msg_len=0;
/*** create workunit (LISTENER) ***/
if (this->my_type == IDENT_LISTENER) {
payload_size=sizeof(struct ipc_message) + sizeof(struct ipc_listenunit);
payload = (char *)malloc(payload_size);
p = payload;
/* Message Header */
ipc_m = (struct ipc_message *) p;
ipc_m->msg_type = MSG_WORKUNIT;
ipc_m->msg_len = payload_size;
p += sizeof(struct ipc_message);
/* Listenunit Header */
ipc_l = (struct ipc_listenunit *) p;
ipc_l->sport=this->scan_sport;
ipc_l->secret = this->scan_secret;
ipc_l->timeout=this->scan_timeout;
/*** create workunit (SENDER) ***/
} else if (this->my_type == IDENT_SENDER) {
ip_data_len = this->target_workunit.size();
port_data_len = this->port_workunit.size();
payload_size=sizeof(struct ipc_message) + sizeof(struct ipc_sendunit) + (sizeof(struct ports) * port_data_len) + (sizeof(struct targets) * ip_data_len);
payload = (char *)malloc(payload_size);
p = payload;
/* Message Header */
ipc_m = (struct ipc_message *) p;
ipc_m->msg_type = MSG_WORKUNIT;
ipc_m->msg_len = payload_size;
p += sizeof(struct ipc_message);
/* Sendunit Header */
ipc_s = (struct ipc_sendunit *) p;
ipc_s->pps = this->scan_pps;
ipc_s->secret = this->scan_secret;
ipc_s->listener_addr = this->listener_addr;
ipc_s->port_data_len = port_data_len;
ipc_s->ip_data_len = ip_data_len;
ipc_s->sport = this->scan_sport;
ipc_s->retry = this->scan_retry;
ipc_s->tcpops = this->scan_tcpops;
p += sizeof(struct ipc_sendunit);
/* Get Targets for this drone */
p += this-><API key>(p);
/* Get Ports for this drone */
p += this->create_port_payload(p);
} else {
return 0; /* Failed */
}
/* send workunit to drone */
MSG(MSG_DBG, "[ipc out] WORKUNIT\n");
send_ipc_msg(this->socket, payload, ipc_m->msg_len);
free(payload);
/* check ipc response */
r_msg_len = get_ipc_message(this->socket, &msg);
if (r_msg_len > 0) {
ipc_m = (struct ipc_message *) msg;
switch(ipc_m->msg_type) {
case MSG_READY:
MSG(MSG_DBG, "[ipc in] READY\n");
return r_msg_len;
break;
case MSG_ERROR:
this->print_error(msg);
return 0;
break;
default:
MSG(MSG_DBG, "[drone] invalid response\n");
return 0;
break;
}
} else {
MSG(MSG_DBG, "[drone] can not read response from drone\n");
return 0; /* Failed */
}
return 0;
}
/*
* used for re-distributing targets to drones during scan
*/
uint32_t drone::send_new_workload(void)
{
char *payload;
char *p;
char *msg = NULL; /* IPC Response Message */
struct ipc_message *ipc_m;
struct ipc_sendunit *ipc_s;
struct targets *tt;
uint32_t port_data_len=0;
uint32_t ip_data_len=0;
uint32_t payload_size=0;
uint32_t r_msg_len=0;
uint32_t target_num = 0;
if (this->my_type == IDENT_SENDER) {
ip_data_len = this->redist_workunit.size();
port_data_len = 0;
payload_size=sizeof(struct ipc_message) + sizeof(struct ipc_sendunit) + (sizeof(struct ports) * port_data_len) + (sizeof(struct targets) * ip_data_len);
payload = (char *)malloc(payload_size);
p = payload;
/* Message Header */
ipc_m = (struct ipc_message *) p;
ipc_m->msg_type = MSG_WORKUNIT;
ipc_m->msg_len = payload_size;
p += sizeof(struct ipc_message);
/* Sendunit Header */
ipc_s = (struct ipc_sendunit *) p;
ipc_s->pps = this->scan_pps;
ipc_s->secret = this->scan_secret;
ipc_s->listener_addr = this->listener_addr;
ipc_s->port_data_len = port_data_len;
ipc_s->ip_data_len = ip_data_len;
ipc_s->sport = this->scan_sport;
ipc_s->retry = this->scan_retry;
ipc_s->tcpops = this->scan_tcpops;
p += sizeof(struct ipc_sendunit);
/* Get Targets for this drone */
for (target_num=0; target_num < this->redist_workunit.size(); target_num++) {
tt = (struct targets *)p;
tt->ipaddr = this->redist_workunit[target_num].ipaddr;
tt->range = this->redist_workunit[target_num].range;
p += sizeof(struct targets);
}
} else {
return 0; /* Failed */
}
/*
* send new workunits to sender drones. they will add them to their existing
* workunits on the fly (realy cool, isn't it?)
*/
MSG(MSG_DBG, "[ipc out] WORKUNIT\n");
send_ipc_msg(this->socket, payload, ipc_m->msg_len);
free(payload);
/* check ipc response */
r_msg_len = get_ipc_message(this->socket, &msg);
if (r_msg_len > 0) {
ipc_m = (struct ipc_message *) msg;
switch(ipc_m->msg_type) {
case MSG_READY:
MSG(MSG_DBG, "[ipc in] READY\n");
return r_msg_len;
break;
case MSG_ERROR:
this->print_error(msg);
return 0;
break;
default:
MSG(MSG_DBG, "[drone] invalid response\n");
return 0;
break;
}
} else {
MSG(MSG_DBG, "[drone] can not read response from drone\n");
return 0; /* Failed */
}
return 0;
}
/*
* create a target payload for the sender workunit
* the data is put to the *payload address
* the bytes added to the workunit are returned
*/
uint32_t drone::<API key>(char *payload)
{
uint32_t i, ret_bytes = 0;
char *p = payload;
struct targets *tt;
struct in_addr start_addr, end_addr;
char ipaddr_start[16];
char ipaddr_end[16];
for (i=0; i<this->target_workunit.size(); i++) {
start_addr.s_addr = this->target_workunit[i].ipaddr;
end_addr.s_addr = htonl(ntohl(this->target_workunit[i].ipaddr) + this->target_workunit[i].range - 1);
/* convert IP addresses to strings */
inet_ntop(AF_INET, &start_addr, ipaddr_start, 16);
inet_ntop(AF_INET, &end_addr, ipaddr_end, 16);
MSG(MSG_DBG, "[workload] [hosts] (drone: %s:%d) [%d] -> from: %s to: %s\n", this->my_addr_str, this->my_port, i+1, ipaddr_start, ipaddr_end);
tt = (struct targets *)p;
tt->ipaddr = this->target_workunit[i].ipaddr;
tt->range = this->target_workunit[i].range;
p += sizeof(struct targets);
ret_bytes += sizeof(struct targets);
}
return ret_bytes;
}
/*
* create a port payload for the sender workunit
* the data is put to the *payload address
* the bytes added to the workunit are returned
*/
uint32_t drone::create_port_payload(char *payload)
{
uint32_t i, ret_bytes = 0;
char *p;
struct ports *pp;
p = payload;
for (i=0; i<this->port_workunit.size(); i++) {
pp = (struct ports *)p;
pp->port = this->port_workunit[i].port;
pp->range = this->port_workunit[i].range;
MSG(MSG_DBG, "[workload] [ports] (drone: %s:%d) [%d] -> from: %d to %d\n",this->my_addr_str, this->my_port, i + 1, pp->port, pp->port + (pp->range));
p += sizeof(struct ports);
ret_bytes += sizeof(struct ports);
}
return ret_bytes;
}
/* constructor */
drone_list::drone_list()
{
this->dl.clear();
this->num_listen_drones = 0;
this->num_send_drones = 0;
this->debug = false;
this->verb = false;
this->local = false;
this->scan_pps = 0;
this->scan_sport = 0;
this->scan_timeout = 0;
this->scan_retry = 1;
this->scan_tcpops = 0;
this->scan_cmd_line = NULL;
/* Zufallsgenerator initialisieren */
srand(time(NULL));
this->scan_secret = get_rnd_uint32();
return;
}
/* destructor */
drone_list::~drone_list()
{
return;
}
/* add drone to list */
uint32_t drone_list::add_drone(uint32_t addr, uint16_t port, char *pass)
{
drone tmpdrone(addr, port, pass);
dl.push_back(tmpdrone);
return 0;
}
/* add host expresseion to target list */
uint32_t drone_list::add_hostexp (char *hostexp)
{
char *target_net = NULL;
char addr_buff[16];
char *buffer = strdup(hostexp);
char *s = NULL;
char *endptr;
char *p;
static struct targets *target = this->target_buffer;
struct in_addr startaddr, endaddr, tmpaddr;
struct hostent *t;
uint32_t i, x, y, z;
uint32_t suffix = 0;
uint32_t netmask = 0;
uint32_t dots = 0;
uint32_t range_start = 0;
uint32_t range_end = 0;
uint32_t ip_count = 0;
in_addr_t ip_address;
target_buffer_count = 0; // set target buffer count to zero
vector <struct s_range> range[4];
struct s_range tmprange;
p = buffer;
if(is_ip(hostexp)) { /* ist es eine einzelne ip? */
if(!(inet_aton(hostexp, &tmpaddr))) {
MSG(MSG_ERR, "invalid target ip: %s\n", hostexp);
return 0;
} else {
target->ipaddr = tmpaddr.s_addr;
target->range = 1;
target++;
this->target_buffer_count++;
this->total_ip_count++;
}
} else if (is_ip_cidr (hostexp)) { /* ist es eine CIDR notation? */
target_net = strtok(buffer, "/");
s = strtok(NULL, ""); /* find the end of the token from hostexp */
suffix = ( s ) ? atoi(s) : 32;
if (suffix < 0 || suffix > 32) {
MSG(MSG_ERR, "Illegal netmask value (%d), must be /0 - /32 . Assuming /32 (one host)", suffix);
suffix = 32;
}
if (suffix) {
ip_address = inet_addr(target_net);
// check for invalid IP addresses due to invalid input
if ((ip_address == 0x0) || (ip_address == 0xffffffff)) {
MSG(MSG_ERR, "invalid ip addr: %s\n", target_net);
return 0;
}
ip_count = (1 << (32 - suffix)) - 2;
netmask = ((1 << suffix) - 1) << (32 - suffix);
ip_address = htonl(ntohl(ip_address) & netmask);
target->ipaddr = htonl(ntohl(ip_address) + 1);
target->range = ip_count;
target++;
this->target_buffer_count++;
this->total_ip_count += ip_count;
} else {
fatal("error while processing target expression: %s", hostexp);
}
} else if (is_ip_range (hostexp)) { /* ist es ein ip-range? */
do {
if (*p == '.') {
if (dots > 3) { MSG(MSG_ERR, "Invalid Target expression: %s\n", hostexp); }
tmprange.start = range_start;
tmprange.end = range_end ? range_end : range_start;
range[dots].push_back(tmprange);
range_end = 0;
range_start = 0;
dots++;
p++;
}
if (*p == '-') {
if (!range_start) { MSG(MSG_ERR, "Invalid IP Range: %s\n", hostexp); }
p++;
}
if (*p == ',') {
tmprange.start = range_start;
tmprange.end = range_end ? range_end : range_start;
range[dots].push_back(tmprange);
range_end = 0;
range_start = 0;
p++;
}
if (isdigit((int) *p)) {
if (!range_start) range_start = strtol(p, &endptr, 10);
else if (!range_end) range_end = strtol(p, &endptr, 10);
else { MSG(MSG_ERR, "Invalid Range Spec\n"); }
p=endptr;
}
if (*p == '\0') {
if (dots==3) {
tmprange.start = range_start;
tmprange.end = range_end ? range_end : range_start;
range[dots].push_back(tmprange);
} else {
MSG(MSG_ERR, "Invalid IP Range: %s\n", hostexp);
}
}
} while (*p);
int a,b,c,d;
for (i=0; i < range[0].size(); i++) {
for (x=0; x < range[1].size(); x++) {
for (y=0; y < range[2].size(); y++) {
for (z=0; z < range[3].size(); z++) {
for (a=range[0][i].start; a <= range[0][i].end; a++) {
for (b=range[1][x].start; b <= range[1][x].end; b++) {
for (c=range[2][y].start; c <= range[2][y].end; c++) {
/* create ip range for workunit */
snprintf(addr_buff, sizeof(addr_buff), "%d.%d.%d.%d\n",a, b, c, range[3][z].start);
target->ipaddr = (uint32_t) inet_addr(addr_buff);
target->range = (uint32_t) (range[3][z].end - range[3][z].start) + 1;
this->target_buffer_count++;
this->total_ip_count += target->range;
target++;
}
}
}
}
}
}
}
} else { /* dann muss es wohl ein hostname sein */
if ((t = gethostbyname(hostexp))) {
uint16_t count=0;
memcpy(&(tmpaddr), t->h_addr_list[0], sizeof(struct in_addr));
while (t->h_addr_list[count]) count++;
if (count > 1) {
MSG(MSG_WARN, "Warning: Hostname %s resolves to %d IPs. Using %s.\n", hostexp, count, inet_ntoa(*((struct in_addr *)t->h_addr_list[0])));
}
target->ipaddr = tmpaddr.s_addr;
target->range = 1;
target++;
this->total_ip_count += target->range;target_buffer_count++;
this->total_ip_count += target->range;total_ip_count++;
} else {
MSG(MSG_ERR, "can't resolve hostname: %s\n", hostexp);
return 0;
}
}
return this->total_ip_count;
}
/* add portstring to portlist */
uint32_t drone_list::add_portstr(char *portstr)
{
char *s = strdup(portstr); // work string
char *p; // general purpose pointer
char *token; // token
struct ports *port; // pointer to port buffer
uint16_t port_number, port_number2; // IP ports
uint16_t range; // port range
uint32_t i, pass; // various counters
port = this->port_buffer; // set port pointer to global port buffer
this->port_buffer_count = 0; // set port buffer count to zero
this->total_port_count = 0; // set IP port counter to zero
// tokenize the target string
i = 0;
pass = 0;
while (i < MAX_PORTS) { // parse until port max. is reached or nothing more to parse
pass++; // increment pass counter
// split target string in comma-separated tokens
if (1 == pass)
token = strtok(s, ","); // call this on first pass
else
token = strtok(NULL, ","); // call this on all other passes
if (token == NULL) // no more tokens?
break; // so we are done
// is the port input a range?
p = strchr(token, '-');
if (p != NULL) {
*p = '\0'; // set terminating zero
// convert strings to integers
port_number = atoi(token);
port_number2 = atoi(p + 1);
// check for invalid IP ports due to invalid input
if ((port_number == 0) || (port_number2 == 0))
return 0;
// if the range is not well-formatted, return
if (port_number > port_number2)
return 0; // return zero IP ports
range = port_number2 - port_number; // calculate port range
this->total_port_count += port_number2 - port_number + 1; // increment total IP port counter
// save target information in global target buffer
port->port = port_number; // save start IP port in host byte order
port->range = range; // set port range
port++; // point to next element in port buffer
this->port_buffer_count++; // increment port buffer count
} else {
// convert token to IP port
port_number = atoi(token); // convert token to IP port
// check for invalid IP port due to invalid input
if (port_number == 0)
return 0;
this->total_port_count++; // increment total IP port counter
// save target information in global target buffer
port->port = port_number; // save startIP port in host byte order
port->range = 0; // set count to 1 for a single port
port++; // point to next element in port buffer
this->port_buffer_count++; // increment port buffer count
}
i++;
}
free(s);
return this->total_port_count;
}
/* connect to all drones */
uint32_t drone_list::connect(void)
{
uint32_t i = 0;
for (i=0; i < this->dl.size(); i++) {
if (this->debug) dl[i].set_debug();
/* try to connect to drone */
if(!this->dl[i].connect()) this->remove_drone (i--, "connection refused");
}
/* drone check */
if (this->dl.size() >= 2) return this->dl.size();
else return 0;
}
/* authenticate with all drones */
uint32_t drone_list::authenticate(void)
{
uint32_t i = 0;
uint32_t drone_type = 0;
struct in_addr addr;
for (i=0; i < this->dl.size(); i++) {
/* try to authenticate with drones*/
if (!this->dl[i].authenticate()) {
this->remove_drone (i--, "authentication failed");
continue;
}
/* try to get drone type */
drone_type = this->dl[i].init();
/* we got a sender drone here */
if (drone_type == IDENT_SENDER) {
this->num_send_drones++;
dl[i].set_pps(this->scan_pps);
dl[i].set_secret(this->scan_secret);
dl[i].set_sport(this->scan_sport);
dl[i].set_retry(this->scan_retry);
dl[i].set_tcpops(this->scan_tcpops);
}
/* this one is a listener drone */
else if (drone_type == IDENT_LISTENER) {
this->num_listen_drones++;
dl[i].set_timeout(this->scan_timeout);
dl[i].set_secret(this->scan_secret);
dl[i].set_sport(this->scan_sport);
this->listener_sock = dl[i].get_socket();
this->listener_addr = dl[i].get_listener_addr();
if (this->debug) {
addr.s_addr = this->listener_addr;
MSG(MSG_DBG, "got listener address: %s\n", inet_ntoa(addr));
}
}
else {
this->remove_drone(i--, "unknown drone type returned");
}
}
/* set listener_addr for all sender drones */
for (i=0; i < this->dl.size(); i++) {
if (dl[i].get_type() == IDENT_SENDER) dl[i].set_listener_addr(this->listener_addr);
}
/* drone check */
if (this->num_send_drones && this->num_listen_drones) return this->dl.size();
else return 0;
}
/* distrubite workunits to all drones */
uint32_t drone_list::<API key>(void)
{
uint32_t i = 0;
uint32_t target_num = 0;
uint32_t port_num = 0;
uint32_t sender_idx = 0;
struct targets tt;
struct ports pp;
/* loadbalancing */
this->balance_workunit();
for (i=0; i < dl.size(); i++) {
if (dl[i].get_type() == IDENT_LISTENER) {
dl[i].send_workload();
continue; /* skip listener drones, they need no host based workunits */
}
for (target_num=0; target_num < this-><API key>[sender_idx]; target_num++) {
tt.ipaddr = target_buffer[this->drone_distribution[sender_idx][target_num]].ipaddr;
tt.range = target_buffer[this->drone_distribution[sender_idx][target_num]].range;
/* add host workload to drone */
dl[i].add_host_workunit (&tt);
}
for (port_num=0; port_num < this->port_buffer_count; port_num++) {
pp.port = port_buffer[port_num].port;
pp.range = port_buffer[port_num].range;
/* add port workload to drone */
dl[i].add_port_workunit (&pp);
}
/* send workload to sender drones */
dl[i].send_workload();
sender_idx++;
}
return 0;
}
/* start all drones (listener first) */
uint32_t drone_list::start_scan(void)
{
uint32_t i = 0;
/* start listener drones first */
for (i=0; i < dl.size(); i++) {
if (dl[i].get_type() == IDENT_LISTENER) dl[i].start();
}
/* then start sender drones */
for (i=0; i < dl.size(); i++) {
if (dl[i].get_type() == IDENT_SENDER) dl[i].start();
}
return 0;
}
/* stop scan for all drones */
uint32_t drone_list::stop_scan(void)
{
uint32_t i = 0;
/* Noooooooooooo!! */
for (i=0; i < dl.size(); i++) {
dl[i].stop();
}
return 0;
}
/*
* the drones are working, so now we check for incoming messages from them until they finish.
* or get killed by a segmentation fault... *douh*
*/
uint32_t drone_list::poll_drones(void)
{
uint32_t bytes;
uint32_t i;
uint32_t msg_len = 0;
struct ipc_message *ipc_m;
struct pollfd *pfd;
char buff[MAX_MSG_LEN];
char *msg = NULL;
pfd = (struct pollfd *) safe_zalloc(this->dl.size() * sizeof(struct pollfd));
while(true) {
for (i=0; i < this->dl.size(); i++) {
pfd[i].fd=this->dl[i].get_socket();
pfd[i].events=POLLIN|POLLPRI;
}
if (poll(pfd, this->dl.size(), 10) < 0) {
printf("[warn] poll fails: %s", strerror(errno));
}
for (i=0; i < this->dl.size(); i++) {
if (pfd[i].revents & POLLIN) { /* received something */
msg_len = get_ipc_message(this->dl[i].get_socket(), &msg);
if (msg_len > 0) {
ipc_m = (struct ipc_message *) msg;
switch (ipc_m->msg_type) {
case MSG_ERROR: /* Oh no, something went wrong. blame someone! */
this->dl[i].print_error(msg);
this->handle_dead_drone(i);
break;
case MSG_WORKDONE: /* drone finished the work. well done, get a cookie */
MSG(MSG_DBG, "[ipc in] workdone from: %s:%d\n", this->dl[i].get_addr_str(), this->dl[i].get_port());
if (this->dl[i].get_type() == IDENT_SENDER) {
/* Close socket and remove drone */
this->remove_drone (i, NULL);
MSG(MSG_DBG, "[drone] sender drone finished [%d drones left]\n", this->num_send_drones);
if(this->num_send_drones == 0) {
MSG(MSG_DBG, "all senders finished. telling listener to stop (%d seconds timeout) \n", this->scan_timeout);
ipc_send_quit(this->get_listener_sock());
}
} else if (this->dl[i].get_type() == IDENT_LISTENER) {
MSG(MSG_DBG, "listener finished. Print results\n");
/* return to main() */
return 0;
} else {
printf("[wtf] holy shit! Error in MSG_WORKDONE processing\n");
}
break;
case MSG_PORTSTATE: /* open port found */
this->set_portstate((char *)ipc_m);
break;
case MSG_SENDER_STATS: /* sender statistics */
this->statistics((char *)ipc_m, i);
break;
default:
printf("[wtf] what the... invalid ipc message recveived. ignoring.\n");
break;
}
} else if (msg_len == 0) {
/* connection lost */
MSG(MSG_WARN, "connection lost to drone %s:%d\n", this->dl[i].get_addr_str(), this->dl[i].get_port());
this->handle_dead_drone(i);
} else {
MSG(MSG_WARN, "invalid message from drone, ignoring\n");
}
}
}
}
}
/*
* remove drone form list and set some counters
*/
void drone_list::remove_drone(uint32_t index, const char *msg)
{
if (msg) {
MSG(MSG_WARN, "%s - removing drone from list (%s:%d).\n", msg, this->dl[index].get_addr_str(), this->dl[index].get_port ());
}
if (this->dl[index].get_type() == IDENT_LISTENER) {
if (msg) MSG(MSG_ERR, "listener drone had an error. Aborting.");
} else if (this->dl[index].get_type() == IDENT_SENDER) {
this->num_send_drones
}
/* close socket */
if (this->dl[index].get_socket()) close(this->dl[index].get_socket());
this->dl.erase(this->dl.begin() + index);
return;
}
/*
* parse drone string and add drones to drone() vector
*/
void drone_list::add_dronestr(char *drone_str)
{
char *p = strdup(drone_str);
char *q = p;
char ip_buff[MAX_IP_STR_LEN + 1];
char port_buff[MAX_PORT_STR_LEN + 1];
bool is_ip=false, is_port=false;
this->num_listen_drones = 0;
this->num_send_drones = 0;
is_ip=true;
do {
if (*p == ':') {
if (is_ip) {
bzero(ip_buff, MAX_IP_STR_LEN + 1);
strncpy(ip_buff, q, (((p-q) > MAX_IP_STR_LEN) ? MAX_IP_STR_LEN : p-q));
q = p + 1;
is_port = true;
is_ip = false;
} else {
MSG(MSG_ERR, "invalid drone string: %s\n", drone_str);
exit(0);
}
} else if (*p == ',' || *p == '\0') {
if (is_port) {
bzero(port_buff, MAX_PORT_STR_LEN + 1);
strncpy(port_buff, q, (((p-q) > MAX_PORT_STR_LEN) ? MAX_PORT_STR_LEN : p-q));
is_port = false;
is_ip = true;
q = p + 1;
this->add_drone(host2long(ip_buff), atoi(port_buff), strdup(DEFAULT_PASS));
} else {
MSG(MSG_ERR, "invalid drone string: %s\n", drone_str);
exit(0);
}
}
} while(*(p++) != '\0');
return;
}
/*
* round-robin loadbalancing. distributes the targets to the sender drones (very cool)
*/
void drone_list::balance_workunit(void)
{
char *payload;
char *p;
struct ports *pp;
struct targets *tt;
uint32_t i=0;
uint32_t port_data_len=0;
uint32_t ip_data_len=0;
uint32_t payload_size=0;
uint32_t r_msg_len=0;
uint32_t current_drone=0;
/* Target distribution */
uint16_t sender_count = 0;
uint32_t ipaddr_per_sender = 0;
uint32_t target_number = 0;
uint32_t ipaddr_sender_count = 0;
uint32_t remaining = 0;
/* number of available drones */
sender_count = this->num_send_drones;
/* no targets? not good... */
if (!this->total_ip_count) { MSG(MSG_ERR, "error in target string\n"); }
/* more drones than targets ? */
if (this->total_ip_count < sender_count) {
MSG(MSG_WARN, "got %d targets for %d sender drones. Removing %d sender drones from list.\n", this->total_ip_count, sender_count, sender_count - this->total_ip_count);
/* remove unused drones from drone list */
i = 0;
do {
if (this->dl[i].get_type() == IDENT_SENDER) {
this->remove_drone (i, "more drones than targets");
i
}
i++;
} while (this->num_send_drones > this->total_ip_count || i > this->dl.size());
sender_count = this->num_send_drones;
}
rearrange_targets(this->total_ip_count, sender_count);
/* Generate Load-Balancing Array */
ipaddr_per_sender = this->total_ip_count / sender_count;
//fprintf(stderr, "ipaddr_per_sender (%d) = total_target_count(%d) / sender_count(%d)\n", ipaddr_per_sender, total_ip_count, sender_count);
tt = this->target_buffer;
target_number = 0;
for (i = 0; i < sender_count; i++) {
ipaddr_sender_count = 0;
this-><API key>[i] = 0;
while (ipaddr_sender_count < ipaddr_per_sender) {
//fprintf(stderr, "debug: drone_distribution[%d][(<API key>[%d]) = %d] = %d\n",i,i,<API key>[i],target_number);
this->drone_distribution[i][this-><API key>[i]] = target_number;
this-><API key>[i]++;
ipaddr_sender_count += tt->range;
//fprintf(stderr, "ipaddr_sender_count (%d) += tt->range(%d)(@%p)\n", ipaddr_sender_count, tt->range, tt);
tt++;
target_number++;
}
}
/* distribute remaining targets round-robin */
while (target_number < target_buffer_count) {
remaining = (i + 1) % sender_count;
this->drone_distribution[remaining][this-><API key>[remaining]]=target_number;
this-><API key>[remaining]++;
target_number++;
i++;
}
}
/*
* rearrange_targets
*/
void drone_list::rearrange_targets(uint32_t ipaddr_count, uint32_t sender_count) {
struct targets local_target_buffer[MAX_TARGETS]; // local target buffer
uint32_t target_count; // counter for local target buffer
struct targets *t_global, *t_local; // pointers to target buffers
struct targets target; // target
uint32_t ipaddr_per_sender, ipaddr_remainder, delta; // calculation stuff
uint32_t i,ip_count_sender; // various counters
// calculate number of IP addresses per sender
ipaddr_per_sender = ipaddr_count / sender_count;
ipaddr_remainder = ipaddr_count % sender_count;
t_global = target_buffer; // set pointer to global target buffer
t_local = local_target_buffer; // set pointer to local target buffer
target_count = 0; // set local target buffer count to zero
i = 0; // index for global target buffer
// process all targets in global target buffer
while (i < sender_count) {
ip_count_sender = 0; // set IP address count for sender to zero
while (ip_count_sender < ipaddr_per_sender) {
// is target a single host or an IP address range?
if (t_global->range == 1) {
// single host
// add single host to local target buffer
t_local->ipaddr = t_global->ipaddr; // save IP address
t_local->range = t_global->range; // save range (in this case 0)
t_local++; // point to next element in local target buffer
ip_count_sender++; // increment IP address count of sender
target_count++; // increment target counter
} else {
// IP address range
// calculate number of IP addresses to complete a sender
delta = ipaddr_per_sender - ip_count_sender;
if (t_global->range <= delta) {
// number of targets fits in current sender
// so add IP address range to local target buffer
t_local->ipaddr = t_global->ipaddr; // save IP address
t_local->range = t_global->range; // save range (in this case 0)
t_local++; // point to next element in local target buffer
ip_count_sender += t_global->range; // increment IP address count of sender
target_count++; // increment target counter
} else {
// IP address range has to be splitted
// so split it in two ranges
target.ipaddr = t_global->ipaddr; // save global target IP address
target.range = t_global->range; // save global target range
// add first IP address range to local target buffer
t_local->ipaddr = t_global->ipaddr; // save IP address
t_local->range = delta; // save range (in this case the calculated delta)
t_local++; // point to next element in local target buffer
ip_count_sender += delta; // increment IP address count of sender
target_count++; // increment target counter
// in-memory replacement of target in global memory buffer with second range
t_global->ipaddr = htonl(ntohl(target.ipaddr) + delta);
t_global->range = target.range - delta;
continue;
}
}
t_global++;
}
i++;
}
// add remaining IP address to local target buffer
while (ipaddr_remainder > 0) {
if (t_global->range == 1) {
// single host
// add single host to local target buffer
t_local->ipaddr = t_global->ipaddr; // save IP address
t_local->range = t_global->range; // save range (in this case 0)
t_local++; // point to next element in local target buffer
ipaddr_remainder--; // decrement remainder counter
target_count++; // increment target counter
} else {
// IP address range
t_local->ipaddr = t_global->ipaddr; // save IP address
t_local->range = t_global->range; // save range (in this case 0)
t_local++; // point to next element in local target buffer
ipaddr_remainder -= t_global->range; // decrement remainder counter
target_count++; // increment target counter
}
//t_global += sizeof(struct targets);
t_global++;
}
// copy local target buffer to global target buffer
memcpy(target_buffer, local_target_buffer, sizeof(struct targets) * target_count);
target_buffer_count = target_count;
}
/*
* a drone has died during the scan (you will always be in our hearts) save this drones workunit
* and balance it to the remaining sender drones (if any)
*/
void drone_list::handle_dead_drone(uint32_t index)
{
uint32_t target_num = 0;
uint32_t i = 0;
uint32_t sender_idx=0;
struct targets tt;
if (this->num_send_drones < 2) {
MSG(MSG_ERR, "to many drones died through the scan. Aborting.\n");
exit(0);
}
if (this->dl[index].get_type() == IDENT_LISTENER) { /* OMG, they killed kenny! */
MSG(MSG_ERR, "listener drone died. Aborting.\n");
exit(0);
}
MSG(MSG_USR, "[info] re-distributing workload of drone %s:%d to the remaining %d sender drones\n", this->dl[index].get_addr_str(), this->dl[index].get_port(), this->num_send_drones -1);
/* step 1: get workload for this drone and overwrite global target array */
this->total_ip_count = 0;
for (target_num=0; target_num < this->dl[index].target_workunit.size(); target_num++) {
this->target_buffer[target_num] = this->dl[index].target_workunit[target_num];
this->total_ip_count += this->dl[index].target_workunit[target_num].range;
}
this->target_buffer_count = this->dl[index].target_workunit.size();
/* step 2: close connection and remove drone from list */
this->remove_drone (index, NULL);
/* step 3: balance the new global target array to the remaining drones */
this->balance_workunit();
for (i=0; i<this->dl.size(); i++) {
if (this->dl[i].get_type() == IDENT_SENDER) {
this->dl[i].redist_workunit.clear();
for (target_num=0; target_num < this-><API key>[sender_idx]; target_num++) {
tt.ipaddr = target_buffer[this->drone_distribution[sender_idx][target_num]].ipaddr;
tt.range = target_buffer[this->drone_distribution[sender_idx][target_num]].range;
this->dl[i].add_redist_workunit(&tt);
/* add range to the host array as well (if this drones workunit must be redistributed too) */
this->dl[i].add_host_workunit (&tt);
}
this->dl[i].send_new_workload();
sender_idx++;
}
}
}
/*
* save commandline arguments (for database entries)
*/
void drone_list::save_cmd_line(int argc, char *argv[])
{
uint32_t i = 0;
uint32_t cmd_line_len = 0;
char *cmd_line, *p;
for (i=0; i<argc; i++)
cmd_line_len += strlen(argv[i]); /* get cmdline length */
/* allocate memory for cmd_line incl. spaces and NULL bytes */
cmd_line = (char *) safe_zalloc(cmd_line_len + (argc * 2));
p = cmd_line;
for (i=0; i<argc; i++) {
p += snprintf(p, strlen(argv[i]) + 2, "%s ", argv[i]);
}
this->scan_cmd_line = cmd_line;
return;
}
/*
* save state of port in database (only open ports are saved. any other state is ignored)
*/
void drone_list::set_portstate (char *msg)
{
struct ipc_message *ipc_m;
struct ipc_portstate *ipc_p;
struct in_addr addr;
ipc_m = (struct ipc_message *) msg;
ipc_p = (struct ipc_portstate *) (msg + sizeof(struct ipc_message));
addr.s_addr = ipc_p->target_addr;
MSG(MSG_VBS, " * found open port %s:%d\n", inet_ntoa(addr), ipc_p->port);
db_store_result(ipc_p->target_addr, ipc_p->port);
return;
}
/*
* this function receives statistic messages from the sender drones and correlate them
*/
void drone_list::statistics (char *msg, uint32_t drone_index)
{
uint16_t i, stats_index;
struct ipc_message *ipc_m;
struct ipc_sender_stats *ipc_s;
struct ipc_sender_stats tmp, sum;
ipc_m = (struct ipc_message *) msg;
ipc_s = (struct ipc_sender_stats *) (msg + sizeof(struct ipc_message));
float timediff = (float)(ipc_s-><API key> - ipc_s->packets_send_time);
float pps = (float)(ipc_s->packets_send / timediff) * 1000000;
uint16_t prozent = ((float)ipc_s->packets_send / ipc_s->packets_total) * 100;
this->dl[drone_index].set_stats(ipc_s);
MSG(MSG_DBG, "statistics from sender drone %s: send %d packets (%d%%) in %.2f seconds (%.2fpps)\n", this->dl[drone_index].get_addr_str(), ipc_s->packets_send, prozent, (timediff/1000000), pps);
/* initiallisere statistic structs */
bzero(&sum, sizeof(struct ipc_sender_stats));
bzero(&tmp, sizeof(struct ipc_sender_stats));
// check if we have statistics from all working drones
for (i=0, stats_index=0; i < this->dl.size(); i++) {
if (dl[i].get_type() == IDENT_SENDER) {
tmp = this->dl[i].get_stats();
// is this a valid statistic received from a sender drone
if (tmp.packets_send) {
stats_index++;
// add statistics to summary struct
sum.packets_send += tmp.packets_send;
sum.packets_send_time += tmp.packets_send_time;
sum.<API key> += tmp.<API key>;
sum.packets_total += tmp.packets_total;
} else {
// not enough statistics received
break;
}
}
}
if (stats_index == this->num_send_drones) {
// calculate summary statistics
float timediff = (float)((sum.<API key> / stats_index)- (sum.packets_send_time / stats_index));
float pps = (float)(sum.packets_send / timediff) * 1000000;
uint16_t prozent = ((float)(sum.packets_send / stats_index) / (sum.packets_total / stats_index)) * 100;
gotoxy(0, 3);
MSG(MSG_VBS, "[statistics from %d sender drones]: send %d packets (%d%%) in %.2f seconds (%.2fpps)\n", stats_index, sum.packets_send, prozent, (timediff/1000000), pps);
reset_cursor();
// reset statistics
bzero(&tmp, sizeof(struct ipc_sender_stats));
for (i=0, stats_index=0; i < this->dl.size(); i++) {
if (dl[i].get_type() == IDENT_SENDER)
dl[i].set_stats(&tmp);
}
}
return;
}
void drone_list::init_routing_table(void)
{
struct routing_entry rtentry;
FILE *routefp;
char buf[1024];
char *p, *endptr, *ret;
int i;
routefp = fopen("/proc/net/route", "r");
if (routefp) {
ret = fgets(buf, sizeof(buf), routefp); /* Kill the first line (column headers) */
while(fgets(buf,sizeof(buf), routefp)) {
bzero(&rtentry, sizeof(rtentry));
p = strtok(buf, " \t\n");
if (!p) {
fprintf(stderr, "Could not find interface in /proc/net/route line");
continue;
}
if (*p == '*')
continue; /* Deleted route -- any other valid reason for a route to start with an asterict? */
strncpy(rtentry.dev, p, sizeof(rtentry.dev));
p = strtok(NULL, " \t\n");
endptr = NULL;
rtentry.dst = strtoul(p, &endptr, 16);
if (!endptr || *endptr) {
fprintf(stderr, "Failed to determine Destination from /proc/net/route");
continue;
}
p = strtok(NULL, " \t\n");
if (!p) break;
endptr = NULL;
rtentry.gw = strtoul(p, &endptr, 16);
if (!endptr || *endptr) {
fprintf(stderr, "Failed to determine gw for %s from /proc/net/route", rtentry.dev);
}
for(i=0; i < 5; i++) {
p = strtok(NULL, " \t\n");
if (!p) break;
}
if (!p) {
fprintf(stderr, "Failed to find field %d in /proc/net/route", i + 2);
continue;
}
endptr = NULL;
rtentry.mask = strtoul(p, &endptr, 16);
if (!endptr || *endptr) {
fprintf(stderr, "Failed to determine mask from /proc/net/route");
continue;
}
this->rtbl.push_back(rtentry);
}
}
return;
}
char *drone_list::get_device (void)
{
int i=0;
if (!this->rtbl.size())
this->init_routing_table();
for (i=0; i < rtbl.size(); i++) {
if ( (rtbl[i].dst & rtbl[i].mask) == (this->target_buffer[0].ipaddr & rtbl[i].mask) ) { /* uuaaaaarrrggghh */
return strdup(rtbl[i].dev);
}
}
return NULL;
} |
#include "tiny_types.h"
#include "tiny_list.h"
#include <stdbool.h>
static tiny_mutex_t s_mutex;
static uint16_t s_uid = 0;
void tiny_list_init(void)
{
static bool initialized = false;
if ( !initialized )
{
initialized = true;
tiny_mutex_create(&s_mutex);
}
}
uint16_t tiny_list_add(list_element **head, list_element *element)
{
uint16_t uid;
tiny_mutex_lock(&s_mutex);
uid = s_uid++;
element->pnext = *head;
element->pprev = 0;
if ( *head )
{
(*head)->pprev = element;
}
*head = element;
tiny_mutex_unlock(&s_mutex);
return uid & 0x0FFF;
}
void tiny_list_remove(list_element **head, list_element *element)
{
tiny_mutex_lock(&s_mutex);
if ( element == *head )
{
*head = element->pnext;
if ( *head )
{
(*head)->pprev = 0;
}
}
else
{
if ( element->pprev )
{
element->pprev->pnext = element->pnext;
}
if ( element->pnext )
{
element->pnext->pprev = element->pprev;
}
}
element->pprev = 0;
element->pnext = 0;
tiny_mutex_unlock(&s_mutex);
}
void tiny_list_clear(list_element **head)
{
tiny_mutex_lock(&s_mutex);
*head = 0;
tiny_mutex_unlock(&s_mutex);
}
void tiny_list_enumerate(list_element *head, uint8_t (*enumerate_func)(list_element *element, uint16_t data),
uint16_t data)
{
tiny_mutex_lock(&s_mutex);
while ( head )
{
if ( !enumerate_func(head, data) )
{
break;
}
head = head->pnext;
}
tiny_mutex_unlock(&s_mutex);
} |
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.03.29 at 05:09:22 PM WET
package com.trackit.presentation.view.map.provider.here.routes.common;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GeoProximityType", propOrder = {
"center",
"radius"
})
public class GeoProximityType
extends GeoAreaType
{
@XmlElement(name = "Center", required = true)
protected GeoCoordinateType center;
@XmlElement(name = "Radius")
protected Double radius;
/**
* Gets the value of the center property.
*
* @return
* possible object is
* {@link GeoCoordinateType }
*
*/
public GeoCoordinateType getCenter() {
return center;
}
/**
* Sets the value of the center property.
*
* @param value
* allowed object is
* {@link GeoCoordinateType }
*
*/
public void setCenter(GeoCoordinateType value) {
this.center = value;
}
/**
* Gets the value of the radius property.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getRadius() {
return radius;
}
/**
* Sets the value of the radius property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setRadius(Double value) {
this.radius = value;
}
} |
using System.Text;
using System.Text.RegularExpressions;
namespace Upsploit.UploadRequest {
class RequestPart{
internal string contentDisposition { get; private set;}
internal string contentType { get; set; }
internal byte[] data { get; set; }
internal string name { get; private set;}
internal byte[] fileName { get; set; }
public RequestPart(string part){
contentDisposition = <API key>(part);
name = getName(part);
fileName = getFileName(part);
if (fileName == null) { //If there's no file name, it's not a file, if it's a file, don't set the data. A files data is set by the test
data = getData(part);
}
else{
contentType = getContentType(part); //Only files have a content type
data = new byte[0]; //No data for a file, it should be set by each test
}
}
//Return the contents of the content disposition (e.g. form-data)
private static string <API key>(string part){
Match match = Regex.Match(part, "(?<=Content-Disposition: )[^;]+(?=(\n|\r|\r\n|;))");
if (match.Success)
return match.Value;
throw new <API key>("Part missing a Content-Disposition header!");
}
//Return the name of a part
private static string getName(string part){
Match match = Regex.Match(part, "(?<=name=\")(\\\\?.)*?(?=\")");
if (match.Success)
return match.Value;
throw new <API key>("Part missing a name header!");
}
//Return the filename of a part (optional parameter)
private static byte[] getFileName(string part){
Match match = Regex.Match(part, "(?<=filename=\")(\\\\?.)*?(?=\")");
return match.Success ? Encoding.ASCII.GetBytes(match.Value) : null;
}
//Returns the content type of a part (e.g. image/jpeg) (optional parameter)
private static string getContentType(string part){
Match match = Regex.Match(part, "(?<=Content-Type: ).*?(?=(\n|\r|\r\n))");
if(match.Success)
return match.Value;
throw new <API key>("Filename found without a matching content-type!");
}
//Returns the data for the part, this isn't called for the data in files (which is set by each test)
private static byte[] getData(string part){
return Encoding.ASCII.GetBytes(Regex.Match(part, "(?<=(\n|\r|\r\n){2,}).*?(?=$)").Value.TrimEnd('\r', '\n'));
}
}
} |
<?php
/**
* Map field class.
*/
class RWMB_Map_Field extends RWMB_Field {
/**
* Enqueue scripts and styles
*
* @return void
*/
static function <API key>() {
$args = func_get_args();
$field = $args[0];
$google_maps_url = add_query_arg( 'key', $field['api_key'], 'https://maps.google.com/maps/api/js' );
$google_maps_url = apply_filters( '<API key>', $google_maps_url );
mn_register_script( 'google-maps', esc_url_raw( $google_maps_url ), array(), '', true );
mn_enqueue_style( 'rwmb-map', RWMB_CSS_URL . 'map.css' );
mn_enqueue_script( 'rwmb-map', RWMB_JS_URL . 'map.js', array( '<API key>', 'google-maps' ), RWMB_VER, true );
}
/**
* Get field HTML
*
* @param mixed $meta
* @param array $field
*
* @return string
*/
static function html( $meta, $field ) {
$html = '<div class="rwmb-map-field">';
$html .= sprintf(
'<div class="rwmb-map-canvas" data-default-loc="%s"></div>
<input type="hidden" name="%s" class="rwmb-map-coordinate" value="%s">',
esc_attr( $field['std'] ),
esc_attr( $field['field_name'] ),
esc_attr( $meta )
);
if ( $address = $field['address_field'] ) {
$html .= sprintf(
'<button class="button <API key>" value="%s">%s</button>',
is_array( $address ) ? implode( ',', $address ) : $address,
__( 'Find Address', 'meta-box' )
);
}
$html .= '</div>';
return $html;
}
/**
* Normalize parameters for field
*
* @param array $field
*
* @return array
*/
static function normalize( $field ) {
$field = parent::normalize( $field );
$field = mn_parse_args( $field, array(
'std' => '',
'address_field' => '',
// Default API key, required by Google Maps since June 2016.
// Users should overwrite this key with their own key.
'api_key' => '<Google Api>',
) );
return $field;
}
/**
* Get the field value
* The difference between this function and 'meta' function is 'meta' function always returns the escaped value
* of the field saved in the database, while this function returns more meaningful value of the field
*
* @param array $field Field parameters
* @param array $args Not used for this field
* @param int|null $post_id Post ID. null for current post. Optional.
*
* @return mixed Array(latitude, longitude, zoom)
*/
static function get_value( $field, $args = array(), $post_id = null ) {
$value = parent::get_value( $field, $args, $post_id );
list( $latitude, $longitude, $zoom ) = explode( ',', $value . ',,' );
return compact( 'latitude', 'longitude', 'zoom' );
}
/**
* Output the field value
* Display Google maps
*
* @param array $field Field parameters
* @param array $args Additional arguments. Not used for these fields.
* @param int|null $post_id Post ID. null for current post. Optional.
*
* @return mixed Field value
*/
static function the_value( $field, $args = array(), $post_id = null ) {
$value = self::get_value( $field, $args, $post_id );
if ( ! $value['latitude'] || ! $value['longitude'] ) {
return '';
}
if ( ! $value['zoom'] ) {
$value['zoom'] = 14;
}
$args = mn_parse_args( $args, array(
'latitude' => $value['latitude'],
'longitude' => $value['longitude'],
'width' => '100%',
'height' => '480px',
'marker' => true, // Display marker?
'marker_title' => '', // Marker title, when hover
'info_window' => '', // Content of info window (when click on marker). HTML allowed
'js_options' => array(),
// Default API key, required by Google Maps since June 2016.
// Users should overwrite this key with their own key.
'api_key' => '<Google Api>',
) );
/*
* Enqueue scripts
* API key is get from $field (if found by RWMB_Helper::find_field()) or $args as a fallback
* Note: We still can enqueue script which outputs in the footer
*/
$api_key = isset( $field['api_key'] ) ? $field['api_key'] : $args['api_key'];
$google_maps_url = add_query_arg( 'key', $api_key, 'https://maps.google.com/maps/api/js' );
$google_maps_url = apply_filters( '<API key>', $google_maps_url );
mn_register_script( 'google-maps', esc_url_raw( $google_maps_url ), array(), '', true );
mn_enqueue_script( 'rwmb-map-frontend', RWMB_JS_URL . 'map-frontend.js', array( 'google-maps' ), '', true );
$args['js_options'] = mn_parse_args( $args['js_options'], array(
// Default to 'zoom' level set in admin, but can be overwritten
'zoom' => $value['zoom'],
// Map type, see https://developers.google.com/maps/documentation/javascript/reference#MapTypeId
'mapTypeId' => 'ROADMAP',
) );
$output = sprintf(
'<div class="rwmb-map-canvas" data-map_options="%s" style="width:%s;height:%s"></div>',
esc_attr( mn_json_encode( $args ) ),
esc_attr( $args['width'] ),
esc_attr( $args['height'] )
);
return $output;
}
} |
#ifndef MISTRUCT_H
#define MISTRUCT_H
#include "mi.h"
#include "regionstr.h"
/* information about dashes */
typedef struct _miDash {
DDXPointRec pt;
int e1, e2; /* keep these, so we don't have to do it again */
int e; /* bresenham error term for this point on line */
int which;
int newLine;/* 0 if part of same original line as previous dash */
} miDashRec;
#endif /* MISTRUCT_H */ |
package com.tigerxiao.basic.viewgroup;
import com.tigerxiao.beautyhunter.R;
import com.tigerxiao.extern.util.L;
import com.tigerxiao.extern.util.T;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class <API key> extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
L.d("onCreate <API key>");
setContentView(R.layout.orientation);
ActionBar actionBar = getActionBar();
actionBar.show();
actionBar.<API key>(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
T.showShort(this,"onCreateOptionMenu");
return CreateMenu(menu);
}
@Override
public boolean <API key>(MenuItem item) {
// TODO Auto-generated method stub
L.d("<API key> ");
return MenuChoice(item);
}
private boolean CreateMenu(Menu menu){
int i = 0;
for(i = 0; i < 5; i++){
MenuItem item = menu.add(0, i, 0, "Item "+i);
item.setIcon(R.drawable.abc_ic_go);
item.setShowAsAction(MenuItem.<API key> | MenuItem.<API key>);
}
return true;
}
private boolean MenuChoice(MenuItem item){
if(item.getItemId() == android.R.id.home){
T.showShort(this, "!!!");
}else{
T.showShort(this, "You have click "+item.getItemId());
}
return true;
}
} |
package net.atf4j.data.factory;
import java.util.Random;
import net.atf4j.core.<API key>;
import net.atf4j.data.CsvRow;
import net.atf4j.data.Postcode;
import net.atf4j.data.PostcodeData;
import net.atf4j.data.Text;
/**
* A factory for creating PostcodeData objects.
*/
public final class PostcodeDataFactory extends <API key> {
/** <API key>. */
private static final PostcodeDataFactory <API key> = new PostcodeDataFactory();
/** POSTCODE_DATA. */
private static final PostcodeData POSTCODE_DATA = PostcodeData.getInstance();
/** The random. */
protected static Random random = new Random(System.currentTimeMillis());
/**
* Gets the single instance of PostcodeDataFactory.
*
* @return single instance of PostcodeDataFactory
*/
public static PostcodeDataFactory getInstance() {
return PostcodeDataFactory.<API key>;
}
/**
* Private constructor prevents wild instantiation.
*/
private PostcodeDataFactory() {
super();
}
/**
* Create new INSTANCE of Postcode.
*
* @return the postal address
*/
public static Postcode create() {
return new Postcode();
}
/**
* Create a random postcode.
*
* @return the Postcode object.
*/
public static Postcode random() {
final Postcode postcode = new Postcode();
final int rowCount = POSTCODE_DATA.rowCount();
final int randomRow = random.nextInt(rowCount);
final CsvRow row = POSTCODE_DATA.row(randomRow);
final String[] fields = row.getFields();
postcode.setOutwardCode(fields[0]);
final String inward = String.format("%c%C%C",
Text.randomDigit(),
Text.randomChar(),
Text.randomChar());
postcode.setInwardCode(inward);
return postcode;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("PostcodeDataFactory [postCodeData=%s]", POSTCODE_DATA);
}
} |
window.onload=function(){
document.onkeydown=function(){
var e=window.event||arguments[0];
if(e.keyCode==123){
alert("");
return false;
}else if((e.ctrlKey)&&(e.shiftKey)&&(e.keyCode==73)){
alert("");
return false;
}
};
document.oncontextmenu=function(){
alert("");
return false;
}
} |
#include <random>
#include <stdexcept>
#include <iostream>
#include "math/sdb_fitting.h"
#include "Eigen"
using Eigen::MatrixXf;
using std::cout;
using std::endl;
using std::runtime_error;
namespace jtil {
namespace math {
SDBFitting::SDBFitting(uint32_t num_coeffs) {
num_coeffs_ = num_coeffs;
cur_x_.resize(num_coeffs_, 1);
new_x_.resize(num_coeffs_, 1);
delta_x_.resize(num_coeffs_, 1);
cur_J_.resize(num_coeffs_, 1);
cur_J_transpose_.resize(1, num_coeffs_);
cur_p_.resize(num_coeffs_, 1);
// Some default parameters
max_iterations = 1000;
eta_s = 1e-4f;
jac_2norm_term = 1e-4f;
gamma = 0.5f;
delta_x_2norm_term = 1e-5f;
delta_f_term = 1e-5f;
}
SDBFitting::~SDBFitting() {
}
MatrixXf& SDBFitting::fitModel(const MatrixXf& start_c,
const bool* angle_coeff,
ObjectiveFuncPtr obj_func,
JacobianFuncPtr jac_func,
CoeffUpdateFuncPtr coeff_update_func) {
obj_func_ = obj_func;
jac_func_ = jac_func;
coeff_update_func_ = coeff_update_func;
angle_coeff_ = angle_coeff;
cout << "Starting Steepest-Descent with backtracking optimization..." << endl;
if (start_c.rows() == 1) {
cur_x_ = start_c.transpose(); // I want a row vector here
} else {
cur_x_ = start_c;
}
cur_f_ = obj_func(cur_x_);
uint32_t no_iterations = 0;
while (no_iterations < max_iterations) {
#ifdef SDB_VERBOSE_SOLVER
cout << "******************************************************" << endl;
cout << "Iteration: " << no_iterations << endl;
//cout << " cur_x_^T = ";
//for (uint32_t i = 0; i < num_coeffs_; i++) { cout << cur_x_(i) << " "; }
//cout << endl;
cout << " cur_f_ = " << cur_f_ << endl;
#endif
jac_func_(cur_J_, cur_x_);
float jac_2norm_ = cur_J_.norm();
#ifdef SDB_VERBOSE_SOLVER
//cout << " cur_J_^T = ";
//for (uint32_t i = 0; i < num_coeffs_; i++) { cout << cur_J_(i) << " "; }
//cout << endl;
cout << " ||J||_2 = " << jac_2norm_ << endl;
#endif
if (jac_2norm_ < jac_2norm_term) {
#ifdef SDB_VERBOSE_SOLVER
cout << " jac_2norm_ < jac_2norm_term" << endl;
#endif
break;
}
cur_p_ = -cur_J_; // search direction is the steepest descent direction
cur_J_transpose_ = cur_J_.transpose();
// Otherwise perform a backtracking line search:
float alpha = 1;
uint32_t <API key> = 0;
interpolateCoeff(new_x_, cur_x_, alpha, cur_p_);
new_f_ = obj_func_(new_x_);
MatrixXf cur_J_tran_p = cur_J_transpose_ * cur_p_; // avoid redundant calc
while (new_f_ > (cur_f_ + eta_s * alpha * cur_J_tran_p(0)) &&
<API key> < 100) {
// Armijo sufficient decrease condition not met: contract the step
alpha *= gamma;
interpolateCoeff(new_x_, cur_x_, alpha, cur_p_);
new_f_ = obj_func_(new_x_);
<API key>++;
}
if (<API key> > 100) {
#ifdef SDB_VERBOSE_SOLVER
cout << " <API key> > 100" << endl;
#endif
break;
}
#ifdef SDB_VERBOSE_SOLVER
cout << " alpha = " << alpha << endl;
#endif
// Take the step:
delta_x_ = cur_x_ - new_x_;
float delta_x_2norm = delta_x_.norm();
float delta_f = cur_f_ - new_f_; // Guaranteed positive
#ifdef SDB_VERBOSE_SOLVER
cout << " ||DeltaX||_2 = " << delta_x_2norm << endl;
cout << " |delta_f| = " << delta_f << endl;
#endif
cur_x_ = new_x_;
cur_f_ = new_f_;
if (delta_x_2norm < delta_x_2norm_term) {
#ifdef SDB_VERBOSE_SOLVER
cout << " delta_x_2norm < delta_x_2norm_term" << endl;
#endif
break;
}
if (delta_f < delta_f_term) {
#ifdef SDB_VERBOSE_SOLVER
cout << " delta_f < delta_f_term" << endl;
#endif
break;
}
no_iterations++;
}
std::cout << "Steepest Descent with backtracking finished with f = " << cur_f_ << endl;
if (start_c.rows() == 1) {
cur_x_.transposeInPlace();
}
return cur_x_;
}
// interpolateCoeff performs the following:
// ret = a + interp_val * (b - c)
void SDBFitting::interpolateCoeff(Eigen::MatrixXf& ret, const Eigen::MatrixXf& a,
const float interp_val, const Eigen::MatrixXf& b, const Eigen::MatrixXf& c) {
for (uint32_t i = 0; i < num_coeffs_; i++) {
if (angle_coeff_ != NULL && angle_coeff_[i]) {
float real_a = cos(a(i));
float imag_a = sin(a(i));
float real_b = cos(b(i));
float imag_b = sin(b(i));
float real_c = cos(c(i));
float imag_c = sin(c(i));
float real_interp = real_a + interp_val * (real_b - real_c);
float imag_interp = imag_a + interp_val * (imag_b - imag_c);
float interp_angle = atan2(imag_interp, real_interp);
ret(i) = interp_angle;
} else {
ret(i) = a(i) + interp_val * (b(i) - c(i));
}
}
if (coeff_update_func_) {
coeff_update_func_(ret);
}
}
// interpolateCoeff performs the following:
// ret = a + interp_val * b
void SDBFitting::interpolateCoeff(Eigen::MatrixXf& ret, const Eigen::MatrixXf& a,
const float interp_val, const Eigen::MatrixXf& b) {
for (uint32_t i = 0; i < num_coeffs_; i++) {
if (angle_coeff_ != NULL && angle_coeff_[i]) {
float real_a = cos(a(i));
float imag_a = sin(a(i));
float real_b = cos(b(i));
float imag_b = sin(b(i));
float real_interp = real_a + interp_val * real_b;
float imag_interp = imag_a + interp_val * imag_b;
float interp_angle = atan2(imag_interp, real_interp);
ret(i) = interp_angle;
} else {
ret(i) = a(i) + interp_val * b(i);
}
}
if (coeff_update_func_) {
coeff_update_func_(ret);
}
}
} // namespace math
} // namespace jtil |
package com.isode.stroke.presence;
import com.isode.stroke.elements.Payload;
import com.isode.stroke.elements.Presence;
/**
* This presence sender adds payloads to outgoing presences.
*
* This class isn't meant to be used with directed presence.
*/
public class <API key> implements PresenceSender {
private Presence lastSentPresence;
private final PresenceSender sender;
private Payload payload;
public <API key>(PresenceSender sender) {
this.sender = sender;
}
public void sendPresence(Presence presence) {
if (presence.isAvailable()) {
if (presence.getTo() != null && !presence.getTo().isValid()) {
lastSentPresence = presence;
}
} else {
lastSentPresence = null;
}
if (payload != null) {
Presence sentPresence = new Presence(presence);
sentPresence.updatePayload(payload);
sender.sendPresence(sentPresence);
} else {
sender.sendPresence(presence);
}
}
public boolean isAvailable() {
return sender.isAvailable();
}
/**
* Sets the payload to be added to outgoing presences. If initial presence
* has been sent, this will resend the last sent presence with an updated
* payload. Initial presence is reset when unavailable presence is sent, or
* when reset() is called.
*/
public void setPayload(Payload payload) {
this.payload = payload;
if (lastSentPresence != null) {
sendPresence(lastSentPresence);
}
}
/**
* Resets the presence sender. This puts the presence sender back in the
* initial state (before initial presence has been sent). This also resets
* the chained sender.
*/
public void reset() {
lastSentPresence = null;
}
} |
require 'package'
class Pygtk < Package
description 'PyGTK is a Python package which provides bindings for GObject based libraries such as GTK+, GStreamer, WebKitGTK+, GLib, GIO and many more.'
homepage 'http:
version '2.24.0'
compatibility 'all'
source_url 'https://ftp.gnome.org/pub/GNOME/sources/pygtk/2.24/pygtk-2.24.0.tar.bz2'
source_sha256 '<SHA256-like>'
binary_url ({
aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/pygtk-2.24.0-chromeos-armv7l.tar.xz',
armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/pygtk-2.24.0-chromeos-armv7l.tar.xz',
i686: 'https://dl.bintray.com/chromebrew/chromebrew/pygtk-2.24.0-chromeos-i686.tar.xz',
x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/pygtk-2.24.0-chromeos-x86_64.tar.xz',
})
binary_sha256 ({
aarch64: '<SHA256-like>',
armv7l: '<SHA256-like>',
i686: '<SHA256-like>',
x86_64: '<SHA256-like>',
})
depends_on 'libglade'
depends_on 'pygobject2'
def self.build
system "./configure --prefix=#{CREW_PREFIX} --libdir=#{CREW_LIB_PREFIX}"
system 'make'
end
def self.install
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
end
end |
<?php
namespace sJo\Model;
use sJo\Model\Database\DatabaseInterface;
use sJo\Object\Singleton;
use sJo\Object\Entity;
use sJo\Model\Database\Map;
abstract class Model implements DatabaseInterface
{
use Singleton;
use Entity;
use Control\Error;
use Control\Validate {
Control\Validate::validate as private validateControl;
}
use Map {
Map::__construct as private __constructMap;
}
public function __construct($id = null)
{
if (null !== $id) {
$this->setPrimaryValue($id);
}
$this->__constructMap();
}
public function secure (array $fields)
{
$success = true;
if (null !== $this->getPrimaryValue()) {
foreach ($fields as $name=>$value) {
if ($this->{$name} !== $value) {
$success = false;
}
}
}
return $success;
}
public function validate ()
{
$this->validateControl();
if (method_exists($this, 'validateForm')) {
$this->validateForm();
}
return !$this->hasErrors();
}
protected function getFieldLabel ($name)
{
// Get field label
$label = null;
if (method_exists($this, '<API key>')) {
$label = $this-><API key>($name, 'label');
}
if (is_null($label)) {
$label = $name;
}
return $label;
}
} |
#!/usr/bin/env python
from ciscoconfparse import CiscoConfParse
def main():
cisco_cfg = CiscoConfParse("cisco_ipsec.txt")
cr_map_list = cisco_cfg.find_objects(r"^crypto map CRYPTO")
for item in cr_map_list:
print item.text
for child in item.children:
print child.text
if __name__ == "__main__":
main() |
#!/usr/bin/python
import simplejson as json
i = open('/proc/cpuinfo')
my_text = i.readlines()
i.close()
username = ""
for line in my_text:
line = line.strip()
ar = line.split(' ')
if ar[0].startswith('Serial'):
username = "a" + ar[1]
if not username:
exit(-1)
o = open('/home/pi/.cgminer/cgminer.conf', 'w');
pools = []
pools.append({"url": "stratum+tcp://ghash.io:3333",
"user": username, "pass": "12345"})
conf = {"pools": pools,
"api-listen" : "true",
"api-port" : "4028",
"api-allow" : "W:127.0.0.1"}
txt = json.dumps(conf, sort_keys=True, indent=4 * ' ')
o.write(txt)
o.write("\n");
o.close() |
package cn.exrick.manager.dto;
import java.io.Serializable;
/**
* @author Exrickx
*/
public class RoleDto implements Serializable{
private int id;
private String name;
private String permissions;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPermissions() {
return permissions;
}
public void setPermissions(String permissions) {
this.permissions = permissions;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} |
<?php
// common hosting config file for all bertas
if (file_exists($ENGINE_ROOT_PATH . 'hosting')) {
$hostingConfig = json_decode(file_get_contents($ENGINE_ROOT_PATH . 'hosting'), true);
}
$options['PLANS'] = isset($hostingConfig['plans']) ? $hostingConfig['plans'] : [];
$options['HOSTING_PROFILE'] = isset($hostingConfig['login']) ? $hostingConfig['login'] : false;
$options['FORGOTPASSWORD_LINK'] = isset($hostingConfig['forgotPassword']) ? $hostingConfig['forgotPassword'] : 'http://support.berta.me/kb/<API key>/forgot-my-<API key>;
$options['INTERCOM_APP_ID'] = isset($hostingConfig['intercomAppId']) ? $hostingConfig['intercomAppId'] : false;
$options['INTERCOM_SECRET_KEY'] = isset($hostingConfig['intercomSecretKey']) ? $hostingConfig['intercomSecretKey'] : false;
$options['EMAIL_FROM_ADDRESS'] = isset($hostingConfig['emailFromAddress']) ? $hostingConfig['emailFromAddress'] : false;
//individual hosting config file for berta
if (file_exists($ENGINE_ROOT_PATH . 'hosting_config')) {
$hostingConfigBerta = parse_ini_string(file_get_contents($ENGINE_ROOT_PATH . 'hosting_config'));
}
$options['NOINDEX'] = isset($hostingConfigBerta['noindex']) && ($hostingConfigBerta['noindex'] === $_SERVER['HTTP_HOST'] || 'www.' . $hostingConfigBerta['noindex'] === $_SERVER['HTTP_HOST']); |
class Admin::ActionsController < AdminController
before_action :load_job
def edit
@action = @job.actions.find_by(id: params[:id])
end
def update
end
def destroy
@action = @job.actions.find_by(id: params[:id])
@action.destroy
redirect_to edit_admin_job_path(@job)
end
private
def action_params
params.require(:action).permit!
end
def load_job
@job = Job.find_by(id: params[:job_id])
end
end |
<?php
# Template for check_swap
# $Id: check_swap.php 631 2009-05-01 12:20:53Z Le_Loup $
# RRDtool Options
$opt[1] = "-X 0 --vertical-label MB -l 0 -u $MAX[1] --title \"Swap usage $hostname / $servicedesc\" ";
# Graphen Definitions
$def[1] = "DEF:var1=$rrdfile:$DS[1]:AVERAGE ";
$def[1] .= "AREA:var1#c6c6c6:\"$servicedesc\\n\" ";
$def[1] .= "LINE1:var1#003300: ";
$def[1] .= "HRULE:$MAX[1]#003300:\"Capacity $MAX[1] MB \" ";
if ($WARN[1] != "") {
$def[1] .= "HRULE:$WARN[1]#ffff00:\"Warning on $WARN[1] MB \" ";
}
if ($CRIT[1] != "") {
$def[1] .= "HRULE:$CRIT[1]#ff0000:\"Critical on $CRIT[1] MB \\n\" ";
}
$def[1] .= "GPRINT:var1:LAST:\"%6.2lf MB currently free \\n\" ";
$def[1] .= "GPRINT:var1:MAX:\"%6.2lf MB max free \\n\" ";
$def[1] .= "GPRINT:var1:AVERAGE:\"%6.2lf MB average free\" ";
?> |
"This module provides uniform and local mesh refinement."
# This file is part of DOLFIN.
# DOLFIN is free software: you can redistribute it and/or modify
# (at your option) any later version.
# DOLFIN is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# First added: 2010-02-26
# Last changed: 2010-02-26
__all__ = ["refine"]
# Import C++ interface
import dolfin.cpp as cpp
def refine(mesh, cell_markers=None):
"""
Refine given mesh and return the refined mesh.
*Arguments*
mesh
the :py:class:`Mesh <dolfin.cpp.Mesh>` to be refined.
cell_markers
an optional argument (a boolean :py:class:`MeshFunction
<dolfin.cpp.MeshFunctionBool>` over cells) may be given
to specify which cells should be refined. If no cell
markers are given, then the mesh is refined uniformly.
*Examples of usage*
.. code-block:: python
mesh = refine(mesh)
To only refine cells with too large error, define a boolean
MeshFunction over the mesh and mark the cells to be refined
as True.
.. code-block:: python
cell_markers = CellFunction("bool", mesh)
cell_markers.set_all(False)
for cell in cells(mesh):
# set cell_markers[cell] = True if the cell's error
# indicator is greater than some criterion.
mesh = refine(mesh, cell_markers)
"""
# This function is necessary to avoid copying in the wrapped
# versions of the return-by-value refine functions in C++.
# Create empty mesh
refined_mesh = cpp.Mesh()
# Call C++ refinement
if cell_markers is None:
cpp.refine(refined_mesh, mesh)
else:
cpp.refine(refined_mesh, mesh, cell_markers)
return refined_mesh |
// This file is part of Return To The Roots.
// Return To The Roots is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Return To The Roots is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#include "defines.h" // IWYU pragma: keep
#include "nofAttacker.h"
#include "EventManager.h"
#include "GameClient.h"
#include "GamePlayer.h"
#include "Random.h"
#include "SerializedGameData.h"
#include "addons/const_addons.h"
#include "buildings/nobHarborBuilding.h"
#include "buildings/nobMilitary.h"
#include "<API key>.h"
#include "nofDefender.h"
#include "nofPassiveSoldier.h"
#include "postSystem/PostMsgWithBuilding.h"
#include "world/GameWorldGame.h"
#include "nodeObjs/noFighting.h"
#include "nodeObjs/noFlag.h"
#include "nodeObjs/noShip.h"
Nach einer bestimmten Zeit, in der der Angreifer an der Flagge des Gebäudes steht, blockt er den Weg
nur benutzt bei <API key>
Dieses Konstante gibt an, wie lange, nachdem er anfängt da zu stehen, er blockt
const unsigned BLOCK_OFFSET = 10;
nofAttacker::nofAttacker(nofPassiveSoldier* other, nobBaseMilitary* const attacked_goal)
: nofActiveSoldier(*other, <API key>), attacked_goal(attacked_goal),
should_haunted(gwg->GetPlayer(attacked_goal->GetPlayer()).ShouldSendDefender()), huntingDefender(NULL), blocking_event(NULL),
harborPos(MapPoint::Invalid()), shipPos(MapPoint::Invalid()), ship_obj_id(0)
{
// Dem Haus Bescheid sagen
static_cast<nobMilitary*>(building)->SoldierOnMission(other, this);
// Dem Ziel Bescheid sagen
attacked_goal->LinkAggressor(this);
}
nofAttacker::nofAttacker(nofPassiveSoldier* other, nobBaseMilitary* const attacked_goal, const nobHarborBuilding* const harbor)
: nofActiveSoldier(*other, <API key>), attacked_goal(attacked_goal),
should_haunted(gwg->GetPlayer(attacked_goal->GetPlayer()).ShouldSendDefender()), huntingDefender(NULL), blocking_event(NULL),
harborPos(harbor->GetPos()), shipPos(MapPoint::Invalid()), ship_obj_id(0)
{
// Dem Haus Bescheid sagen
static_cast<nobMilitary*>(building)->SoldierOnMission(other, this);
// Dem Ziel Bescheid sagen
attacked_goal->LinkAggressor(this);
}
nofAttacker::~nofAttacker()
{
// unsigned char oplayer = (player == 0) ? 1 : 0;
// RTTR_Assert(!gwg->GetPlayer(oplayer).GetFirstWH()->Test(this));
}
void nofAttacker::Destroy_nofAttacker()
{
RTTR_Assert(!attacked_goal);
RTTR_Assert(!ship_obj_id);
RTTR_Assert(!huntingDefender);
<API key>();
/*unsigned char oplayer = (player == 0) ? 1 : 0;
RTTR_Assert(!gwg->GetPlayer(oplayer).GetFirstWH()->Test(this));*/
}
void nofAttacker::<API key>(SerializedGameData& sgd) const
{
<API key>(sgd);
if(state != STATE_WALKINGHOME && state != STATE_FIGUREWORK)
{
sgd.PushObject(attacked_goal, false);
sgd.PushBool(should_haunted);
sgd.PushObject(huntingDefender, true);
sgd.PushUnsignedShort(radius);
if(state == <API key>)
sgd.PushObject(blocking_event, true);
sgd.PushMapPoint(harborPos);
sgd.PushMapPoint(shipPos);
sgd.PushUnsignedInt(ship_obj_id);
} else
{
RTTR_Assert(!attacked_goal);
RTTR_Assert(!huntingDefender);
RTTR_Assert(!blocking_event);
}
}
nofAttacker::nofAttacker(SerializedGameData& sgd, const unsigned obj_id) : nofActiveSoldier(sgd, obj_id)
{
if(state != STATE_WALKINGHOME && state != STATE_FIGUREWORK)
{
attacked_goal = sgd.PopObject<nobBaseMilitary>(GOT_UNKNOWN);
should_haunted = sgd.PopBool();
huntingDefender = sgd.PopObject<<API key>>(<API key>);
radius = sgd.PopUnsignedShort();
if(state == <API key>)
blocking_event = sgd.PopEvent();
else
blocking_event = NULL;
harborPos = sgd.PopMapPoint();
shipPos = sgd.PopMapPoint();
ship_obj_id = sgd.PopUnsignedInt();
} else
{
attacked_goal = NULL;
should_haunted = false;
huntingDefender = NULL;
radius = 0;
blocking_event = NULL;
harborPos = MapPoint::Invalid();
shipPos = MapPoint::Invalid(); //-V656
ship_obj_id = 0;
}
}
void nofAttacker::Walked()
{
ExpelEnemies();
// Was bestimmtes machen, je nachdem welchen Status wir gerade haben
switch(state)
{
default: nofActiveSoldier::Walked(); break;
case <API key>: { MissAttackingWalk();
}
break;
case <API key>:
{
if(!attacked_goal)
{
// Nach Hause gehen
<API key>();
return;
}
MapPoint goalFlagPos = attacked_goal->GetFlag()->GetPos();
// RTTR_Assert(enemy->GetGOT() == GOT_NOF_DEFENDER);
// Are we at the flag?
nofDefender* defender = NULL;
// Look for defenders at this position
const std::list<noBase*>& figures = gwg->GetFigures(goalFlagPos);
for(std::list<noBase*>::const_iterator it = figures.begin(); it != figures.end(); ++it)
{
if((*it)->GetGOT() == GOT_NOF_DEFENDER)
{
// Is the defender waiting at the flag?
// (could be wandering around or something)
if(static_cast<nofDefender*>(*it)->IsWaitingAtFlag())
{
defender = static_cast<nofDefender*>(*it);
}
}
}
if(pos == goalFlagPos)
{
if(defender)
{
// Start fight with the defender
gwg->AddFigure(new noFighting(this, defender), pos);
// Set the appropriate states
state = <API key>;
defender->FightStarted();
} else
// No defender at the flag?
// -> Order new defenders or capture the building
ContinueAtFlag();
} else
{
unsigned char dir = gwg->FindHumanPath(pos, goalFlagPos, 5, true);
if(dir == 0xFF)
{
state = <API key>;
MissAttackingWalk();
if(defender)
defender->AttackerArrested();
} else
{
// Hinlaufen
StartWalking(Direction(dir));
}
}
}
break;
case <API key>:
{
if(!attacked_goal)
{
// Nach Hause gehen
<API key>();
return;
}
// Wenn schon welche drin sind, ist wieder ein feindlicher reingegangen
if(attacked_goal->DefendersAvailable())
{
// Wieder rausgehen, Platz reservieren
if(attacked_goal->GetGOT() == GOT_NOB_MILITARY)
static_cast<nobMilitary*>(attacked_goal)->StopCapturing();
state = <API key>;
StartWalking(Direction::SOUTHEAST);
return;
} else
{
if(attacked_goal->GetBuildingType() >= BLD_BARRACKS && attacked_goal->GetBuildingType() <= BLD_FORTRESS)
{
RTTR_Assert(dynamic_cast<nobMilitary*>(attacked_goal));
if(building)
building->SoldierLost(this);
<API key>();
// Ggf. Schiff Bescheid sagen (Schiffs-Angreifer)
if(ship_obj_id)
CancelAtShip();
nobMilitary* goal = static_cast<nobMilitary*>(attacked_goal);
goal->Capture(player);
// This is the new home
building = attacked_goal;
attacked_goal->AddActiveSoldier(this);
<API key>();
// Tell that we arrived and probably call other capturers
goal-><API key>();
gwg->RemoveFigure(this, pos);
}
// oder ein Hauptquartier oder Hafen?
else
{
// Inform the owner of the building
const std::string msg = (attacked_goal->GetGOT() == GOT_NOB_HQ) ? _("Our headquarters was destroyed!") :
_("This harbor building was destroyed");
SendPostMessage(attacked_goal->GetPlayer(),
new PostMsgWithBuilding(GetEvMgr().GetCurrentGF(), msg, PostCategory::Military, *attacked_goal));
nobBaseMilitary* tmp_goal = attacked_goal; // attacked_goal wird evtl auf 0 gesetzt!
tmp_goal->Destroy();
delete tmp_goal;
attacked_goal = NULL;
<API key>();
}
}
}
break;
case <API key>: { CapturingWalking();
}
break;
case <API key>:
{
// Gucken, ob der Abflughafen auch noch steht und sich in unserer Hand befindet
bool valid_harbor = true;
noBase* hb = gwg->GetNO(harborPos);
if(hb->GetGOT() != <API key>)
valid_harbor = false;
else if(static_cast<nobHarborBuilding*>(hb)->GetPlayer() != player)
valid_harbor = false;
if(!valid_harbor || !attacked_goal)
{
// Dann gehen wir halt wieder nach Hause
<API key>();
return;
}
// Sind wir schon da?
if(pos == harborPos)
{
state = <API key>;
gwg->RemoveFigure(this, pos);
gwg->GetSpecObj<nobHarborBuilding>(pos)->AddSeaAttacker(this);
return;
}
// Erstmal Flagge ansteuern
MapPoint harborFlagPos = gwg->GetNeighbour(harborPos, Direction::SOUTHEAST);
// Wenn wir an der Flagge bereits sind, in den Hafen eintreten
if(pos == harborFlagPos)
StartWalking(Direction::NORTHWEST);
else
{
// Weg zum Hafen suchen
unsigned char dir = gwg->FindHumanPath(pos, harborFlagPos, <API key>, false, NULL);
if(dir == 0xff)
{
// Kein Weg gefunden? Dann auch abbrechen!
<API key>();
return;
}
StartWalking(Direction(dir));
}
}
break;
case <API key>: // wartet im Hafen auf das ankommende Schiff
{
}
break;
case <API key>: // befindet sich auf dem Schiff auf dem Weg zum Zielpunkt
{
// Auweia, das darf nicht passieren
RTTR_Assert(false);
}
break;
case <API key>:
{
<API key>();
}
break;
}
}
Wenn ein Heimat-Militärgebäude bei Missionseinsätzen zerstört wurde
void nofAttacker::HomeDestroyed()
{
switch(state)
{
case <API key>:
{
// Hier muss sofort reagiert werden, da man steht
nobBaseMilitary* curGoal = attacked_goal; // attacked_goal gets reset
<API key>();
// Ggf. Schiff Bescheid sagen (Schiffs-Angreifer)
if(ship_obj_id)
CancelAtShip();
// Rumirren
building = NULL;
state = STATE_FIGUREWORK;
StartWandering();
Wander();
curGoal->SendSuccessor(pos, radius, GetCurMoveDir());
}
break;
default:
{
if(goal_ == building)
goal_ = NULL;
building = NULL;
}
break;
}
}
void nofAttacker::<API key>()
{
building = NULL;
<API key>();
state = STATE_FIGUREWORK;
// Rumirren
StartWandering();
StartWalking(Direction(RANDOM.Rand(__FILE__, __LINE__, GetObjId(), 6)));
}
Wenn ein Kampf gewonnen wurde
void nofAttacker::WonFighting()
{
// addon <API key> active? -> increase rank!
if(gwg->GetGGS().isEnabled(AddonId::<API key>))
IncreaseRank();
if(!building && state != <API key>)
{
<API key>();
// Ggf. Schiff Bescheid sagen (Schiffs-Angreifer)
if(ship_obj_id)
CancelAtShip();
// Rumirren
state = STATE_FIGUREWORK;
StartWandering();
Wander();
return;
}
if(!attacked_goal)
{
// Nach Hause gehen
<API key>();
return;
}
ContinueAtFlag();
}
Doesn't find a defender at the flag -> Send defenders or capture it
void nofAttacker::ContinueAtFlag()
{
if(state == <API key>
|| (attacked_goal && state == STATE_FIGHTING && attacked_goal->GetFlag()->GetPos() == pos))
{
// Dann neuen Verteidiger rufen
if(attacked_goal->CallDefender(this))
{
// Verteidiger gefunden --> hinstellen und auf ihn warten
<API key>();
} else
{
// check for soldiers of other non-friendly non-owner players to fight
if(FindEnemiesNearby(attacked_goal->GetPlayer()))
return;
state = <API key>;
StartWalking(Direction::NORTHWEST);
if(attacked_goal->GetGOT() == GOT_NOB_MILITARY)
static_cast<nobMilitary*>(attacked_goal)->PrepareCapturing();
}
} else
{
// weiterlaufen
state = <API key>;
MissAttackingWalk();
}
}
Wenn ein Kampf verloren wurde (Tod)
void nofAttacker::LostFighting()
{
AbrogateWorkplace();
<API key>();
// Ggf. Schiff Bescheid sagen
if(ship_obj_id)
this->CancelAtShip();
}
void nofAttacker::<API key>()
{
// Zielen Bescheid sagen
<API key>();
// Schiffsangreifer?
if(ship_obj_id)
{
state = <API key>;
<API key>();
} else
// Und nach Hause gehen
ReturnHome();
}
void nofAttacker::MissAttackingWalk()
{
if(!building)
{
<API key>();
// Ggf. Schiff Bescheid sagen (Schiffs-Angreifer)
if(ship_obj_id)
CancelAtShip();
// Rumirren
state = STATE_FIGUREWORK;
StartWandering();
Wander();
return;
}
if(!attacked_goal)
{
<API key>();
return;
}
/*// Is it still a hostile destination?
// (Could be captured in the meantime)
if(!players->getElement(player)->IsPlayerAttackable(attacked_goal->GetPlayer()))
{
<API key>();
return;
}*/
MapPoint goal = attacked_goal->FindAnAttackerPlace(radius, this);
// Keinen Platz mehr gefunden?
if(!goal.isValid())
{
// Dann nach Haus gehen
<API key>();
return;
}
// Sind wir evtl schon da?
if(pos == goal)
{
ReachedDestination();
return;
}
// Find all sorts of enemies (attackers, aggressive defenders..) nearby
if(FindEnemiesNearby())
// Enemy found -> abort, because nofActiveSoldier handles all things now
return;
// Haben wir noch keinen Feind?
<API key>();
// Ansonsten Weg zum Ziel suchen
unsigned char dir = gwg->FindHumanPath(pos, goal, <API key>, true);
// Keiner gefunden? Nach Hause gehen
if(dir == 0xff)
{
<API key>();
return;
}
// Start walking
StartWalking(Direction(dir));
}
Ist am Militärgebäude angekommen
void nofAttacker::ReachedDestination()
{
// Sind wir direkt an der Flagge?
if(pos == attacked_goal->GetFlag()->GetPos())
{
// Building already captured? Continue capturing
// This can only be a far away attacker
if(attacked_goal->GetPlayer() == player)
{
state = <API key>;
RTTR_Assert(dynamic_cast<nobMilitary*>(attacked_goal));
nobMilitary* goal = static_cast<nobMilitary*>(attacked_goal);
RTTR_Assert(goal->IsFarAwayCapturer(this));
// Start walking first so the flag is free
StartWalking(Direction::NORTHWEST);
// Then tell the building
goal-><API key>(this);
return;
}
SendPostMessage(attacked_goal->GetPlayer(), new PostMsgWithBuilding(GetEvMgr().GetCurrentGF(), _("We are under attack!"),
PostCategory::Military, *attacked_goal));
// Dann Verteidiger rufen
if(attacked_goal->CallDefender(this))
{
// Verteidiger gefunden --> hinstellen und auf ihn warten
<API key>();
} else
{
state = <API key>;
StartWalking(Direction::NORTHWEST);
if(attacked_goal->GetGOT() == GOT_NOB_MILITARY)
static_cast<nobMilitary*>(attacked_goal)->PrepareCapturing();
}
} else
{
// reservieren, damit sich kein anderer noch hier hinstellt
state = <API key>;
// zur Flagge hin ausrichten
Direction dir(Direction::WEST);
MapPoint attFlagPos = attacked_goal->GetFlag()->GetPos();
if(pos.y == attFlagPos.y && pos.x <= attFlagPos.x)
dir = Direction::EAST;
else if(pos.y == attFlagPos.y && pos.x > attFlagPos.x)
dir = Direction::WEST;
else if(pos.y < attFlagPos.y && pos.x < attFlagPos.x)
dir = Direction::SOUTHEAST;
else if(pos.y < attFlagPos.y && pos.x > attFlagPos.x)
dir = Direction::SOUTHWEST;
else if(pos.y > attFlagPos.y && pos.x < attFlagPos.x)
dir = Direction::NORTHEAST;
else if(pos.y > attFlagPos.y && pos.x > attFlagPos.x)
dir = Direction::NORTHWEST;
else /* (pos.x == attFlagPos.x)*/
{
if(pos.y < attFlagPos.y && !(SafeDiff(pos.y, attFlagPos.y) & 1))
dir = Direction::SOUTHEAST;
else if(pos.y < attFlagPos.y && (SafeDiff(pos.y, attFlagPos.y) & 1))
{
if(pos.y & 1)
dir = Direction::SOUTHWEST;
else
dir = Direction::SOUTHEAST;
} else if(pos.y > attFlagPos.y && !(SafeDiff(pos.y, attFlagPos.y) & 1))
dir = Direction::NORTHEAST;
else /* (pos.y > attFlagPos.y && (SafeDiff(pos.y, attFlagPos.y) & 1))*/
{
if(pos.y & 1)
dir = Direction::NORTHWEST;
else
dir = Direction::NORTHEAST;
}
}
FaceDir(dir);
if(attacked_goal->GetPlayer() == player)
{
// Building already captured? -> Then we might be a far-away-capturer
// -> Tell the building, that we are here
RTTR_Assert(dynamic_cast<nobMilitary*>(attacked_goal));
nobMilitary* goal = static_cast<nobMilitary*>(attacked_goal);
if(goal->IsFarAwayCapturer(this))
goal-><API key>(this);
}
}
}
Versucht, eine aggressiven Verteidiger für uns zu bestellen
void nofAttacker::<API key>()
{
RTTR_Assert(state == <API key>);
// Haben wir noch keinen Gegner?
if(!should_haunted)
return;
// 20%ige Chance, dass wirklich jemand angreift
if(RANDOM.Rand(__FILE__, __LINE__, GetObjId(), 10) >= 2)
return;
sortedMilitaryBlds buildings = gwg-><API key>(pos, 2);
for(sortedMilitaryBlds::iterator it = buildings.begin(); it != buildings.end(); ++it)
{
if((*it)->GetBuildingType() == BLD_HEADQUARTERS && (*it) != attacked_goal)
continue;
// darf nicht weiter weg als 15 sein
if(gwg->CalcDistance(pos, (*it)->GetPos()) >= 15)
continue;
if(gwg->GetPlayer(attacked_goal->GetPlayer()).IsAlly((*it)->GetPlayer()) && gwg->GetPlayer(player).IsAttackable((*it)->GetPlayer()))
{
// ggf. Verteidiger rufen
huntingDefender = (*it)-><API key>(this);
if(huntingDefender)
{
// nun brauchen wir keinen Verteidiger mehr
should_haunted = false;
break;
}
}
}
}
void nofAttacker::<API key>()
{
attacked_goal = NULL;
bool <API key> = (state == <API key>);
// Wenn man gerade rumsteht, muss man sich bewegen
if(state == <API key> || state == <API key> || state == <API key>)
<API key>();
else if(state == <API key>)
{
// We don't need to wait anymore, target was destroyed
nobHarborBuilding* harbor = gwg->GetSpecObj<nobHarborBuilding>(harborPos);
RTTR_Assert(harbor);
// go home
goal_ = building;
state = STATE_FIGUREWORK;
fs = FS_GOTOGOAL;
harbor->CancelSeaAttacker(this);
return;
}
if(<API key>)
{
// Block-Event ggf abmelden
GetEvMgr().RemoveEvent(blocking_event);
gwg->RoadNodeAvailable(pos);
}
}
bool nofAttacker::AttackFlag(nofDefender* /*defender*/)
{
// Zur Flagge laufen, findet er einen Weg?
unsigned char tmp_dir = gwg->FindHumanPath(pos, attacked_goal->GetFlag()->GetPos(), 3, true);
if(tmp_dir != 0xFF)
{
Direction old_dir = GetCurMoveDir();
// Hat er drumrum gewartet?
bool <API key> = (state == <API key>);
// Ja er hat einen Weg gefunden, also hinlaufen
// Wenn er steht, muss er loslaufen
if(<API key>)
StartWalking(Direction(tmp_dir));
state = <API key>;
if(<API key>)
{
attacked_goal->SendSuccessor(pos, radius, old_dir);
}
return true;
}
return false;
}
void nofAttacker::AttackFlag()
{
// "Normal" zur Flagge laufen
state = <API key>;
MissAttackingWalk();
}
void nofAttacker::CaptureBuilding()
{
state = <API key>;
// und hinlaufen
CapturingWalking();
}
void nofAttacker::CapturingWalking()
{
if(!attacked_goal)
{
// Nach Hause gehen
<API key>();
return;
}
RTTR_Assert(dynamic_cast<nobMilitary*>(attacked_goal));
MapPoint attFlagPos = attacked_goal->GetFlag()->GetPos();
if(pos == attacked_goal->GetPos())
{
if(building)
building->SoldierLost(this);
<API key>();
if(ship_obj_id)
CancelAtShip();
// mich von der Karte tilgen-
gwg->RemoveFigure(this, pos);
// Das ist nun mein neues zu Hause
building = attacked_goal;
attacked_goal->AddActiveSoldier(this);
// Ein erobernder Soldat weniger
if(attacked_goal->GetBuildingType() >= BLD_BARRACKS && attacked_goal->GetBuildingType() <= BLD_FORTRESS)
{
RTTR_Assert(dynamic_cast<nobMilitary*>(attacked_goal));
nobMilitary* goal = static_cast<nobMilitary*>(attacked_goal);
// If we are still a far-away-capturer at this point, then the building belongs to us and capturing was already finished
if(!goal->IsFarAwayCapturer(this))
{
<API key>();
goal-><API key>();
} else
{
<API key>();
RTTR_Assert(goal->GetPlayer() == player);
}
} else
<API key>();
}
// oder zumindest schonmal an der Flagge?
else if(pos == attFlagPos)
{
StartWalking(Direction::NORTHWEST);
RTTR_Assert(attacked_goal->GetPlayer() == player); // Assumed by the call below
static_cast<nobMilitary*>(attacked_goal)->NeedOccupyingTroops();
} else
{
if(!building)
{
if(attacked_goal)
{
nobMilitary* attackedBld = static_cast<nobMilitary*>(attacked_goal);
<API key>();
// Evtl. neue Besatzer rufen
RTTR_Assert(attackedBld->GetPlayer() == player);
attackedBld->NeedOccupyingTroops();
}
// Ggf. Schiff Bescheid sagen (Schiffs-Angreifer)
if(ship_obj_id)
CancelAtShip();
// Rumirren
state = STATE_FIGUREWORK;
StartWandering();
Wander();
return;
}
// weiter zur Flagge laufen
unsigned char dir = gwg->FindHumanPath(pos, attFlagPos, 10, true);
if(dir == 0xFF)
{
// auweia, es wurde kein Weg mehr gefunden
// Evtl. neue Besatzer rufen
RTTR_Assert(attacked_goal->GetPlayer() == player); // Assumed by the call below
static_cast<nobMilitary*>(attacked_goal)->NeedOccupyingTroops();
// Nach Hause gehen
<API key>();
} else
StartWalking(Direction(dir));
}
}
void nofAttacker::<API key>()
{
// No need to notify the goal
attacked_goal = NULL;
switch(state)
{
default: break;
case <API key>:
{
// nach Hause gehen
<API key>();
}
break;
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case STATE_MEETENEMY:
case STATE_FIGHTING:
case <API key>:
case <API key>: // wartet im Hafen auf das ankommende Schiff
case <API key>: // befindet sich auf dem Schiff auf dem Weg zum Zielpunkt
{
// gehen die nicht rein)
attacked_goal = NULL;
}
break;
}
}
void nofAttacker::StartSucceeding(const MapPoint pt, const unsigned short new_radius, Direction dir)
{
state = <API key>;
Direction old_dir = GetCurMoveDir();
attacked_goal->SendSuccessor(this->pos, radius, old_dir);
// Und schonmal loslaufen, da wir ja noch stehen
MissAttackingWalk();
// Neuen Radius speichern
radius = new_radius;
}
void nofAttacker::LetsFight(<API key>* other)
{
RTTR_Assert(!huntingDefender);
// wir werden jetzt "gejagt"
should_haunted = false;
huntingDefender = other;
}
void nofAttacker::<API key>()
{
RTTR_Assert(huntingDefender);
huntingDefender = NULL;
}
void nofAttacker::<API key>()
{
state = <API key>;
// Blockevent anmelden
blocking_event = GetEvMgr().AddEvent(this, BLOCK_OFFSET, 5);
}
void nofAttacker::HandleDerivedEvent(const unsigned )
{
if(state == <API key>)
{
// Figuren stoppen
gwg->StopOnRoads(pos);
blocking_event = NULL;
}
}
bool nofAttacker::IsBlockingRoads() const
{
if(state != <API key>)
return false;
return blocking_event == NULL;
}
Sagt den verschiedenen Zielen Bescheid, dass wir doch nicht mehr kommen können
void nofAttacker::<API key>()
{
nofActiveSoldier::<API key>();
<API key>();
// Ziel Bescheid sagen, falls es das noch gibt
if(attacked_goal)
<API key>();
RTTR_Assert(attacked_goal == NULL);
}
void nofAttacker::<API key>()
{
// If state == <API key> then we probably just lost the fight against the defender, otherwise there must either
// be no defender or he is not waiting for us
RTTR_Assert(state == <API key> || !attacked_goal->GetDefender()
|| (attacked_goal->GetDefender()->GetAttacker() != this && attacked_goal->GetDefender()->GetEnemy() != this));
// No defender should be chasing us at this point
for(std::list<<API key>*>::const_iterator it = attacked_goal-><API key>().begin();
it != attacked_goal-><API key>().end(); ++it)
RTTR_Assert((*it)->GetAttacker() != this);
attacked_goal->UnlinkAggressor(this);
attacked_goal = NULL;
}
Startet den Angriff am Landungspunkt vom Schiff
void nofAttacker::<API key>(const MapPoint shipPos, const unsigned ship_id)
{
pos = this->shipPos = shipPos;
this->ship_obj_id = ship_id;
state = <API key>;
on_ship = false;
// Normal weiterlaufen
MissAttackingWalk();
}
Sea attacker enters harbor and finds no shipping route or no longer has a valid target: set state,target,goal,building to 0 to avoid
future problems (and add to harbor inventory)
void nofAttacker::<API key>()
{
<API key>();
RTTR_Assert(!huntingDefender);
AbrogateWorkplace();
goal_ = NULL;
state = STATE_FIGUREWORK;
}
Sagt Schiffsangreifern, dass sie mit dem Schiff zurück fahren
void nofAttacker::StartReturnViaShip(noShip& ship)
{
if(pos.isValid())
{
// remove us from where we are, so nobody will ever draw us :)
gwg->RemoveFigure(this, pos);
pos = MapPoint::Invalid(); // Similar to start ship journey
ship.AddReturnedAttacker(this);
} else
{
// If pos is not valid, then we are still on the ship!
// This can happen, if the ship cannot reach its target
RTTR_Assert(state == <API key>);
RTTR_Assert(helpers::contains(ship.GetFigures(), this));
<API key>();
}
goal_ = building;
state = STATE_FIGUREWORK;
fs = FS_GOTOGOAL;
on_ship = true;
ship_obj_id = 0;
}
notify sea attackers that they wont return home
void nofAttacker::HomeHarborLost()
{
goal_ = NULL; // this in combination with telling the home building that the soldier is lost should work just fine
}
Für Schiffsangreifer: Sagt dem Schiff Bescheid, dass wir nicht mehr kommen
void nofAttacker::CancelAtShip()
{
// Alle Figuren durchgehen
std::vector<noBase*> figures = gwg-><API key>(shipPos);
for(std::vector<noBase*>::iterator it = figures.begin(); it != figures.end(); ++it)
{
if((*it)->GetObjId() == ship_obj_id)
{
noShip* ship = static_cast<noShip*>(*it);
ship-><API key>();
break;
}
}
ship_obj_id = 0;
}
void nofAttacker::<API key>()
{
if(huntingDefender)
{
RTTR_Assert(huntingDefender->GetAttacker() == this);
huntingDefender->AttackerLost();
huntingDefender = NULL;
}
}
Behandelt das Laufen zurück zum Schiff
void nofAttacker::<API key>()
{
if(!building)
{
// Rumirren
state = STATE_FIGUREWORK;
StartWandering();
Wander();
// Schiff Bescheid sagen
CancelAtShip();
return;
}
// Sind wir schon im Schiff?
if(pos == shipPos)
{
// Alle Figuren durchgehen
std::vector<noBase*> figures = gwg-><API key>(pos);
for(std::vector<noBase*>::iterator it = figures.begin(); it != figures.end(); ++it)
{
if((*it)->GetObjId() == ship_obj_id)
{
StartReturnViaShip(static_cast<noShip&>(**it));
return;
}
}
RTTR_Assert(false);
ship_obj_id = 0;
// Kein Schiff gefunden? Das kann eigentlich nich sein!
// Dann rumirren
StartWandering();
state = STATE_FIGUREWORK;
Wander();
return;
}
unsigned char dir = gwg->FindHumanPath(pos, shipPos, <API key>);
// oder finden wir gar keinen Weg mehr?
if(dir == 0xFF)
{
// Kein Weg gefunden --> Rumirren
StartWandering();
state = STATE_FIGUREWORK;
Wander();
building->SoldierLost(this);
// Und dem Schiff
CancelAtShip();
}
// oder ist alles ok? :)
else
{
// weiterlaufen
StartWalking(Direction(dir));
}
}
Bricht einen Seeangriff ab
void nofAttacker::CancelSeaAttack()
{
<API key>();
RTTR_Assert(!huntingDefender);
Abrogate();
}
The derived classes regain control after a fight of nofActiveSoldier
void nofAttacker::FreeFightEnded()
{
nofActiveSoldier::FreeFightEnded();
// Continue with normal walking towards our goal
state = <API key>;
}
Try to start capturing although he is still far away from the destination
Returns true if successful
bool nofAttacker::<API key>(nobMilitary* dest)
{
// Are we already walking to the destination?
if(state == <API key> || state == STATE_MEETENEMY || state == <API key> || state == STATE_FIGHTING)
{
// Not too far away?
if(gwg->CalcDistance(pos, dest->GetPos()) < <API key>)
return true;
}
return false;
} |
package jmedialayer.backends.awt;
import jmedialayer.backends.Backend;
import jmedialayer.backends.ResourcePromise;
import jmedialayer.graphics.Bitmap32;
import jmedialayer.graphics.G1;
import jmedialayer.input.Input;
import jmedialayer.input.Keys;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
public class AwtBackend extends Backend {
private final int width;
private final int height;
JFrame frame = new JFrame("jmedialayer");
BufferedImage front;
BufferedImage image;
Graphics2D frontg;
Graphics2D g;
boolean[] keys = new boolean[KeyEvent.KEY_LAST];
public AwtBackend(int width, int height) {
this.width = width;
this.height = height;
init();
}
public AwtBackend() {
this(960, 544);
}
private void init() {
front = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
frontg = front.createGraphics();
g = image.createGraphics();
JLabel label = new JLabel(new ImageIcon(front));
label.setSize(width, height);
frame.add(label);
//frame.setSize(width, height);
frame.pack();
frame.setResizable(false);
frame.<API key>(JFrame.EXIT_ON_CLOSE);
frame.<API key>(null);
frame.setVisible(true);
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
}
@Override
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode() & 0x3FF] = true;
}
@Override
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode() & 0x3FF] = false;
}
});
frame.getContentPane().setBackground(Color.black);
}
@Override
public int getNativeWidth() {
return width;
}
@Override
public int getNativeHeight() {
return height;
}
static private int rgbaToBgra(int rgba) {
return (rgba & 0xFF00FF00) | ((rgba >> 16) & 0xFF) | ((rgba & 0xFF) << 16);
}
@Override
protected G1 createG1() {
return new G1() {
@Override
public void updateBitmap(Bitmap32 bmp) {
final int minwidth = Math.min(bmp.width, width);
final int minheight = Math.min(bmp.height, height);
final int image_width = image.getWidth();
final int[] bmp_data = bmp.data;
final int bmp_width = bmp.width;
final int[] data = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
int ioffset = 0;
int ooffset = 0;
for (int y = 0; y < minheight; y++) {
for (int x = 0; x < minwidth; x++) data[ooffset + x] = rgbaToBgra(bmp_data[ioffset + x]);
ioffset += bmp_width;
ooffset += image_width;
}
frontg.setComposite(AlphaComposite.Src);
frontg.drawImage(image, 0, 0, null);
frame.repaint();
}
};
}
@Override
protected Input createInput() {
return new Input() {
@Override
public boolean isPressing(Keys key) {
switch (key) {
case UP:
return keys[KeyEvent.VK_UP];
case DOWN:
return keys[KeyEvent.VK_DOWN];
case LEFT:
return keys[KeyEvent.VK_LEFT];
case RIGHT:
return keys[KeyEvent.VK_RIGHT];
case START:
return keys[KeyEvent.VK_ENTER];
}
return false;
}
};
}
@Override
protected void waitNextFrame() {
super.waitNextFrame();
}
@Override
protected void preEnd() {
frame.setVisible(false);
frame.dispose();
}
@Override
public ResourcePromise<Bitmap32> loadBitmap32(String path) {
return _loadBitmap32Sync(path);
}
} |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Fri Dec 04 23:17:21 GMT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title><API key>.ShardsRepeat (Solr 5.4.0 API)</title>
<meta name="date" content="2015-12-04">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="<API key>.ShardsRepeat (Solr 5.4.0 API)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/<API key>.ShardsRepeat.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/apache/solr/<API key>.ShardsFixed.html" title="annotation in org.apache.solr"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/apache/solr/<API key>.ShardsRepeatRule.html" title="class in org.apache.solr"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/apache/solr/<API key>.ShardsRepeat.html" target="_top">Frames</a></li>
<li><a href="<API key>.ShardsRepeat.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Required | </li>
<li><a href="#<API key>">Optional</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#<API key>">Element</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">org.apache.solr</div>
<h2 title="Annotation Type <API key>.ShardsRepeat" class="title">Annotation Type <API key>.ShardsRepeat</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre><a href="http://download.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true" title="class or interface in java.lang.annotation">@Retention</a>(<a href="http://download.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true
<a href="http://download.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true" title="class or interface in java.lang.annotation">@Target</a>(<a href="http://download.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true
public static @interface <span class="strong"><API key>.ShardsRepeat</span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="<API key>">
</a>
<h3>Optional Element Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Optional Element Summary table, listing optional elements, and an explanation">
<caption><span>Optional Elements</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Optional Element and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../org/apache/solr/<API key>.ShardsRepeat.html#max()">max</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../org/apache/solr/<API key>.ShardsRepeat.html#min()">min</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="<API key>">
</a>
<h3>Element Detail</h3>
<a name="min()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>min</h4>
<pre>public abstract int min</pre>
<dl>
<dt>Default:</dt>
<dd>1</dd>
</dl>
</li>
</ul>
<a name="max()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>max</h4>
<pre>public abstract int max</pre>
<dl>
<dt>Default:</dt>
<dd>3</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/<API key>.ShardsRepeat.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/apache/solr/<API key>.ShardsFixed.html" title="annotation in org.apache.solr"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/apache/solr/<API key>.ShardsRepeatRule.html" title="class in org.apache.solr"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/apache/solr/<API key>.ShardsRepeat.html" target="_top">Frames</a></li>
<li><a href="<API key>.ShardsRepeat.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Required | </li>
<li><a href="#<API key>">Optional</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#<API key>">Element</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html> |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Tue Feb 21 18:03:00 GMT 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>gate.sgml (GATE JavaDoc)</title>
<meta name="date" content="2017-02-21">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../gate/sgml/package-summary.html" target="classFrame">gate.sgml</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="Sgml2Xml.html" title="class in gate.sgml" target="classFrame">Sgml2Xml</a></li>
</ul>
</div>
</body>
</html> |
#!/usr/bin/env sh
# Terminate already running bar instances
killall -q polybar
# Wait until the processes have been shut down
while pgrep -u $UID -x polybar >/dev/null; do sleep 1; done
# Launch bar1 and bar2
polybar example & |
from odoo import api
from odoo import fields
from odoo import models
class booking_settings(models.Model):
_name="booking.settings"
post_booking_time = fields.Integer('Post Booking Time')
pre_booking_time = fields.Integer('Pre Booking Time')
# Example post booking is 30 <integer> minutes <static text>
# That means when the system does the "check" for the booking of
# stakeholders, it will check whether they have any event during that duration
# + the post booking time and pre booking time
# with 4.15, thus employee A is unavailable
# Default Pre and Post booking time is 0 minutes. |
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "top_talkers"
local top_asn_intf = {}
if (ntop.isPro()) then
package.path = dirs.installdir .. "/pro/scripts/lua/modules/top_scripts/?.lua;" .. package.path
local new = require("top_aggregate")
if (type(new) ~= "table") then new = {} end
-- Add pro methods to local method table
for k,v in pairs(new) do
top_asn_intf[k] = v
end
end
local function getTopAS(ifid, ifname)
return <API key>(ifid, ifname, 10, true, false,
nil, nil, top_asn_intf.key,
top_asn_intf.JSONkey, nil, true, nil, top_asn_intf.uniqueKey)
end
local function getTopASBy(ifid, ifname, filter_col, filter_val)
local lastdump_key = getLastDumpKey(top_asn_intf.uniqueKey, filter_col, filter_val)
return <API key>(ifid, ifname, 10, true, false,
filter_col, filter_val, top_asn_intf.key,
top_asn_intf.JSONkey, nil, true, nil, lastdump_key)
end
local function getTopASClean(ifid, ifname, param)
top = getCurrentTopGroups(ifid, ifname, 5, false, false,
nil, nil, top_asn_intf.key,
top_asn_intf.JSONkey, true, param, top_asn_intf.uniqueKey)
section_beginning = string.find(top, '%[')
if (section_beginning == nil) then
return("[ ]\n")
else
return(string.sub(top, section_beginning))
end
end
local function <API key>(tblarray, arithOp)
local ret = {}
local outer_cnt = 1
local num_glob = 1
for _,tbl in pairs(tblarray) do
for _,outer in pairs(tbl) do
if (ret[outer_cnt] == nil) then ret[outer_cnt] = {} end
for key, value in pairs(outer) do
for _,record in pairs(value) do
local found = false
if (ret[outer_cnt][key] == nil) then ret[outer_cnt][key] = {} end
for _,el in pairs(ret[outer_cnt][key]) do
if (found == false and el["address"] == record["address"]) then
el["value"] = arithOp(el["value"], record["value"])
found = true
end
end
if (found == false) then
ret[outer_cnt][key][num_glob] = record
num_glob = num_glob + 1
end
end
end
end
end
return ret
end
local function printTopASTable(tbl)
local rsp = "{\n"
for i,v in pairs(tbl) do
local outouterlooped = 0
for dk,dv in pairs(v) do
rsp = rsp..'"'..dk..'": [\n'
local keys = getKeys(dv, "value")
local outerlooped = 0
for tv,tk in pairsByKeys(keys, rev) do
rv = dv[tk]
rsp = rsp.."{ "
local looped = 0
for k,v in pairs(rv) do
rsp = rsp..'"'..k..'": '
if (k == "value") then
rsp = rsp..tostring(v)
else
rsp = rsp..'"'..v..'"'
end
rsp = rsp..", "
looped = looped + 1
end
if (looped > 0) then
rsp = string.sub(rsp, 1, -3)
end
rsp = rsp.."},\n"
outerlooped = outerlooped + 1
end
if (outerlooped > 0) then
rsp = string.sub(rsp, 1, -3)
end
rsp = rsp.."],\n"
outouterlooped = outouterlooped + 1
end
if (outouterlooped > 0) then
rsp= string.sub(rsp, 1, -3)
end
end
rsp = rsp.."\n}"
return rsp
end
local function <API key>(table, wantedDir, add_vlan)
local elements = ""
-- For each VLAN, get ASs and concatenate them
for i,vlan in pairs(table["vlan"]) do
local vlanid = vlan["label"]
local vlanname = vlan["name"]
-- XXX asn is an array of (senders, receivers) pairs?
for i2,asnpair in pairs(vlan[top_asn_intf.JSONkey]) do
-- asnpair is { "senders": [...], "receivers": [...] }
for k2,direction in pairs(asnpair) do
-- direction is "senders": [...] or "receivers": [...]
if (k2 ~= wantedDir) then goto continue end
-- scan ASs
for i2,asn in pairs(direction) do
-- asn is { "label": ..., "value": ..., "url": ... }
elements = elements.."{ "
local n_el = 0
for k3,v3 in pairs(asn) do
elements = elements..'"'..k3..'": '
if (k3 == "value") then
elements = elements..tostring(v3)
else
elements = elements..'"'..v3..'"'
end
elements = elements..", "
n_el = n_el + 1
end
if (add_vlan ~= nil) then
elements = elements..'"vlanm": "'..vlanname..'", '
elements = elements..'"vlan": "'..vlanid..'", '
end
if (n_el ~= 0) then
elements = string.sub(elements, 1, -3)
end
elements = elements.." },\n"
end
::continue::
end
end
end
return elements
end
local function printTopASFromTable(table, add_vlan)
if (table == nil or table["vlan"] == nil) then return "[ ]\n" end
local elements = "{\n"
elements = elements..'"senders": [\n'
local result = <API key>(table, "senders", add_vlan)
if (result ~= "") then
result = string.sub(result, 1, -3) --remove comma
end
elements = elements..result
elements = elements.."],\n"
elements = elements..'"receivers": [\n'
result = <API key>(table, "receivers", add_vlan)
if (result ~= "") then
result = string.sub(result, 1, -3) --remove comma
end
elements = elements..result
elements = elements.."]\n"
elements = elements.."}\n"
return elements
end
local function getTopASFromJSON(content, add_vlan)
if(content == nil) then return("[ ]\n") end
local table = json.decode(content, 1)
local rsp = printTopASFromTable(table, add_vlan)
if (rsp == nil or rsp == "") then return "[ ]\n" end
return rsp
end
local function getHistoricalTopAS(ifid, ifname, epoch, add_vlan)
if (epoch == nil) then
return("[ ]\n")
end
return getTopASFromJSON(ntop.getMinuteSampling(ifid, tonumber(epoch)), add_vlan)
end
top_asn_intf.name = "ASN"
top_asn_intf.infoScript = "hosts_stats.lua"
top_asn_intf.infoScriptKey = "asn"
top_asn_intf.key = "asn"
top_asn_intf.JSONkey = "asn"
top_asn_intf.uniqueKey = "top_asn"
top_asn_intf.getTop = getTopAS
top_asn_intf.getTopBy = getTopASBy
top_asn_intf.getTopClean = getTopASClean
top_asn_intf.getTopFromJSON = getTopASFromJSON
top_asn_intf.printTopTable = printTopASTable
top_asn_intf.getHistoricalTop = getHistoricalTopAS
top_asn_intf.topSectionInTableOp = <API key>
top_asn_intf.numLevels = 2
return top_asn_intf |
package org.mc.bridge;
public abstract class AbstractRoad {
AbstractCar aCar;
public void run(){
}
} |
{-# LANGUAGE UnicodeSyntax #-}
-- $ ghc -o Haskell.hs
-- $ ghci --version
-- The Glorious Glasgow Haskell Compilation System, version 8.2.1
:: Foldable => ( -> -> ) -> -> ->
= foldr
:: Num => -> ->
= (*)
:: Int -> Int
= 1 [ 1 .. ]
main :: IO ()
main = do
let = print
in $ 5
-- a -> a |
#include <stdint.h>
#include <retro_miscellaneous.h>
#include <lists/file_list.h>
#include <lists/string_list.h>
#include <file/file_path.h>
#include <compat/strl.h>
#include <string/stdstring.h>
#ifdef HAVE_NETWORKING
#include <net/net_http.h>
#endif
#include "menu_driver.h"
#include "menu_networking.h"
#include "menu_cbs.h"
#include "menu_entries.h"
#include "../core_info.h"
#include "../configuration.h"
#include "../file_path_special.h"
#include "../msg_hash.h"
#include "../tasks/task_file_transfer.h"
#include "../tasks/tasks_internal.h"
unsigned print_buf_lines(file_list_t *list, char *buf,
const char *label, int buf_size,
enum msg_file_type type, bool append, bool extended)
{
char c;
unsigned count = 0;
int i, j = 0;
char *line_start = buf;
if (!buf || !buf_size)
return 0;
for (i = 0; i < buf_size; i++)
{
size_t ln;
const char *core_date = NULL;
const char *core_crc = NULL;
const char *core_pathname = NULL;
struct string_list *str_list = NULL;
/* The end of the buffer, print the last bit */
if (*(buf + i) == '\0')
break;
if (*(buf + i) != '\n')
continue;
/* Found a line ending, print the line and compute new line_start */
/* Save the next char */
c = *(buf + i + 1);
/* replace with \0 */
*(buf + i + 1) = '\0';
/* We need to strip the newline. */
ln = strlen(line_start) - 1;
if (line_start[ln] == '\n')
line_start[ln] = '\0';
str_list = string_split(line_start, " ");
if (str_list->elems[0].data)
core_date = str_list->elems[0].data;
if (str_list->elems[1].data)
core_crc = str_list->elems[1].data;
if (str_list->elems[2].data)
core_pathname = str_list->elems[2].data;
(void)core_date;
(void)core_crc;
if (extended)
{
if (append)
{
if (<API key>(list, core_pathname, "",
<API key>, type, 0, 0))
count++;
}
else
{
<API key>(list, core_pathname, "",
<API key>, type, 0, 0);
count++;
}
}
else
{
if (append)
{
if (<API key>(list, line_start, label,
<API key>, type, 0, 0))
count++;
}
else
{
<API key>(list, line_start, label,
<API key>, type, 0, 0);
count++;
}
}
switch (type)
{
case <API key>:
{
settings_t *settings = config_get_ptr();
if (settings)
{
char display_name[255];
char core_path[PATH_MAX_LENGTH];
char *last = NULL;
display_name[0] = core_path[0] = '\0';
<API key>(
core_path,
settings->paths.path_libretro_info,
(extended && !string_is_empty(core_pathname))
? core_pathname : line_start,
sizeof(core_path));
<API key>(core_path);
last = (char*)strrchr(core_path, '_');
if (!string_is_empty(last))
{
if (<API key>(last, "_libretro", 9))
*last = '\0';
}
strlcat(core_path,
file_path_str(<API key>),
sizeof(core_path));
if (
path_is_valid(core_path)
&& <API key>(
core_path, display_name, sizeof(display_name)))
<API key>(list, j, display_name);
}
}
break;
default:
case FILE_TYPE_NONE:
break;
}
j++;
string_list_free(str_list);
/* Restore the saved char */
*(buf + i + 1) = c;
line_start = buf + i + 1;
}
if (append)
<API key>(list);
/* If the buffer was completely full, and didn't end
* with a newline, just ignore the partial last line. */
return count;
}
void <API key>(retro_task_t *task,
void *task_data, void *user_data, const char *err)
{
#ifdef HAVE_NETWORKING
char subdir_path[PATH_MAX_LENGTH];
<API key> *data = (<API key>*)task_data;
file_transfer_t *state = (file_transfer_t*)user_data;
subdir_path[0] = '\0';
if (!data || err)
goto finish;
if (!string_is_empty(data->data))
memcpy(subdir_path, data->data, data->len * sizeof(char));
subdir_path[data->len] = '\0';
finish:
if (!err && !strstr(subdir_path, file_path_str(<API key>)))
{
char parent_dir[PATH_MAX_LENGTH];
parent_dir[0] = '\0';
<API key>(parent_dir,
state->path, sizeof(parent_dir));
/*<API key>(parent_dir, NULL,
subdir_path, 0, 0, 0, <API key>);*/
}
if (data)
{
if (data->data)
free(data->data);
free(data);
}
if (user_data)
free(user_data);
#endif
}
void cb_net_generic(retro_task_t *task,
void *task_data, void *user_data, const char *err)
{
#ifdef HAVE_NETWORKING
bool refresh = false;
<API key> *data = (<API key>*)task_data;
file_transfer_t *state = (file_transfer_t*)user_data;
menu_handle_t *menu = menu_driver_get_ptr();
if (!menu)
goto finish;
if (menu->core_buf)
free(menu->core_buf);
menu->core_buf = NULL;
menu->core_len = 0;
if (!data || err)
goto finish;
menu->core_buf = (char*)malloc((data->len+1) * sizeof(char));
if (!menu->core_buf)
goto finish;
if (!string_is_empty(data->data))
memcpy(menu->core_buf, data->data, data->len * sizeof(char));
menu->core_buf[data->len] = '\0';
menu->core_len = data->len;
finish:
refresh = true;
menu_entries_ctl(<API key>, &refresh);
if (data)
{
if (data->data)
free(data->data);
free(data);
}
if (!err && !strstr(state->path, file_path_str(<API key>)))
{
char *parent_dir = (char*)malloc(PATH_MAX_LENGTH * sizeof(char));
char *parent_dir_encoded = (char*)malloc(PATH_MAX_LENGTH * sizeof(char));
file_transfer_t *transf = NULL;
parent_dir[0] = '\0';
parent_dir_encoded[0] = '\0';
<API key>(parent_dir,
state->path, PATH_MAX_LENGTH * sizeof(char));
strlcat(parent_dir,
file_path_str(<API key>),
PATH_MAX_LENGTH * sizeof(char));
transf = (file_transfer_t*)malloc(sizeof(*transf));
transf->enum_idx = MSG_UNKNOWN;
strlcpy(transf->path, parent_dir, sizeof(transf->path));
<API key>(parent_dir_encoded, parent_dir, PATH_MAX_LENGTH * sizeof(char));
<API key>(parent_dir_encoded, true,
"index_dirs", <API key>, transf);
free(parent_dir);
free(parent_dir_encoded);
}
if (state)
free(state);
#endif
} |
package org.workcraft.dom.visual;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.LinkedList;
import org.workcraft.plugins.shared.<API key>;
public class RenderedText {
private final double spacingRatio = <API key>.getLineSpacing();
private final String text;
private final Font font;
private final Positioning positioning;
private final double xOffset;
private final double yOffset;
private final LinkedList<GlyphVector> glyphVectors;
private final Rectangle2D boundingBox;
private final double spacing;
public RenderedText(String text, Font font, Positioning positioning, Point2D offset) {
this.text = text;
this.font = font;
this.positioning = positioning;
this.xOffset = offset.getX();
this.yOffset = offset.getY();
Rectangle2D textBounds = null;
glyphVectors = new LinkedList<GlyphVector>();
String[] lines = text.split("\\|");
for (String line: lines) {
final FontRenderContext context = new FontRenderContext(AffineTransform.getScaleInstance(1000.0, 1000.0), true, true);
final GlyphVector glyphVector = font.createGlyphVector(context, line.trim());
glyphVectors.add(glyphVector);
Rectangle2D lineBounds = glyphVector.getVisualBounds();
if (textBounds != null) {
textBounds = BoundingBoxHelper.move(textBounds, 0.0, -lineBounds.getHeight());
}
textBounds = BoundingBoxHelper.union(textBounds, lineBounds);
}
spacing = (lines.length < 2) ? 0.0 : (spacingRatio * textBounds.getHeight() / (lines.length - 1));
textBounds = BoundingBoxHelper.transform(textBounds, AffineTransform.getScaleInstance(1.0, 1.0 + spacingRatio));
double x = xOffset + positioning.xOffset + 0.5 * positioning.xSign * textBounds.getWidth() - textBounds.getCenterX();
double y = yOffset + positioning.yOffset + 0.5 * positioning.ySign * textBounds.getHeight() - textBounds.getCenterY();
boundingBox = BoundingBoxHelper.move(textBounds, x, y);
}
public boolean isDifferent(String text, Font font, Positioning positioning, Point2D offset) {
if (text == null) {
text = "";
}
return !text.equals(this.text) || !font.equals(this.font) || positioning != this.positioning
|| offset.getX() != this.xOffset || offset.getY() != this.yOffset;
}
public void draw(Graphics2D g) {
draw(g, Alignment.LEFT);
}
public void draw(Graphics2D g, Alignment alignment) {
g.setFont(font);
float y = (float) boundingBox.getMinY();
for (GlyphVector glyphVector: glyphVectors) {
final Rectangle2D lineBoundingBox = glyphVector.getVisualBounds();
double xMargin = 0.0;
switch (alignment) {
case CENTER :
xMargin = (boundingBox.getWidth() - lineBoundingBox.getWidth()) / 2.0;
break;
case RIGHT:
xMargin = boundingBox.getWidth() - lineBoundingBox.getWidth();
break;
default:
xMargin = 0.0;
}
double x = boundingBox.getX() - lineBoundingBox.getX() + xMargin * (1.0 - positioning.xSign);
y += lineBoundingBox.getHeight();
g.drawGlyphVector(glyphVector, (float) x, y);
y += spacing;
}
}
public boolean hitTest(Point2D point) {
return boundingBox.contains(point);
}
public Rectangle2D getBoundingBox() {
return boundingBox;
}
public boolean isEmpty() {
return (text == null) || text.isEmpty();
}
} |
title: 3px
date: 2016-07-18
tags: [CSS]
categories: Static
`li`li`3px`
`a``16px`
css
a{
font-size: 0;
}
img{
vertical-align: bottom;
}
`li` |
package org.wandora.application.tools.extractors.word;
import java.util.ArrayList;
import java.util.List;
import uk.ac.shef.wit.simmetrics.similaritymetrics.<API key>;
import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein;
import uk.ac.shef.wit.simmetrics.similaritymetrics.Jaro;
import org.apache.commons.collections.bidimap.DualHashBidiMap;
import uk.ac.shef.wit.simmetrics.similaritymetrics.JaroWinkler;
/**
*
* @author Eero Lehtonen <eero.lehtonen@gripstudios.com>
*/
class <API key> extends WordConfiguration{
private float THRESHOLD;
private <API key> STRING_METRIC;
private final DualHashBidiMap STRING_METRICS;
<API key>() {
super();
setAssociateScore(true);
THRESHOLD = 0.5f;
STRING_METRICS = new DualHashBidiMap();
STRING_METRICS.put("Levenshtein", new Levenshtein());
STRING_METRICS.put("Jaro", new Jaro());
STRING_METRICS.put("Jaro Winkler", new JaroWinkler());
STRING_METRIC = new Levenshtein();
}
protected float getThreshold(){
return THRESHOLD;
}
protected void setThreshold(float f){
THRESHOLD = f;
}
protected void setStringMetric(String s){
STRING_METRIC = (<API key>) STRING_METRICS.get(s);
}
protected <API key> getStringMetric(){
return STRING_METRIC;
}
protected String getStringMetricName(){
return (String)STRING_METRICS.getKey(STRING_METRIC);
}
protected List<String> <API key>(){
List<String> l = new ArrayList();
l.addAll(STRING_METRICS.keySet());
return l;
}
} |
# Peer and Content Routing
DHTs (Distributed Hash Tables) are one of the most common building blocks used when creating P2P networks. However, the name doesn't make justice to all the benefits it brings and putting the whole set of features in one box has proven to be limiting when we want to integrate multiple pieces together. With this in mind, we've come up with a new definition for what a DHT offers: Peer Routing and Content Routing.
Peer Routing is the category of modules that offer a way to find other peers in the network by intentionally issuing queries, iterative or recursive, until a Peer is found or the closest Peers, given the Peer Routing algorithm strategy are found.
Content Routing is the category of modules that offer a way to find where content lives in the network, it works in two steps: 1) Peers provide (announce) to the network that they are holders of specific content (multihashes) and 2) Peers issue queries to find where that content lives. A Content Routing mechanism could be as complex as a Kademlia DHT or a simple registry somewhere in the network.
# 1. Using Peer Routing to find other peers
This example builds on top of the [Protocol and Stream Muxing](../<API key>). We need to install `libp2p-kad-dht`, go ahead and `npm install libp2p-kad-dht`. If you want to see the final version, open [1.js](./1.js).
First, let's update our bundle to support Peer Routing and Content Routing.
JavaScript
class MyBundle extends libp2p {
constructor (peerInfo) {
const modules = {
transport: [new TCP()],
connection: {
muxer: [Multiplex],
crypto: [SECIO]
},
// we add the DHT module that will enable Peer and Content Routing
DHT: KadDHT
}
super(modules, peerInfo)
}
}
Once that is done, we can use the createNode function we developed in the previous example to create 3 nodes. Connect node 1 to node 2 and node 2 to node 3. We will use node 2 as a way to find the whereabouts of node 3
JavaScript
const node1 = nodes[0]
const node2 = nodes[1]
const node3 = nodes[2]
parallel([
(cb) => node1.dial(node2.peerInfo, cb),
(cb) => node2.dial(node3.peerInfo, cb),
// Set up of the cons might take time
(cb) => setTimeout(cb, 100)
], (err) => {
if (err) { throw err }
node1.peerRouting.findPeer(node3.peerInfo.id, (err, peer) => {
if (err) { throw err }
console.log('Found it, multiaddrs are:')
peer.multiaddrs.forEach((ma) => console.log(ma.toString()))
})
})
You should see the output being something like:
Bash
> node 1.js
Found it, multiaddrs are:
/ip4/127.0.0.1/tcp/63617/ipfs/<API key>
/ip4/192.168.86.41/tcp/63617/ipfs/<API key>
You have successfully used Peer Routing to find a peer that you were not directly connected. Now all you have to do is to dial to the multiaddrs you discovered.
# 2. Using Content Routing to find providers of content
With Content Routing, you can create records that are stored in multiple points in the network, these records can be resolved by you or other peers and they act as memos or rendezvous points. A great usage of this feature is to support discovery of content, where one node holds a file and instead of using a centralized tracker to inform other nodes that it holds that file, it simply puts a record in the network that can be resolved by other peers. Peer Routing and Content Routing are commonly known as Distributed Hash Tables, DHT.
You can find this example completed in [2.js](./2.js), however as you will see it is very simple to update the previous example.
Instead of calling `peerRouting.findPeer`, we will use `contentRouting.provide` and `contentRouting.findProviders`.
JavaScript
node1.contentRouting.provide(cid, (err) => {
if (err) { throw err }
console.log('Node %s is providing %s', node1.peerInfo.id.toB58String(), cid.toBaseEncodedString())
node3.contentRouting.findProviders(cid, 5000, (err, providers) => {
if (err) { throw err }
console.log('Found provider:', providers[0].id.toB58String())
})
})
The output of your program should look like:
bash
> node 2.js
Node <API key> is providing <API key>
Found provider: <API key>
That's it, now you know how to find peers that have pieces of information that interest you!
# 3. Future Work
Currently, the only mechanisms for Peer and Content Routing come from the DHT, however we do have the intention to support:
- Multiple Peer Routing Mechanisms, including ones that do recursive searches (i.e [webrtc-explorer](http:
- Content Routing via PubSub
- Content Routing via centralized index (i.e a tracker) |
#ifndef WIDGET_H
#define WIDGET_H
#include <string>
#include <vector>
#include <boost/make_shared.hpp>
#include <boost/checked_delete.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/signals2.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
namespace ribi {
GUI independent widget class, modeled after the Qt and Wt architure
Name should have been 'Geometry'
struct Widget
{
using Point = boost::geometry::model::d2::point_xy<double>;
using Rect = boost::geometry::model::box<Point>;
Widget(
const Point& top_left = Point(0.0,0.0),
const Point& bottom_right = Point(0.0,0.0)
);
virtual ~Widget() noexcept {}
static Rect CreateRect(
const double left,
const double top,
const double width,
const double height
) noexcept;
static Rect CreateRect(
const Point& top_left,
const Point& bottom_right
) noexcept;
double GetBottom() const noexcept;
const Rect& GetGeometry() const noexcept { return m_geometry; }
Rect& GetGeometry() noexcept { return m_geometry; }
double GetHeight() const noexcept;
double GetLeft() const noexcept;
double GetRight() const noexcept;
double GetTop() const noexcept;
static std::string GetVersion() noexcept;
static std::vector<std::string> GetVersionHistory() noexcept;
double GetWidth() const noexcept;
Is the coordinat within the widget its rectangle?
bool IsIn(const double x, const double y) const noexcept;
SetGeometry resizes the Widget and emits an OnResize signal
void SetGeometry(const Rect& geometry) noexcept;
void SetGeometry(const double left, const double top, const double width, const double height) noexcept;
private:
Rect m_geometry;
};
bool operator==(const Widget& lhs, const Widget& rhs) noexcept;
bool operator!=(const Widget& lhs, const Widget& rhs) noexcept;
} //~namespace ribi
#endif // WIDGET_H |
# Glotaran package __init__.py
from . import model, parameter, io # noqa: F401
__version__ = '0.0.10'
ParameterGroup = parameter.ParameterGroup
<API key> = ParameterGroup.from_csv
<API key> = ParameterGroup.from_yaml
<API key> = ParameterGroup.from_yaml_file
from .parse import parser # noqa: E402
read_model_from_yml = parser.load_yml
<API key> = parser.load_yml_file
import pkg_resources # noqa: E402
for entry_point in pkg_resources.iter_entry_points('glotaran.plugins'):
entry_point.load() |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class <API key> extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('ef2016s', function (Blueprint $table) {
$table->text("beneficiarios")->nullable()->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('ef2016s', function (Blueprint $table) {
});
}
} |
package com.nilhcem.bblfr.core.map;
import android.location.Location;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import java.util.List;
import rx.Observable;
import timber.log.Timber;
public class MapUtils {
public static final float HUE_DEFAULT = 25.0f;
private MapUtils() {
throw new <API key>();
}
public static Observable<GoogleMap> <API key>(MapFragment fragment) {
return Observable.create(subscriber -> {
subscriber.onNext(fragment.getMap());
subscriber.onCompleted();
});
}
public static LatLng gpsToLatLng(String gps) {
String[] gpsSplit = gps.split(",");
return new LatLng(Double.parseDouble(gpsSplit[0].trim()), Double.parseDouble(gpsSplit[1].trim()));
}
public static void <API key>(GoogleMap map, List<Marker> markers, Location lastLocation, float zoom) {
map.<API key>(true);
if (lastLocation == null && markers != null && !markers.isEmpty()) {
moveToMarkerBounds(map, markers);
} else if (lastLocation != null) {
LatLng currentLocation = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, zoom));
} else {
Timber.w("Both lastLocation and markers are null");
}
}
public static void moveToMarkerBounds(GoogleMap map, List<Marker> markers) {
// Calculate the bounds of all the markers
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
// Obtain a movement description object
int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
// Move the map
map.moveCamera(cu);
}
} |
<?php
/**
* \file htdocs/core/class/html.formmail.class.php
* \ingroup core
* \brief Fichier de la classe permettant la generation du formulaire html d'envoi de mail unitaire
*/
require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
/**
* Classe permettant la generation du formulaire html d'envoi de mail unitaire
* Usage: $formail = new FormMail($db)
* $formmail->proprietes=1 ou chaine ou tableau de valeurs
* $formmail->show_form() affiche le formulaire
*/
class FormMail
{
var $db;
var $withform;
var $fromname;
var $frommail;
var $replytoname;
var $replytomail;
var $toname;
var $tomail;
var $withsubstit; // Show substitution array
var $withfrom;
var $withto; // Show recipient emails
var $withtofree; // Show free text for recipient emails
var $withtocc;
var $withtoccc;
var $withtopic;
var $withfile; // 0=No attaches files, 1=Show attached files, 2=Can add new attached files
var $withbody;
var $withfromreadonly;
var $withreplytoreadonly;
var $withtoreadonly;
var $withtoccreadonly;
var $withtopicreadonly;
var $withfilereadonly;
var $withdeliveryreceipt;
var $withcancel;
var $withfckeditor;
var $substit=array();
var $param=array();
var $error;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
function __construct($db)
{
$this->db = $db;
$this->withform=1;
$this->withfrom=1;
$this->withto=1;
$this->withtofree=1;
$this->withtocc=1;
$this->withtoccc=0;
$this->witherrorsto=0;
$this->withtopic=1;
$this->withfile=0;
$this->withbody=1;
$this->withfromreadonly=1;
$this->withreplytoreadonly=1;
$this->withtoreadonly=0;
$this->withtoccreadonly=0;
$this-><API key>=0;
$this->withtopicreadonly=0;
$this->withfilereadonly=0;
$this->withbodyreadonly=0;
$this-><API key>=0;
$this->withfckeditor=0;
return 1;
}
/**
* Clear list of attached files in send mail form (stored in session)
*
* @return void
*/
function <API key>()
{
global $conf,$user;
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
// Set tmp user directory
$vardir=$conf->user->dir_output."/".$user->id;
$upload_dir = $vardir.'/temp/';
if (is_dir($upload_dir)) <API key>($upload_dir);
unset($_SESSION["listofpaths"]);
unset($_SESSION["listofnames"]);
unset($_SESSION["listofmimes"]);
}
/**
* Add a file into the list of attached files (stored in SECTION array)
*
* @param string $path Full absolute path on filesystem of file, including file name
* @param string $file Only filename
* @param string $type Mime type
* @return void
*/
function add_attached_files($path,$file,$type)
{
$listofpaths=array();
$listofnames=array();
$listofmimes=array();
if (! empty($_SESSION["listofpaths"])) $listofpaths=explode(';',$_SESSION["listofpaths"]);
if (! empty($_SESSION["listofnames"])) $listofnames=explode(';',$_SESSION["listofnames"]);
if (! empty($_SESSION["listofmimes"])) $listofmimes=explode(';',$_SESSION["listofmimes"]);
if (! in_array($file,$listofnames))
{
$listofpaths[]=$path;
$listofnames[]=$file;
$listofmimes[]=$type;
$_SESSION["listofpaths"]=join(';',$listofpaths);
$_SESSION["listofnames"]=join(';',$listofnames);
$_SESSION["listofmimes"]=join(';',$listofmimes);
}
}
/**
* Remove a file from the list of attached files (stored in SECTION array)
*
* @param string $keytodelete Key in file array
* @return void
*/
function <API key>($keytodelete)
{
$listofpaths=array();
$listofnames=array();
$listofmimes=array();
if (! empty($_SESSION["listofpaths"])) $listofpaths=explode(';',$_SESSION["listofpaths"]);
if (! empty($_SESSION["listofnames"])) $listofnames=explode(';',$_SESSION["listofnames"]);
if (! empty($_SESSION["listofmimes"])) $listofmimes=explode(';',$_SESSION["listofmimes"]);
if ($keytodelete >= 0)
{
unset ($listofpaths[$keytodelete]);
unset ($listofnames[$keytodelete]);
unset ($listofmimes[$keytodelete]);
$_SESSION["listofpaths"]=join(';',$listofpaths);
$_SESSION["listofnames"]=join(';',$listofnames);
$_SESSION["listofmimes"]=join(';',$listofmimes);
//var_dump($_SESSION['listofpaths']);
}
}
/**
* Return list of attached files (stored in SECTION array)
*
* @return array array('paths'=> ,'names'=>, 'mimes'=> )
*/
function get_attached_files()
{
$listofpaths=array();
$listofnames=array();
$listofmimes=array();
if (! empty($_SESSION["listofpaths"])) $listofpaths=explode(';',$_SESSION["listofpaths"]);
if (! empty($_SESSION["listofnames"])) $listofnames=explode(';',$_SESSION["listofnames"]);
if (! empty($_SESSION["listofmimes"])) $listofmimes=explode(';',$_SESSION["listofmimes"]);
return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes);
}
/**
* Show the form to input an email
* this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
*
* @param string $addfileaction Name of action when posting file attachments
* @param string $removefileaction Name of action when removing file attachments
* @return void
*/
function show_form($addfileaction='addfile',$removefileaction='removefile')
{
print $this->get_form($addfileaction,$removefileaction);
}
/**
* Get the form to input an email
* this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
*
* @param string $addfileaction Name of action when posting file attachments
* @param string $removefileaction Name of action when removing file attachments
* @return string Form to show
*/
function get_form($addfileaction='addfile',$removefileaction='removefile')
{
global $conf, $langs, $user, $hookmanager;
$langs->load("other");
$langs->load("mails");
$hookmanager->initHooks(array('formmail'));
$parameters=array(
'addfileaction' => $addfileaction,
'removefileaction'=> $removefileaction
);
$reshook=$hookmanager->executeHooks('getFormMail', $parameters, $this);
if (!empty($reshook))
{
return $hookmanager->resPrint;
}
else
{
$out='';
// Define list of attached files
$listofpaths=array();
$listofnames=array();
$listofmimes=array();
if (! empty($_SESSION["listofpaths"])) $listofpaths=explode(';',$_SESSION["listofpaths"]);
if (! empty($_SESSION["listofnames"])) $listofnames=explode(';',$_SESSION["listofnames"]);
if (! empty($_SESSION["listofmimes"])) $listofmimes=explode(';',$_SESSION["listofmimes"]);
$form=new Form($this->db);
$out.= "\n<!-- Debut form mail -->\n";
if ($this->withform)
{
$out.= '<form method="POST" name="mailform" enctype="multipart/form-data" action="'.$this->param["returnurl"].'">'."\n";
$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'" />';
}
foreach ($this->param as $key=>$value)
{
$out.= '<input type="hidden" id="'.$key.'" name="'.$key.'" value="'.$value.'" />'."\n";
}
$out.= '<table class="border" width="100%">'."\n";
// Substitution array
if (! empty($this->withsubstit))
{
$out.= '<tr><td colspan="2">';
$help="";
foreach($this->substit as $key => $val)
{
$help.=$key.' -> '.$langs->trans($val).'<br>';
}
$out.= $form->textwithpicto($langs->trans("<API key>"),$help);
$out.= "</td></tr>\n";
}
// From
if (! empty($this->withfrom))
{
if (! empty($this->withfromreadonly))
{
$out.= '<input type="hidden" id="fromname" name="fromname" value="'.$this->fromname.'" />';
$out.= '<input type="hidden" id="frommail" name="frommail" value="'.$this->frommail.'" />';
$out.= '<tr><td width="180">'.$langs->trans("MailFrom").'</td><td>';
if ($this->fromtype == 'user' && $this->fromid > 0)
{
$langs->load("users");
$fuser=new User($this->db);
$fuser->fetch($this->fromid);
$out.= $fuser->getNomUrl(1);
}
else
{
$out.= $this->fromname;
}
if ($this->frommail)
{
$out.= " <".$this->frommail.">";
}
else
{
if ($this->fromtype)
{
$langs->load("errors");
$out.= '<font class="warning"> <'.$langs->trans("<API key>").'> </font>';
}
}
$out.= "</td></tr>\n";
$out.= "</td></tr>\n";
}
else
{
$out.= "<tr><td>".$langs->trans("MailFrom")."</td><td>";
$out.= $langs->trans("Name").':<input type="text" id="fromname" name="fromname" size="32" value="'.$this->fromname.'" />';
$out.= ' ';
$out.= $langs->trans("EMail").':<<input type="text" id="frommail" name="frommail" size="32" value="'.$this->frommail.'" />>';
$out.= "</td></tr>\n";
}
}
// Replyto
if (! empty($this->withreplyto))
{
if ($this->withreplytoreadonly)
{
$out.= '<input type="hidden" id="replyname" name="replyname" value="'.$this->replytoname.'" />';
$out.= '<input type="hidden" id="replymail" name="replymail" value="'.$this->replytomail.'" />';
$out.= "<tr><td>".$langs->trans("MailReply")."</td><td>".$this->replytoname.($this->replytomail?(" <".$this->replytomail.">"):"");
$out.= "</td></tr>\n";
}
}
// Errorsto
if (! empty($this->witherrorsto))
{
//if (! $this->errorstomail) $this->errorstomail=$this->frommail;
$errorstomail = (! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail);
if ($this-><API key>)
{
$out.= '<input type="hidden" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
$out.= '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
$out.= $errorstomail;
$out.= "</td></tr>\n";
}
else
{
$out.= '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
$out.= '<input size="30" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
$out.= "</td></tr>\n";
}
}
if (! empty($this->withto) || is_array($this->withto))
{
$out.= '<tr><td width="180">';
if ($this->withtofree) $out.= $form->textwithpicto($langs->trans("MailTo"),$langs->trans("<API key>"));
else $out.= $langs->trans("MailTo");
$out.= '</td><td>';
if ($this->withtoreadonly)
{
if (! empty($this->toname) && ! empty($this->tomail))
{
$out.= '<input type="hidden" id="toname" name="toname" value="'.$this->toname.'" />';
$out.= '<input type="hidden" id="tomail" name="tomail" value="'.$this->tomail.'" />';
if ($this->totype == 'thirdparty')
{
$soc=new Societe($this->db);
$soc->fetch($this->toid);
$out.= $soc->getNomUrl(1);
}
else if ($this->totype == 'contact')
{
$contact=new Contact($this->db);
$contact->fetch($this->toid);
$out.= $contact->getNomUrl(1);
}
else
{
$out.= $this->toname;
}
$out.= ' <'.$this->tomail.'>';
if ($this->withtofree)
{
$out.= '<br>'.$langs->trans("or").' <input size="'.(is_array($this->withto)?"30":"60").'" id="sendto" name="sendto" value="'.(! is_array($this->withto) && ! is_numeric($this->withto)? (isset($_REQUEST["sendto"])?$_REQUEST["sendto"]:$this->withto) :"").'" />';
}
}
else
{
$out.= (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:"";
}
}
else
{
if (! empty($this->withtofree))
{
$out.= '<input size="'.(is_array($this->withto)?"30":"60").'" id="sendto" name="sendto" value="'.(! is_array($this->withto) && ! is_numeric($this->withto)? (isset($_REQUEST["sendto"])?$_REQUEST["sendto"]:$this->withto) :"").'" />';
}
if (! empty($this->withto) && is_array($this->withto))
{
if (! empty($this->withtofree)) $out.= " ".$langs->trans("or")." ";
$out.= $form->selectarray("receiver", $this->withto, GETPOST("receiver"), 1);
}
if (isset($this->withtosocid) && $this->withtosocid > 0) // deprecated. TODO Remove this. Instead, fill withto with array before calling method.
{
$liste=array();
$soc=new Societe($this->db);
$soc->fetch($this->withtosocid);
foreach ($soc-><API key>(1) as $key=>$value)
{
$liste[$key]=$value;
}
if ($this->withtofree) $out.= " ".$langs->trans("or")." ";
$out.= $form->selectarray("receiver", $liste, GETPOST("receiver"), 1);
}
}
$out.= "</td></tr>\n";
}
if (! empty($this->withtocc) || is_array($this->withtocc))
{
$out.= '<tr><td width="180">';
$out.= $form->textwithpicto($langs->trans("MailCC"),$langs->trans("<API key>"));
$out.= '</td><td>';
if ($this->withtoccreadonly)
{
$out.= (! is_array($this->withtocc) && ! is_numeric($this->withtocc))?$this->withtocc:"";
}
else
{
$out.= '<input size="'.(is_array($this->withtocc)?"30":"60").'" id="sendtocc" name="sendtocc" value="'.((! is_array($this->withtocc) && ! is_numeric($this->withtocc))? (isset($_POST["sendtocc"])?$_POST["sendtocc"]:$this->withtocc) : (isset($_POST["sendtocc"])?$_POST["sendtocc"]:"") ).'" />';
if (! empty($this->withtocc) && is_array($this->withtocc))
{
$out.= " ".$langs->trans("or")." ";
$out.= $form->selectarray("receivercc", $this->withtocc, GETPOST("receivercc"), 1);
}
}
$out.= "</td></tr>\n";
}
// CCC
if (! empty($this->withtoccc) || is_array($this->withtoccc))
{
$out.= '<tr><td width="180">';
$out.= $form->textwithpicto($langs->trans("MailCCC"),$langs->trans("<API key>"));
$out.= '</td><td>';
if (! empty($this->withtocccreadonly))
{
$out.= (! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))?$this->withtoccc:"";
}
else
{
$out.= '<input size="'.(is_array($this->withtoccc)?"30":"60").'" id="sendtoccc" name="sendtoccc" value="'.((! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))? (isset($_POST["sendtoccc"])?$_POST["sendtoccc"]:$this->withtoccc) : (isset($_POST["sendtoccc"])?$_POST["sendtoccc"]:"") ).'" />';
if (! empty($this->withtoccc) && is_array($this->withtoccc))
{
$out.= " ".$langs->trans("or")." ";
$out.= $form->selectarray("receiverccc", $this->withtoccc, GETPOST("receiverccc"), 1);
}
}
//if (! empty($conf->global-><API key>)) print ' '.info_admin("+ ".$conf->global-><API key>,1);
$out.= "</td></tr>\n";
}
// Ask delivery receipt
if (! empty($this->withdeliveryreceipt))
{
$out.= '<tr><td width="180">'.$langs->trans("DeliveryReceipt").'</td><td>';
if (! empty($this-><API key>))
{
$out.= yn($this->withdeliveryreceipt);
}
else
{
$out.= $form->selectyesno('deliveryreceipt', (isset($_POST["deliveryreceipt"])?$_POST["deliveryreceipt"]:0), 1);
}
$out.= "</td></tr>\n";
}
// Topic
if (! empty($this->withtopic))
{
$this->withtopic=make_substitutions($this->withtopic,$this->substit);
$out.= '<tr>';
$out.= '<td width="180">'.$langs->trans("MailTopic").'</td>';
$out.= '<td>';
if ($this->withtopicreadonly)
{
$out.= $this->withtopic;
$out.= '<input type="hidden" size="60" id="subject" name="subject" value="'.$this->withtopic.'" />';
}
else
{
$out.= '<input type="text" size="60" id="subject" name="subject" value="'. (isset($_POST["subject"])?$_POST["subject"]:(is_numeric($this->withtopic)?'':$this->withtopic)) .'" />';
}
$out.= "</td></tr>\n";
}
// Attached files
if (! empty($this->withfile))
{
$out.= '<tr>';
$out.= '<td width="180">'.$langs->trans("MailFile").'</td>';
$out.= '<td>';
// TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript
$out.= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
$out.= '<script type="text/javascript" language="javascript">';
$out.= 'jQuery(document).ready(function () {';
$out.= ' jQuery(".removedfile").click(function() {';
$out.= ' jQuery(".removedfilehidden").val(jQuery(this).val());';
$out.= ' });';
$out.= '})';
$out.= '</script>'."\n";
if (count($listofpaths))
{
foreach($listofpaths as $key => $val)
{
$out.= '<div id="attachfile_'.$key.'">';
$out.= img_mime($listofnames[$key]).' '.$listofnames[$key];
if (! $this->withfilereadonly)
{
$out.= ' <input type="image" style="border: 0px;" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/delete.png" value="'.($key+1).'" class="removedfile" id="removedfile_'.$key.'" name="removedfile_'.$key.'" />';
//$out.= ' <a href="'.$_SERVER["PHP_SELF"].'?removedfile='.($key+1).' id="removedfile_'.$key.'">'.img_delete($langs->trans("Delete").'</a>';
}
$out.= '<br></div>';
}
}
else
{
$out.= $langs->trans("NoAttachedFiles").'<br>';
}
if ($this->withfile == 2) // Can add other files
{
$out.= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
$out.= ' ';
$out.= '<input type="submit" class="button" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
}
$out.= "</td></tr>\n";
}
// Message
if (! empty($this->withbody))
{
$defaultmessage="";
// TODO A partir du type, proposer liste de messages dans table llx_models
if ($this->param["models"]=='facture_send') { $defaultmessage=$langs->transnoentities("<API key>"); }
elseif ($this->param["models"]=='facture_relance') { $defaultmessage=$langs->transnoentities("<API key>"); }
elseif ($this->param["models"]=='propal_send') { $defaultmessage=$langs->transnoentities("<API key>"); }
elseif ($this->param["models"]=='order_send') { $defaultmessage=$langs->transnoentities("<API key>"); }
elseif ($this->param["models"]=='order_supplier_send') { $defaultmessage=$langs->transnoentities("<API key>"); }
elseif ($this->param["models"]=='<API key>') { $defaultmessage=$langs->transnoentities("<API key>"); }
elseif ($this->param["models"]=='shipping_send') { $defaultmessage=$langs->transnoentities("<API key>"); }
elseif ($this->param["models"]=='fichinter_send') { $defaultmessage=$langs->transnoentities("<API key>"); }
elseif (! is_numeric($this->withbody)) { $defaultmessage=$this->withbody; }
// Complete substitution array
if (! empty($conf->paypal->enabled) && ! empty($conf->global-><API key>))
{
require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
$langs->load('paypal');
if ($this->param["models"]=='order_send')
{
$url=getPaypalPaymentUrl(0,'order',$this->substit['__ORDERREF__']);
$this->substit['__PERSONALIZED__']=$langs-><API key>("<API key>",$url);
}
if ($this->param["models"]=='facture_send')
{
$url=getPaypalPaymentUrl(0,'invoice',$this->substit['__FACREF__']);
$this->substit['__PERSONALIZED__']=$langs-><API key>("<API key>",$url);
}
}
$defaultmessage=str_replace('\n',"\n",$defaultmessage);
// Deal with format differences between message and signature (text / HTML)
if(dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__SIGNATURE__'])) {
$this->substit['__SIGNATURE__'] = dol_nl2br($this->substit['__SIGNATURE__']);
} else if(!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__SIGNATURE__'])) {
$defaultmessage = dol_nl2br($defaultmessage);
}
$defaultmessage=make_substitutions($defaultmessage,$this->substit);
if (isset($_POST["message"])) $defaultmessage=$_POST["message"];
$out.= '<tr>';
$out.= '<td width="180" valign="top">'.$langs->trans("MailText").'</td>';
$out.= '<td>';
if ($this->withbodyreadonly)
{
$out.= nl2br($defaultmessage);
$out.= '<input type="hidden" id="message" name="message" value="'.$defaultmessage.'" />';
}
else
{
if (! isset($this->ckeditortoolbar)) $this->ckeditortoolbar = 'dolibarr_notes';
// Editor wysiwyg
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
if (!empty($conf->global-><API key>)) {
$this->withfckeditor=1;
}
$doleditor=new DolEditor('message',$defaultmessage,'',280,$this->ckeditortoolbar,'In',true,true,$this->withfckeditor,8,72);
$out.= $doleditor->Create(1);
}
$out.= "</td></tr>\n";
}
if (! empty($this->withform))
{
$out.= '<tr><td align="center" colspan="2"><center>';
$out.= '<input class="button" type="submit" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"';
// Add a javascript test to avoid to forget to submit file before sending email
if ($this->withfile == 2 && $conf->use_javascript_ajax)
{
$out.= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"';
}
$out.= ' />';
if ($this->withcancel)
{
$out.= ' ';
$out.= '<input class="button" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />';
}
$out.= '</center></td></tr>'."\n";
}
$out.= '</table>'."\n";
if (! empty($this->withform)) $out.= '</form>'."\n";
$out.= "<!-- Fin form mail -->\n";
return $out;
}
}
}
?> |
package cm.aptoide.pt.dataprovider.model.v3;
import com.fasterxml.jackson.annotation.JsonProperty;
public class <API key> extends BaseV3Response {
@JsonProperty("tos") private boolean tos;
@JsonProperty("privacy") private boolean privacy;
public <API key>() {
}
public boolean isTos() {
return tos;
}
public void setTos(boolean tos) {
this.tos = tos;
}
public boolean isPrivacy() {
return privacy;
}
public void setPrivacy(boolean privacy) {
this.privacy = privacy;
}
} |
/* Department of Cybernetics */
/* Faculty of Applied Sciences */
/* University of West Bohemia in Pilsen */
/* This file is part of CeCe. */
/* CeCe is free software: you can redistribute it and/or modify */
/* (at your option) any later version. */
/* CeCe is distributed in the hope that it will be useful, */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
#pragma once
#include <initializer_list>
// CeCe
#include "cece/core/Real.hpp"
#include "cece/core/Pair.hpp"
#include "cece/core/String.hpp"
#include "cece/core/StringView.hpp"
#include "cece/core/DynamicArray.hpp"
#include "cece/core/Exception.hpp"
namespace cece {
inline namespace core {
/**
* @brief Exception for missing parameter.
*/
class <API key> : public <API key>
{
using <API key>::<API key>;
};
/**
* @brief Class for storing simulation parameters.
*/
class Parameters
{
// Public Types
public:
Key type.
using KeyType = String;
Value type.
using ValueType = RealType;
Key view type.
using KeyViewType = StringView;
// Public Ctors & Dtors
public:
/**
* @brief Default constructor.
*/
Parameters() = default;
/**
* @brief Constructor.
*
* @param data Initial data.
*/
explicit Parameters(std::initializer_list<Pair<KeyType, ValueType>> data)
: m_data(data)
{
// Nothing to do
}
// Public Operators
public:
/**
* @brief Parameter access operator.
*
* @param name Parameter name.
*
* @return Reference to parameter value.
*
* @note In case of missing value, new is created.
*/
ValueType& operator[](const KeyViewType& name) noexcept
{
return get(name);
}
/**
* @brief Parameter access operator.
*
* @param name Parameter name.
*
* @return Reference to parameter value.
*
* @throw <API key> In case of missing value.
*/
ValueType operator[](const KeyViewType& name) const
{
return get(name);
}
// Public Accessors
public:
/**
* @brief Returns if parameter with given name exists.
*
* @param name Parameter name.
*
* @return
*/
bool exists(const KeyViewType& name) const noexcept;
/**
* @brief Returns parameter with given value.
*
* @param name Parameter name.
*
* @return Parameter value.
*
* @throw <API key> In case of missing value.
*/
ValueType get(const KeyViewType& name) const;
/**
* @brief Returns parameter with given value.
*
* @param name Parameter name.
*
* @return Parameter value.
*
* @throw <API key> In case of missing value.
*/
ValueType& get(const KeyViewType& name);
/**
* @brief Returns parameter with given value.
*
* @param name Parameter name.
* @param def Default parameter in case of missing value.
*
* @return Parameter value.
*/
ValueType get(const KeyViewType& name, ValueType def) const noexcept;
// Public Mutators
public:
/**
* @brief Store or replace parameter.
*
* @param name Parameter name.
* @param value Value to store.
*/
void set(KeyType name, ValueType value);
// Public Operations
public:
/**
* @brief Merge parameters.
*
* @param parameters
*/
void merge(const Parameters& parameters);
// Private Data Members
private:
Stored data
DynamicArray<Pair<KeyType, ValueType>> m_data;
};
}
} |
package serverftpgui;
import java.io.BufferedInputStream;
import java.io.<API key>;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import javax.swing.JOptionPane;
/**
*
* @author lander
*/
public class ServerHilo extends Thread{
private Socket cliente = new Socket();
private static final String PATH = "/home/lander/FTP/";
// Constructor
public ServerHilo(Socket cliente){
this.cliente = cliente;
}// end constructor
@Override
public void run(){
// Streams
DataOutputStream envio = null;
DataInputStream recibido = null;
String nomFichero = "";
<API key> bufferSalida = null;
BufferedInputStream bufferEntrada = null;
byte [] bufferLeido = null;
// flag
int flag = Integer.MAX_VALUE;
try {
// Recibimos el flag del usuario
recibido = new DataInputStream(cliente.getInputStream());
flag = recibido.readInt();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(flag);
if(flag == 0){
// Descargamos del servidor
try {
// Ruta de los ficheros en el servidor
File directorioFicheros = new File(PATH);
if (!directorioFicheros.exists()){
JOptionPane.showMessageDialog(null, "Cambie la constante PATH en el servidor");
System.exit(0);
}
// Array de ficheros/carpetas contenidos en el directorio
File [] listaFicheros = directorioFicheros.listFiles();
// Enviamos al cliente la cantidad de ficheros que tenemos
envio = new DataOutputStream(cliente.getOutputStream());
envio.writeInt(listaFicheros.length);
// Le enviamos la lista
for (int i = 0; i < listaFicheros.length; i++) {
envio.writeUTF(listaFicheros[i].getName());
}// end for
// Recibimos por parte del cliente el nombre del fichero a descargar
recibido = new DataInputStream(cliente.getInputStream());
nomFichero = recibido.readUTF();
// Leemos los datos del arvhivo para poder recibirnos en el cliente
// debug
//System.out.println(nomFichero);
File ficheroEnviar = new File(PATH+nomFichero);
envio = new DataOutputStream(cliente.getOutputStream());
envio.writeInt((int)ficheroEnviar.length());
FileInputStream lectura = new FileInputStream(ficheroEnviar);
bufferEntrada = new BufferedInputStream(lectura);
bufferSalida = new <API key>(cliente.getOutputStream());
bufferLeido = new byte [(int) ficheroEnviar.length()];
// Introducimos el contenido del fichero en el array
bufferEntrada.read(bufferLeido);
// Recorremos el array de bytes y lo enviamos
for (int i = 0; i < bufferLeido.length; i++) {
bufferSalida.write(bufferLeido [i]);
}// end for
// Cerramos los streams
bufferSalida.close();
bufferEntrada.close();
} catch (IOException e) {
e.printStackTrace();
}
}else{
// El servidor recibe el fichero
try {
// Recibimos el nombre del fichero
recibido = new DataInputStream(cliente.getInputStream());
nomFichero = recibido.readUTF();
recibido = new DataInputStream(cliente.getInputStream());
int tamFichero = (int) recibido.readInt();
FileOutputStream fichero = new FileOutputStream(PATH+nomFichero);
bufferSalida = new <API key>(fichero);
bufferEntrada = new BufferedInputStream(cliente.getInputStream());
byte [] bufferFichero = new byte [tamFichero];
for (int i = 0; i < bufferFichero.length; i++) {
bufferFichero [i] = (byte) bufferEntrada.read();
}// end for
// Persistimos el fichero
bufferSalida.write(bufferFichero);
bufferSalida.flush();
fichero.close();
bufferEntrada.close();
JOptionPane.showMessageDialog(null, "Fichero en el servidor");
} catch (IOException e) {
}
}
System.out.println("Hilo finalizado");
}// end run
}// class |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_60) on Thu Nov 05 23:31:39 MST 2015 -->
<title>Uses of Class cmput301exchange.exchange.Activities.<API key></title>
<meta name="date" content="2015-11-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class cmput301exchange.exchange.Activities.<API key>";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../cmput301exchange/exchange/Activities/<API key>.html" title="class in cmput301exchange.exchange.Activities">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?cmput301exchange/exchange/Activities/class-use/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Class cmput301exchange.exchange.Activities.<API key>" class="title">Uses of Class<br>cmput301exchange.exchange.Activities.<API key></h2>
</div>
<div class="classUseContainer">No usage of cmput301exchange.exchange.Activities.<API key></div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../cmput301exchange/exchange/Activities/<API key>.html" title="class in cmput301exchange.exchange.Activities">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?cmput301exchange/exchange/Activities/class-use/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html> |
#!/bin/bash
#argument 1 : -f make the replacement force!
shopt -s expand_aliases
source ~/.bash_aliases
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")" |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ECCentral.Service.Inventory.IDataAccess;
using ECCentral.Service.Utility;
using ECCentral.Service.Utility.DataAccess;
namespace ECCentral.Service.Inventory.SqlDataAccess
{
[VersionExport(typeof(IBatchManagementDA))]
public class BatchManagementDA : IBatchManagementDA
{
#region IBatchManagementDA Members
public void <API key>(BizEntity.Inventory.ProductRingDayInfo entity)
{
var command = DataCommandManager.GetDataCommand("UpdateProductRing");
command.SetParameterValue("@SysNo", entity.SysNo.Value);
command.SetParameterValue("@BrandSysNo", entity.BrandSysNo);
command.SetParameterValue("@C3SysNo", entity.C3SysNo);
command.SetParameterValue("@RingDay", entity.RingDay);
command.SetParameterValue("@Email", entity.Email);
command.SetParameterValue("@EditUser", entity.EditUser);
command.ExecuteNonQuery();
}
public void <API key>(BizEntity.Inventory.ProductRingDayInfo entity)
{
var command = DataCommandManager.GetDataCommand("InsertProductRing");
command.SetParameterValue("@BrandSysNo", entity.BrandSysNo);
command.SetParameterValue("@C3SysNo", entity.C3SysNo);
command.SetParameterValue("@RingDay", entity.RingDay);
command.SetParameterValue("@Email", entity.Email);
command.SetParameterValue("@InUser", entity.InUser);
command.SetParameterValue("@InDate", entity.InDate);
command.SetParameterValue("@EditUser", entity.EditUser);
command.SetParameterValue("@EditDate", entity.EditDate);
command.ExecuteNonQuery();
}
#endregion
}
} |
// extern crate sdl2;
macro_rules! struct_events {
(
keyboard: { $( $k_alias:ident : $k_sdl:ident ),* },
// match against a pattern
else: { $( $e_alias:ident : $e_sdl:pat ),* }
) => {
use sdl2::EventPump;
pub struct ImmediateEvents {
// for every keyboard event, we have an Option<bool>
// Some(true) => was just pressed
// Some(false) => was just released
// None => nothing happening right now.
$( pub $k_alias: Option<bool> , )*
$( pub $e_alias : bool ),* ,
resize: Option<(u32, u32)>
}
impl ImmediateEvents {
pub fn new() -> ImmediateEvents {
ImmediateEvents {
// when initialized, nothing has happened yet, so all are
// set to None
$( $k_alias: None , )*
$( $e_alias: false ),* ,
resize: None
}
}
}
pub struct Events {
pump: EventPump,
pub now: ImmediateEvents,
// true => pressed
// false => not pressed
$( pub $k_alias: bool ),*
}
impl Events {
pub fn new(pump: EventPump) -> Events {
Events {
pump: pump,
now: ImmediateEvents::new(),
// by default, initialize evy key with not pressed
$( $k_alias: false ),*
}
}
pub fn pump(&mut self, renderer: &mut ::sdl2::render::Renderer) {
self.now = ImmediateEvents::new();
use sdl2::event::Event::*;
use sdl2::event::WindowEvent::*;
use sdl2::keyboard::Keycode::*;
for event in self.pump.poll_iter() {
match event {
Window { window_id, win_event: Resized(x, y), .. } => {
println!("Resized window {} to {}, {}", window_id, x, y);
self.now.resize = Some(renderer.output_size().unwrap());
},
KeyDown { keycode, .. } => match keycode {
// $( .. ),* containing $k_sdl and $k_alias means:
// "for every element ($k_alias : $k_sdl) pair,
// check whether the keycode is Some($k_sdl). If
// it is, then set the $k_alias fields to true."
$(
Some($k_sdl) => {
// prevent multiple presses when keeping a
// key down; was it previously pressed or not?
if !self.$k_alias {
// key pressed
self.now.$k_alias = Some(true);
}
self.$k_alias = true;
}
),*
_ => {}
},
KeyUp { keycode, .. } => match keycode {
$(
Some($k_sdl) => {
// key released
self.now.$k_alias = Some(false);
self.$k_alias = false;
}
),*
_ => {}
},
$(
$e_sdl => {
self.now.$e_alias = true;
}
)*,
_ => {}
}
}
}
}
}
} |
#include <stdint.h>
#include <platform.h>
#include "drivers/io.h"
#include "drivers/timer.h"
const timerHardware_t timerHardware[<API key>] = {
{ TIM4, IO_TAG(PB6), TIM_Channel_1, TIM_USE_PWM, 0, }, // S1_IN
{ TIM3, IO_TAG(PB5), TIM_Channel_2, TIM_USE_PWM, 0, }, // S2_IN - SoftSerial TX - <API key> / Sonar trigger
{ TIM3, IO_TAG(PB0), TIM_Channel_3, TIM_USE_PWM, 0, }, // S3_IN - SoftSerial RX / Sonar echo / RSSI ADC
{ TIM3, IO_TAG(PB1), TIM_Channel_4, TIM_USE_PWM, 0, }, // S4_IN - Current
{ TIM4, IO_TAG(PB8), TIM_Channel_3, TIM_USE_PWM, 0, }, // S5_IN - Vbattery
{ TIM2, IO_TAG(PA1), TIM_Channel_2, TIM_USE_PWM | TIM_USE_PPM, 0, }, // S6_IN - PPM IN
{ TIM4, IO_TAG(PB9), TIM_Channel_4, TIM_USE_MOTOR, 1, }, // S1_OUT
{ TIM2, IO_TAG(PA0), TIM_Channel_1, TIM_USE_MOTOR, 1, }, // S2_OUT
{ TIM4, IO_TAG(PB7), TIM_Channel_2, TIM_USE_MOTOR, 1, }, // S3_OUT
{ TIM1, IO_TAG(PA8), TIM_Channel_1, TIM_USE_MOTOR, 1, }, // S4_OUT
{ TIM3, IO_TAG(PB4), TIM_Channel_1, TIM_USE_MOTOR, 1, }, // S5_OUT - <API key> - LED Strip
{ TIM2, IO_TAG(PA2), TIM_Channel_3, TIM_USE_MOTOR, 1, } // S6_OUT
}; |
#include <msp430.h>
#include <legacymsp430.h>
#include "serial.h"
#include "serial_rb.h"
#include "core_proto.h"
#include "core_handlers.h"
#include "packet_handler.h"
#include "config.h"
/**
* Serial ringbuffer to receive packet data
*/
SERIAL_RB_Q srx_buf[RB_SIZE];
serial_rb srx;
/**
* Serial ringbuffer to send packet data
*/
SERIAL_RB_Q stx_buf[RB_SIZE];
serial_rb stx;
void packet_handler_init()
{
serial_init(BAUDRATE);
serial_rb_init(&srx, &(srx_buf[0]), RB_SIZE);
serial_rb_init(&stx, &(stx_buf[0]), RB_SIZE);
IE2 |= UCA0RXIE;
__bis_SR_register(GIE);
}
void <API key>(unsigned char pkt_byte)
{
// wait until buffer empties
while(serial_rb_full(&stx)) {
__asm__("nop");
}
serial_rb_write(&stx, pkt_byte);
IE2 |= UCA0TXIE;
}
unsigned char <API key>()
{
// wait until data arrived in buffer
while(serial_rb_empty(&srx)) {
// see if external interrupts need to be reported ...
process_exti();
}
// see if external interrupts need to be reported ...
process_exti();
return serial_rb_read(&srx);
}
interrupt(USCIAB0RX_VECTOR) USCI0RX_ISR(void)
{
if (!serial_rb_full(&srx)) {
serial_rb_write(&srx, UCA0RXBUF);
}
}
interrupt(USCIAB0TX_VECTOR) USCI0TX_ISR(void)
{
if(!serial_rb_empty(&stx)) {
serial_send(serial_rb_read(&stx));
}
else {
IE2 &= ~UCA0TXIE;
}
} |
package at.ac.tuwien.infosys.prybila.runtimeVerification.bitcoin.core;
import at.ac.tuwien.infosys.prybila.runtimeVerification.bitcoin.core.model.<API key>;
import at.ac.tuwien.infosys.prybila.runtimeVerification.bitcoin.core.model.<API key>;
import at.ac.tuwien.infosys.prybila.runtimeVerification.utils.<API key>;
import org.bitcoinj.script.Script;
import java.util.List;
import static org.bitcoinj.script.ScriptOpCodes.OP_RETURN;
/**
* Verify a transaction for the three common transaction types of the handover framework
*/
public class <API key> {
private <API key> transaction;
private <API key> <API key>;
/**
* Verifies the transaction on object creation.
* Throws a <API key> if the transaction structure does not fit any of the three common transaction types.
*/
public <API key>(<API key> transaction) {
this.transaction = transaction;
verify();
}
/**
* Verifies the transaction.
* Throws a <API key> if the transaction does not fit any of the three common transaction types.
*/
private void verify() {
if (<API key>()) {
<API key> = <API key>.INTERMEDIATE;
return;
}
if (<API key>()) {
<API key> = <API key>.START;
return;
}
if (<API key>()) {
<API key> = <API key>.END;
return;
}
if (<API key>()) {
<API key> = <API key>.SPLIT;
return;
}
if (<API key>()) {
<API key> = <API key>.JOIN;
return;
}
throw new <API key>("The given transaction " + transaction + " did not fit a common transaction type.");
}
/**
* Returns true if the given transaction has the structure of a WF split transaction
*/
private boolean <API key>() {
//Must have exactly one input.
if (transaction.getInputSize() != 1) {
return false;
}
//Must originate from P2SH, can on this level only be checked if the transaction was initiated by this instance.
if (transaction.<API key>()) {
if (transaction.<API key>().getInputs().get(0).getConnectedOutput() != null
&& !transaction.<API key>().getInputs().get(0).getConnectedOutput().getScriptPubKey().isPayToScriptHash()) {
return false;
}
}
//Must have at least three outputs
if (transaction.getOutputSize() < 3) {
return false;
}
//All but the last must have a P2SH scripts
for (int i = 0; i < transaction.getOutputSize() - 1; i++) {
if (!new Script(transaction.getOutputScript(i)).isPayToScriptHash()) {
return false;
}
}
//Last output must be of type OP_RETURN
Script dataScript = new Script(transaction.getOutputScript(transaction.getOutputSize() - 1));
if (dataScript.getChunks().size() != 2) {
return false;
}
if (dataScript.getChunks().get(0).opcode != OP_RETURN) {
return false;
}
//Data block must be of type <API key>.SPLIT
byte[] dataBlock = dataScript.getChunks().get(1).data;
<API key> <API key> = new <API key>(dataBlock);
<API key> type = <API key>.<API key>().<API key>();
if (type != <API key>.SPLIT) {
return false;
}
return true;
}
/**
* Returns true if the given transaction has the structure of a WF join transaction
*/
private boolean <API key>() {
//Must have at least two inputs
if (transaction.getInputSize() < 2) {
return false;
}
//All inputs must originate from P2SH, can on this level only be checked if the transaction was initiated by this instance.
if (transaction.<API key>()) {
for (int i = 0; i < transaction.<API key>().getInputs().size(); i++) {
if (transaction.<API key>().getInputs().get(i).getConnectedOutput() != null
&& !transaction.<API key>().getInputs().get(i).getConnectedOutput().getScriptPubKey().isPayToScriptHash()) {
return false;
}
}
}
//Must have exactly two outputs.
if (transaction.getOutputSize() != 2) {
return false;
}
//First output must be of type P2SH
if (!new Script(transaction.getOutputScript(0)).isPayToScriptHash()) {
return false;
}
//Second output must be of type OP_RETURN
Script dataScript = new Script(transaction.getOutputScript(1));
if (dataScript.getChunks().size() != 2) {
return false;
}
if (dataScript.getChunks().get(0).opcode != OP_RETURN) {
return false;
}
//Data block must be of type <API key>.Join
byte[] dataBlock = dataScript.getChunks().get(1).data;
<API key> <API key> = new <API key>(dataBlock);
<API key> type = <API key>.<API key>().<API key>();
if (type != <API key>.JOIN) {
return false;
}
return true;
}
/**
* Returns true if the given transaction has the structure of a WF start transaction
*/
private boolean <API key>() {
//Can have an arbitrary amount of inputs
//Type of input does not matter
//Must have at most three outputs, one for token, one for OP_RETURN, and one for change.
if (transaction.getOutputSize() > 3) {
return false;
}
//First output must be of type P2SH
if (!new Script(transaction.getOutputScript(0)).isPayToScriptHash()) {
return false;
}
//Second output must be of type OP_RETURN
Script dataScript = new Script(transaction.getOutputScript(1));
if (dataScript.getChunks().size() != 2) {
return false;
}
if (dataScript.getChunks().get(0).opcode != OP_RETURN) {
return false;
}
//Data block must be of type <API key>.START
byte[] dataBlock = dataScript.getChunks().get(1).data;
<API key> <API key> = new <API key>(dataBlock);
<API key> type = <API key>.<API key>().<API key>();
if (type != <API key>.START) {
return false;
}
return true;
}
/**
* Returns true if the given transaction has the structure of a WF end transaction
*/
private boolean <API key>() {
//Must have exactly one input.
if (transaction.getInputSize() != 1) {
return false;
}
//Must originate from P2SH, can on this level only be checked if the transaction was initiated by this instance.
if (transaction.<API key>()) {
if (transaction.<API key>().getInputs().get(0).getConnectedOutput() != null
&& !transaction.<API key>().getInputs().get(0).getConnectedOutput().getScriptPubKey().isPayToScriptHash()) {
return false;
}
}
//Must have exactly two outputs.
if (transaction.getOutputSize() != 2) {
return false;
}
//One output must be of type OP_RETURN
byte[] <API key> = findOpReturnOutput(transaction.getOutputScripts());
if (<API key> == null) {
return false;
}
Script <API key> = new Script(<API key>);
//Data block must be of type <API key>.END
byte[] dataBlock = <API key>.getChunks().get(1).data;
<API key> <API key> = new <API key>(dataBlock);
<API key> type = <API key>.<API key>().<API key>();
if (type != <API key>.END) {
return false;
}
return true;
}
/**
* Returns the first found instance of type OP_RETURN or null.
*/
private byte[] findOpReturnOutput(List<byte[]> outputScriptList) {
for (byte[] <API key> : outputScriptList) {
Script dataScript = new Script(<API key>);
if (dataScript.getChunks().size() != 2) {
continue;
}
if (dataScript.getChunks().get(0).opcode != OP_RETURN) {
continue;
}
return <API key>;
}
return null;
}
/**
* Returns true if the given transaction has the structure of a WF intermediate transaction
*/
private boolean <API key>() {
//Must have exactly one input.
if (transaction.getInputSize() != 1) {
return false;
}
//Must originate from P2SH, can on this level only be checked if the transaction was initiated by this instance.
if (transaction.<API key>()) {
if (transaction.<API key>().getInputs().get(0).getConnectedOutput() != null
&& !transaction.<API key>().getInputs().get(0).getConnectedOutput().getScriptPubKey().isPayToScriptHash()) {
return false;
}
}
//Must have exactly two outputs.
if (transaction.getOutputSize() != 2) {
return false;
}
//First output must be of type P2SH
if (!new Script(transaction.getOutputScript(0)).isPayToScriptHash()) {
return false;
}
//Second output must be of type OP_RETURN
Script dataScript = new Script(transaction.getOutputScript(1));
if (dataScript.getChunks().size() != 2) {
return false;
}
if (dataScript.getChunks().get(0).opcode != OP_RETURN) {
return false;
}
//Data block must be of type <API key>.INTERMEDIATE
byte[] dataBlock = dataScript.getChunks().get(1).data;
<API key> <API key> = new <API key>(dataBlock);
<API key> type = <API key>.<API key>().<API key>();
if (type != <API key>.INTERMEDIATE) {
return false;
}
return true;
}
/**
* Returns true if the transaction is a WF start transaction
*/
public boolean <API key>() {
return <API key>(<API key>.START);
}
/**
* Returns true if the transaction is a WF start transaction
*/
public boolean isWFEndTransaction() {
return <API key>(<API key>.END);
}
/**
* Returns true if the transaction is a WF start transaction
*/
public boolean <API key>() {
return <API key>(<API key>.INTERMEDIATE);
}
public boolean <API key>() {
return <API key>(<API key>.SPLIT);
}
public boolean isWFJoinTransaction() {
return <API key>(<API key>.JOIN);
}
/**
* Returns true if the transaction is of the given type
*/
private boolean <API key>(<API key> typeToCheckAgainst) {
if (<API key> == null) {
return false;
}
return <API key> == typeToCheckAgainst;
}
} |
#include "Models/MixedPerturbator.h"
#include "Models/<API key>.h"
#include "Models/<API key>.h"
#include "Util/ParametersSet.h"
#include <iostream>
#include <assert.h>
using namespace std;
MixedPerturbator::MixedPerturbator():Perturbator(){
lastModifiedModel = -1;
models.clear();
rndModels.clear();
}
MixedPerturbator::~MixedPerturbator(){
}
void MixedPerturbator::registerModel( Model* model, const string& genericModelName,
ParametersSet& parameters, const string& <API key>,
double* averageRate, double <API key>,
const string& initialStepString ){
unsigned int modelPrio = parameters.intParameter(genericModelName + ", proposal priority");
if (models.size()){
double extrMin, extrMax;
char label[60];
sprintf( label, "Model%d/model1 average substitution rate ratio",
models.size()+1 );
//when its average rate is modified, the underlying model will receive a message AVERAGE_RATE
//it has to treat it
<API key>* pert =
<API key>( *model, UpdateMessage::AVERAGE_RATE,
label, averageRate,
parameters, <API key>,
<API key>, 0.001, 5.0,
initialStepString );
pert->getExtrema( extrMin, extrMax );
if (extrMin<0.0){
cerr << "invalid prior for the " << <API key>
<< parameters.stringParameter( <API key> + ", prior") << endl;
exit(EXIT_FAILURE);
}
}
modelToModel.insert(modelToModel.end(), modelPrio, models.size() );
models.push_back( model );
rndModels.insert( rndModels.end(), modelPrio, model );
}
double MixedPerturbator::perturb(){
double res = 0.0;
if( rndTable.size() || rndModels.size() ){
assert(lastModified == -1);
assert(lastModifiedModel == -1);
int nb = (int)(rand.ran()*(double)(rndTable.size()+rndModels.size()));
if ( nb >= (int)rndTable.size() ){
lastModifiedModel = nb - (int)rndTable.size();
res = rndModels[lastModifiedModel]->perturb();
}
else{
lastModified = nb;
//if we change an average substitution rate
res = rndTable[lastModified]->perturb();
}
}
return res;
}
bool MixedPerturbator::<API key>(bool validation){
if( rndTable.size() || rndModels.size() ){
if (lastModified != -1){
assert(lastModifiedModel==-1);
bool res = rndTable[lastModified]->
<API key>(validation);
lastModified = -1;
return res;
}
else{
assert(lastModifiedModel!=-1);
bool res = rndModels[lastModifiedModel]-><API key>(validation);
lastModifiedModel = -1;
return res;
}
}
return true;
}
void MixedPerturbator::<API key>(ostream& outputStream) {
Perturbator::<API key>( outputStream );
for ( unsigned int i = 0; i < models.size(); ++i ){
outputStream << "MODEL " << i+1 << endl;
models[i]-><API key>( outputStream );
}
}
void MixedPerturbator::<API key>( vector<double>& params ) const{
//first add the basic parameters
Perturbator::<API key>( params );
//then add the parameters from each model
vector<double> p;
for (unsigned int j=0; j < models.size(); ++j){
models[j]-><API key>( p );
params.insert( params.end(), p.begin(), p.end() );
}
}
void MixedPerturbator::<API key>( const vector<double>& params){
assert( params.size() == <API key>() );
vector<double>::const_iterator iter = params.begin();
vector<double> p;
unsigned int nbp;
//first set basic parameters
nbp = Perturbator::<API key>();
p.resize(nbp);
for ( unsigned int i = 0; i < nbp; ++i ){
p[i] = *iter;
++iter;
}
Perturbator::<API key>( p );
//then for each model
for (unsigned int j=0; j < models.size(); ++j){
nbp = models[j]-><API key>();
p.resize(nbp);
for ( unsigned int i = 0; i < nbp; ++i ){
p[i] = *iter;
++iter;
}
models[j]-><API key>( p );
}
}
unsigned int MixedPerturbator::<API key>() const{
//count the basic number of parameters first (use ancestor method)
unsigned int <API key> =
Perturbator::<API key>();
//then add the parameters from each model perturbator
for (unsigned int j=0; j < models.size(); ++j){
<API key> += models[j]-><API key>();
}
return <API key>;
}
void MixedPerturbator::<API key>( vector<double>& params ) const{
//first add the basic parameters
Perturbator::<API key>( params );
//then add the parameters from each model
vector<double> p;
for (unsigned int j=0; j < models.size(); ++j){
models[j]-><API key>( p );
params.insert( params.end(), p.begin(), p.end() );
}
assert( params.size() == <API key>() );
}
void MixedPerturbator::<API key>( const vector<double>& params){
assert( params.size() == <API key>() );
vector<double>::const_iterator iter = params.begin();
vector<double> p;
unsigned int nbp;
//first set basic parameters
nbp = Perturbator::<API key>();
p.resize(nbp);
for ( unsigned int i = 0; i < nbp; ++i ){
p[i] = *iter;
++iter;
}
Perturbator::<API key>( p );
//then for each model
for (unsigned int j=0; j < models.size(); ++j){
nbp = models[j]-><API key>();
p.resize(nbp);
for ( unsigned int i = 0; i < nbp; ++i ){
p[i] = *iter;
++iter;
}
models[j]-><API key>( p );
}
}
unsigned int MixedPerturbator::<API key>() const{
//count the basic number of parameters first (use ancestor method)
unsigned int <API key> =
Perturbator::<API key>();
//then add the parameters from each model perturbator
for (unsigned int j=0; j < models.size(); ++j){
<API key> += models[j]-><API key>();
}
return <API key>;
}
double MixedPerturbator::getLnPrior() const{
double lnPrior = Perturbator::getLnPrior();
for (unsigned int j=0; j < models.size(); ++j){
lnPrior += models[j]->getLnPrior();
}
return lnPrior;
} |
/*
* LegOrdGroup44.java
*
* $Id: LegOrdGroup44.java,v 1.3 2011-09-09 08:05:13 vrotaru Exp $
*/
package net.hades.fix.message.group.impl.v44;
import net.hades.fix.message.FragmentContext;
import net.hades.fix.message.comp.InstrumentLeg;
import net.hades.fix.message.comp.impl.v44.InstrumentLeg44;
import net.hades.fix.message.comp.impl.v44.LegStipulations44;
import net.hades.fix.message.comp.impl.v44.NestedParties44;
import net.hades.fix.message.exception.InvalidMsgException;
import net.hades.fix.message.group.LegAllocGroup;
import net.hades.fix.message.group.<API key>;
import net.hades.fix.message.struct.Tag;
import net.hades.fix.message.util.MsgUtil;
import java.io.<API key>;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import net.hades.fix.message.comp.LegStipulations;
import net.hades.fix.message.comp.NestedParties;
import net.hades.fix.message.exception.<API key>;
import net.hades.fix.message.exception.<API key>;
import net.hades.fix.message.group.LegOrdGroup;
import net.hades.fix.message.group.NestedPartyGroup;
import net.hades.fix.message.type.CoveredOrUncovered;
import net.hades.fix.message.type.LegSwapType;
import net.hades.fix.message.type.PositionEffect;
import net.hades.fix.message.type.SessionRejectReason;
import net.hades.fix.message.type.TagNum;
import net.hades.fix.message.util.TagEncoder;
import net.hades.fix.message.xml.codec.jaxb.adapter.FixDateAdapter;
/**
* FIX 4.4 implementation of LegOrdGroup group.
*
* @author <a href="mailto:support@marvisan.com">Support Team</a>
* @version $Revision: 1.3 $
* @created 29/04/2009, 6:46:57 PM
*/
@XmlRootElement(name = "Ord")
@XmlType(propOrder = {"instrumentLeg", "<API key>", "legAllocGroups", "nestedPartyIDGroups"})
@XmlAccessorType(XmlAccessType.NONE)
public class LegOrdGroup44 extends LegOrdGroup {
// <editor-fold defaultstate="collapsed" desc="Constants">
private static final long serialVersionUID = 1L;
protected static final Set<Integer> TAGS_V44 = new HashSet<Integer>(Arrays.asList(new Integer[] {
TagNum.LegQty.getValue(),
TagNum.LegSwapType.getValue(),
TagNum.LegAllocID.getValue(),
TagNum.NoLegAllocs.getValue(),
TagNum.LegPositionEffect.getValue(),
TagNum.<API key>.getValue(),
TagNum.LegRefID.getValue(),
TagNum.LegPrice.getValue(),
TagNum.LegSettlType.getValue(),
TagNum.LegSettlDate.getValue(),
TagNum.LegOrderQty.getValue(),
TagNum.LegVolatility.getValue(),
TagNum.LegDividendYield.getValue(),
TagNum.LegCurrencyRatio.getValue(),
TagNum.LegExecInst.getValue()
}));
protected static final Set<Integer> ALL_TAGS;
protected static final Set<Integer> START_COMP_TAGS;
protected static final Set<Integer> <API key> = new InstrumentLeg44().getFragmentAllTags();
protected static final Set<Integer> <API key> = new LegStipulations44().getFragmentAllTags();
protected static final Set<Integer> <API key> = new LegAllocGroup44().getFragmentAllTags();
protected static final Set<Integer> <API key> = new NestedParties44().getFragmentAllTags();
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Static Block">
static {
ALL_TAGS = new HashSet<Integer>(TAGS_V44);
ALL_TAGS.addAll(<API key>);
ALL_TAGS.addAll(<API key>);
ALL_TAGS.addAll(<API key>);
ALL_TAGS.addAll(<API key>);
START_COMP_TAGS = new HashSet<Integer>(<API key>);
START_COMP_TAGS.addAll(<API key>);
START_COMP_TAGS.addAll(<API key>);
START_COMP_TAGS.addAll(<API key>);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Attributes">
protected Set<Integer> <API key> = ALL_TAGS;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Constructors">
public LegOrdGroup44() {
super();
SECURED_TAGS = <API key>;
}
public LegOrdGroup44(FragmentContext context) {
super(context);
SECURED_TAGS = <API key>;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Public Methods">
@Override
public Set<Integer> getFragmentAllTags() {
return ALL_TAGS;
}
// ACCESSOR METHODS
@XmlElementRef
@Override
public InstrumentLeg getInstrumentLeg() {
return instrumentLeg;
}
@Override
public void setInstrumentLeg() {
FragmentContext context = new FragmentContext(sessionCharset, messageEncoding, encryptionRequired, crypter, validateRequired);
instrumentLeg = new InstrumentLeg44(context);
}
@Override
public void clearInstrumentLeg() {
instrumentLeg = null;
}
public void setInstrumentLeg(InstrumentLeg instrumentLeg) {
this.instrumentLeg = instrumentLeg;
}
@XmlAttribute(name = "Qty")
@Override
public Double getLegQty() {
return legQty;
}
@Override
public void setLegQty(Double legQty) {
this.legQty = legQty;
}
@XmlAttribute(name = "SwapTyp")
@Override
public LegSwapType getLegSwapType() {
return legSwapType;
}
@Override
public void setLegSwapType(LegSwapType legSwapType) {
this.legSwapType = legSwapType;
}
@Override
public LegStipulations getLegStipulations() {
return legStipulations;
}
@Override
public void setLegStipulations() {
FragmentContext context = new FragmentContext(sessionCharset, messageEncoding, encryptionRequired, crypter, validateRequired);
this.legStipulations = new LegStipulations44(context);
}
@Override
public void <API key>() {
this.legStipulations = null;
}
@XmlElementRef
public <API key>[] <API key>() {
return legStipulations == null ? null : legStipulations.<API key>();
}
public void <API key>(<API key>[] <API key>) {
if (<API key> != null) {
if (legStipulations == null) {
setLegStipulations();
}
((LegStipulations44) legStipulations).<API key>(<API key>);
}
}
@Override
public Integer getNoLegAllocs() {
return noLegAllocs;
}
@Override
public void setNoLegAllocs(Integer noLegAllocs) {
this.noLegAllocs = noLegAllocs;
if (noLegAllocs != null) {
legAllocGroups = new LegAllocGroup[noLegAllocs.intValue()];
for (int i = 0; i < legAllocGroups.length; i++) {
legAllocGroups[i] = new LegAllocGroup44(new FragmentContext(sessionCharset, messageEncoding, validateRequired));
}
}
}
@XmlElementRef
@Override
public LegAllocGroup[] getLegAllocGroups() {
return legAllocGroups;
}
public void setLegAllocGroups(LegAllocGroup[] legAllocGroups) {
this.legAllocGroups = legAllocGroups;
if (legAllocGroups != null) {
noLegAllocs = new Integer(legAllocGroups.length);
}
}
@Override
public LegAllocGroup addLegAllocGroup() {
LegAllocGroup group = new LegAllocGroup44(new FragmentContext(sessionCharset, messageEncoding, validateRequired));
List<LegAllocGroup> groups = new ArrayList<LegAllocGroup>();
if (legAllocGroups != null && legAllocGroups.length > 0) {
groups = new ArrayList<LegAllocGroup>(Arrays.asList(legAllocGroups));
}
groups.add(group);
legAllocGroups = groups.toArray(new LegAllocGroup[groups.size()]);
noLegAllocs = new Integer(legAllocGroups.length);
return group;
}
@Override
public LegAllocGroup deleteLegAllocGroup(int index) {
LegAllocGroup result = null;
if (legAllocGroups != null && legAllocGroups.length > 0 && legAllocGroups.length > index) {
List<LegAllocGroup> groups = new ArrayList<LegAllocGroup>(Arrays.asList(legAllocGroups));
result = groups.remove(index);
legAllocGroups = groups.toArray(new LegAllocGroup[groups.size()]);
if (legAllocGroups.length > 0) {
noLegAllocs = new Integer(legAllocGroups.length);
} else {
legAllocGroups = null;
noLegAllocs = null;
}
}
return result;
}
@Override
public int clearLegAllocGroups() {
int result = 0;
if (legAllocGroups != null && legAllocGroups.length > 0) {
result = legAllocGroups.length;
legAllocGroups = null;
noLegAllocs = null;
}
return result;
}
@XmlAttribute(name = "PosEfct")
@Override
public PositionEffect <API key>() {
return legPositionEffect;
}
@Override
public void <API key>(PositionEffect legPositionEffect) {
this.legPositionEffect = legPositionEffect;
}
@XmlAttribute(name = "Cover")
@Override
public CoveredOrUncovered <API key>() {
return <API key>;
}
@Override
public void <API key>(CoveredOrUncovered <API key>) {
this.<API key> = <API key>;
}
@Override
public NestedParties getNestedParties() {
return nestedParties;
}
@Override
public void setNestedParties() {
FragmentContext context = new FragmentContext(sessionCharset, messageEncoding, encryptionRequired, crypter, validateRequired);
this.nestedParties = new NestedParties44(context);
}
@Override
public void clearNestedParties() {
this.nestedParties = null;
}
@XmlElementRef
public NestedPartyGroup[] <API key>() {
return nestedParties == null ? null : nestedParties.<API key>();
}
public void <API key>(NestedPartyGroup[] nestedPartyIDGroups) {
if (nestedPartyIDGroups != null) {
if (nestedParties == null) {
setNestedParties();
}
((NestedParties44) nestedParties).<API key>(nestedPartyIDGroups);
}
}
@XmlAttribute(name = "RefID")
@Override
public String getLegRefID() {
return legRefID;
}
@Override
public void setLegRefID(String legRefID) {
this.legRefID = legRefID;
}
@XmlAttribute(name = "Px")
@Override
public Double getLegPrice() {
return legPrice;
}
@Override
public void setLegPrice(Double legPrice) {
this.legPrice = legPrice;
}
@XmlAttribute(name = "SettlTyp")
@Override
public String getLegSettlType() {
return legSettlType;
}
@Override
public void setLegSettlType(String legSettlType) {
this.legSettlType = legSettlType;
}
@XmlAttribute(name = "SettlDt")
@XmlJavaTypeAdapter(FixDateAdapter.class)
@Override
public Date getLegSettlDate() {
return legSettlDate;
}
@Override
public void setLegSettlDate(Date legSettlDate) {
this.legSettlDate = legSettlDate;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Protected Methods">
@Override
protected byte[] <API key>(boolean secured) throws <API key>, <API key> {
byte[] result = new byte[0];
<API key> bao = new <API key>();
try {
bao.write(instrumentLeg.encode(<API key>(secured)));
if (MsgUtil.isTagInList(TagNum.LegQty, SECURED_TAGS, secured)) {
TagEncoder.encode(bao, TagNum.LegQty, legQty);
}
if (legSwapType != null && MsgUtil.isTagInList(TagNum.LegSwapType, SECURED_TAGS, secured)) {
TagEncoder.encode(bao, TagNum.LegSwapType, legSwapType.getValue());
}
if (legStipulations != null) {
bao.write(legStipulations.encode(<API key>(secured)));
}
if (noLegAllocs != null && MsgUtil.isTagInList(TagNum.NoLegAllocs, SECURED_TAGS, secured)) {
TagEncoder.encode(bao, TagNum.NoLegAllocs, noLegAllocs);
if (legAllocGroups != null && legAllocGroups.length == noLegAllocs.intValue()) {
for (int i = 0; i < noLegAllocs.intValue(); i++) {
if (legAllocGroups[i] != null) {
bao.write(legAllocGroups[i].encode(<API key>(secured)));
}
}
} else {
String error = "LegAllocGroups field has been set but there is no data or the number of groups does not match.";
LOGGER.severe(error);
throw new <API key>(SessionRejectReason.<API key>, TagNum.NoLegAllocs.getValue(), error);
}
}
if (legPositionEffect != null && MsgUtil.isTagInList(TagNum.LegPositionEffect, SECURED_TAGS, secured)) {
TagEncoder.encode(bao, TagNum.LegPositionEffect, legPositionEffect.getValue());
}
if (<API key> != null && MsgUtil.isTagInList(TagNum.<API key>, SECURED_TAGS, secured)) {
TagEncoder.encode(bao, TagNum.<API key>, <API key>.getValue());
}
if (nestedParties != null) {
bao.write(nestedParties.encode(<API key>(secured)));
}
if (MsgUtil.isTagInList(TagNum.LegRefID, SECURED_TAGS, secured)) {
TagEncoder.encode(bao, TagNum.LegRefID, legRefID);
}
if (MsgUtil.isTagInList(TagNum.LegPrice, SECURED_TAGS, secured)) {
TagEncoder.encode(bao, TagNum.LegPrice, legPrice);
}
if (MsgUtil.isTagInList(TagNum.LegSettlType, SECURED_TAGS, secured)) {
TagEncoder.encode(bao, TagNum.LegSettlType, legSettlType);
}
if (MsgUtil.isTagInList(TagNum.LegSettlDate, SECURED_TAGS, secured)) {
TagEncoder.encodeDate(bao, TagNum.LegSettlDate, legSettlDate);
}
result = bao.toByteArray();
} catch (IOException ex) {
String error = "Error writing to the byte array.";
LOGGER.log(Level.SEVERE, "{0} Error was : {1}", new Object[] { error, ex.toString() });
throw new <API key>(error, ex);
}
return result;
}
@Override
protected void <API key>(Tag tag, ByteBuffer message)
throws <API key>, InvalidMsgException, <API key> {
FragmentContext context = new FragmentContext(sessionCharset, messageEncoding, encryptionRequired, crypter, validateRequired);
if (<API key>.contains(tag.tagNum)) {
if (instrumentLeg == null) {
instrumentLeg = new InstrumentLeg44(context);
}
instrumentLeg.decode(tag, message);
}
if (<API key>.contains(tag.tagNum)) {
if (legStipulations == null) {
legStipulations = new LegStipulations44(context);
}
legStipulations.decode(tag, message);
}
if (<API key>.contains(tag.tagNum)) {
if (noLegAllocs != null && noLegAllocs.intValue() > 0) {
message.reset();
legAllocGroups = new LegAllocGroup44[noLegAllocs.intValue()];
for (int i = 0; i < noLegAllocs.intValue(); i++) {
LegAllocGroup group = new LegAllocGroup44(context);
group.decode(message);
legAllocGroups[i] = group;
}
}
}
if (<API key>.contains(tag.tagNum)) {
if (nestedParties == null) {
nestedParties = new NestedParties44(context);
}
nestedParties.decode(tag, message);
}
}
@Override
protected String <API key>() {
return "This tag is not supported in [LegOrdGroup] group version [4.4].";
}
@Override
protected Set<Integer> getFragmentCompTags() {
return START_COMP_TAGS;
}
@Override
protected Set<Integer> <API key>() {
return SECURED_TAGS;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Package Methods">
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Private Methods">
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Inner Classes">
// </editor-fold>
} |
package com.liumapp.DNSBrood.forward;
import com.liumapp.DNSBrood.concurrent.ThreadPools;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xbill.DNS.Message;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.*;
@Component
public class MultiUDPReceiver implements InitializingBean {
private static final int dnsPackageLength = 512;
private Map<String, ForwardAnswer> answers = new ConcurrentHashMap<String, ForwardAnswer>();
private DatagramChannel datagramChannel;
private final static int PORT_RECEIVE = 40311;
private DelayQueue<DelayStringKey> delayRemoveQueue = new DelayQueue<DelayStringKey>();
private static class DelayStringKey implements Delayed {
private final String key;
private final long initDelay;
private long startTime;
/**
* @param key
* @param initDelay in ms
*/
public DelayStringKey(String key, long initDelay) {
this.startTime = System.currentTimeMillis();
this.key = key;
this.initDelay = initDelay;
}
public String getKey() {
return key;
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Delayed o) {
long delayA = startTime + initDelay - System.currentTimeMillis();
long delayB = o.getDelay(TimeUnit.MILLISECONDS);
if (delayA > delayB) {
return 1;
} else if (delayA < delayB) {
return -1;
} else {
return 0;
}
}
/*
* (non-Javadoc)
*
* @see
* java.util.concurrent.Delayed#getDelay(java.util.concurrent.TimeUnit)
*/
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(
startTime + initDelay - System.currentTimeMillis(),
TimeUnit.MILLISECONDS);
}
}
@Autowired
private ThreadPools threadPools;
@Autowired
private <API key> <API key>;
private Logger logger = Logger.getLogger(getClass());
public MultiUDPReceiver() {
super();
}
private String getKey(Message message) {
return message.getHeader().getID() + "_"
+ message.getQuestion().getName().toString() + "_"
+ message.getQuestion().getType();
}
public void registerReceiver(Message message, ForwardAnswer forwardAnswer) {
answers.put(getKey(message), forwardAnswer);
}
public ForwardAnswer getAnswer(Message message) {
return answers.get(getKey(message));
}
/**
* Add answer to remove queue and remove when timeout.
* @param message
* @param timeOut
*/
public void delayRemoveAnswer(Message message, long timeOut) {
delayRemoveQueue.add(new DelayStringKey(getKey(message), timeOut));
}
private void receive() {
ExecutorService processExecutors = threadPools.<API key>();
final ByteBuffer byteBuffer = ByteBuffer.allocate(dnsPackageLength);
while (true) {
try {
byteBuffer.clear();
final SocketAddress remoteAddress = datagramChannel
.receive(byteBuffer);
final byte[] answer = Arrays.copyOfRange(byteBuffer.array(), 0,
dnsPackageLength);
processExecutors.submit(new Runnable() {
@Override
public void run() {
try {
final Message message = new Message(answer);
<API key>.handleAnswer(answer, message, remoteAddress, getAnswer(message));
} catch (Throwable e) {
logger.warn("forward exception " + e);
}
}
});
} catch (Throwable e) {
logger.warn("receive exception" + e);
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
datagramChannel = DatagramChannel.open();
try {
datagramChannel.socket().bind(new InetSocketAddress(PORT_RECEIVE));
} catch (IOException e) {
System.err.println("Startup fail, maybe another process is running.");
logger.error("Startup fail, maybe another process is running.", e);
System.exit(-1);
}
datagramChannel.configureBlocking(true);
Thread threadForReceive = new Thread(new Runnable() {
@Override
public void run() {
receive();
}
});
threadForReceive.setDaemon(true);
threadForReceive.start();
Thread threadForRemove = new Thread(new Runnable() {
@Override
public void run() {
<API key>();
}
});
threadForRemove.setDaemon(true);
threadForRemove.start();
}
private void <API key>() {
while (true) {
try {
DelayStringKey delayRemoveKey = delayRemoveQueue.take();
ForwardAnswer forwardAnswer = answers.get(delayRemoveKey.getKey());
if (forwardAnswer != null && forwardAnswer.getTempAnswer() != null) {
forwardAnswer.getResponser().response(forwardAnswer.getTempAnswer().toWire());
}
answers.remove(delayRemoveKey.getKey());
if (logger.isDebugEnabled()) {
logger.debug("remove key " + delayRemoveKey.getKey());
}
} catch (Exception e) {
logger.warn("remove answer error", e);
}
}
}
/**
* @return the datagramChannel
*/
public DatagramChannel getDatagramChannel() {
return datagramChannel;
}
} |
__docformat__ = 'restructuredtext en'
import sys
import threading
import os
from ctypes import *
from ctypes.util import find_library
import time
import logging
from Skype4Py.api import Command, SkypeAPIBase, \
timeout2float, finalize_opts
from Skype4Py.enums import *
from Skype4Py.errors import SkypeAPIError
__all__ = ['SkypeAPI', 'threads_init']
# The Xlib Programming Manual:
# some Xlib constants
PropertyChangeMask = 0x400000
PropertyNotify = 28
ClientMessage = 33
PropertyNewValue = 0
PropertyDelete = 1
# some Xlib types
c_ulong_p = POINTER(c_ulong)
DisplayP = c_void_p
Atom = c_ulong
AtomP = c_ulong_p
XID = c_ulong
Window = XID
Bool = c_int
Status = c_int
Time = c_ulong
c_int_p = POINTER(c_int)
# should the structures be aligned to 8 bytes?
align = (sizeof(c_long) == 8 and sizeof(c_int) == 4)
# some Xlib structures
class XClientMessageEvent(Structure):
if align:
_fields_ = [('type', c_int),
('pad0', c_int),
('serial', c_ulong),
('send_event', Bool),
('pad1', c_int),
('display', DisplayP),
('window', Window),
('message_type', Atom),
('format', c_int),
('pad2', c_int),
('data', c_char * 20)]
else:
_fields_ = [('type', c_int),
('serial', c_ulong),
('send_event', Bool),
('display', DisplayP),
('window', Window),
('message_type', Atom),
('format', c_int),
('data', c_char * 20)]
class XPropertyEvent(Structure):
if align:
_fields_ = [('type', c_int),
('pad0', c_int),
('serial', c_ulong),
('send_event', Bool),
('pad1', c_int),
('display', DisplayP),
('window', Window),
('atom', Atom),
('time', Time),
('state', c_int),
('pad2', c_int)]
else:
_fields_ = [('type', c_int),
('serial', c_ulong),
('send_event', Bool),
('display', DisplayP),
('window', Window),
('atom', Atom),
('time', Time),
('state', c_int)]
class XErrorEvent(Structure):
if align:
_fields_ = [('type', c_int),
('pad0', c_int),
('display', DisplayP),
('resourceid', XID),
('serial', c_ulong),
('error_code', c_ubyte),
('request_code', c_ubyte),
('minor_code', c_ubyte)]
else:
_fields_ = [('type', c_int),
('display', DisplayP),
('resourceid', XID),
('serial', c_ulong),
('error_code', c_ubyte),
('request_code', c_ubyte),
('minor_code', c_ubyte)]
class XEvent(Union):
if align:
_fields_ = [('type', c_int),
('xclient', XClientMessageEvent),
('xproperty', XPropertyEvent),
('xerror', XErrorEvent),
('pad', c_long * 24)]
else:
_fields_ = [('type', c_int),
('xclient', XClientMessageEvent),
('xproperty', XPropertyEvent),
('xerror', XErrorEvent),
('pad', c_long * 24)]
XEventP = POINTER(XEvent)
if getattr(sys, 'skype4py_setup', False):
# we get here if we're building docs; to let the module import without
# exceptions, we emulate the X11 library using a class:
class X(object):
def __getattr__(self, name):
return self
def __setattr__(self, name, value):
pass
def __call__(self, *args, **kwargs):
pass
x11 = X()
else:
# load X11 library (Xlib)
libpath = find_library('X11')
if not libpath:
raise ImportError('Could not find X11 library')
x11 = cdll.LoadLibrary(libpath)
del libpath
# setup Xlib function prototypes
x11.XCloseDisplay.argtypes = (DisplayP,)
x11.XCloseDisplay.restype = None
x11.XCreateSimpleWindow.argtypes = (DisplayP, Window, c_int, c_int, c_uint,
c_uint, c_uint, c_ulong, c_ulong)
x11.XCreateSimpleWindow.restype = Window
x11.XDefaultRootWindow.argtypes = (DisplayP,)
x11.XDefaultRootWindow.restype = Window
x11.XDeleteProperty.argtypes = (DisplayP, Window, Atom)
x11.XDeleteProperty.restype = None
x11.XDestroyWindow.argtypes = (DisplayP, Window)
x11.XDestroyWindow.restype = None
x11.XFree.argtypes = (c_void_p,)
x11.XFree.restype = None
x11.XGetAtomName.argtypes = (DisplayP, Atom)
x11.XGetAtomName.restype = c_void_p
x11.XGetErrorText.argtypes = (DisplayP, c_int, c_char_p, c_int)
x11.XGetErrorText.restype = None
x11.XGetWindowProperty.argtypes = (DisplayP, Window, Atom, c_long, c_long, Bool,
Atom, AtomP, c_int_p, c_ulong_p, c_ulong_p, POINTER(POINTER(Window)))
x11.XGetWindowProperty.restype = c_int
x11.XInitThreads.argtypes = ()
x11.XInitThreads.restype = Status
x11.XInternAtom.argtypes = (DisplayP, c_char_p, Bool)
x11.XInternAtom.restype = Atom
x11.XNextEvent.argtypes = (DisplayP, XEventP)
x11.XNextEvent.restype = None
x11.XOpenDisplay.argtypes = (c_char_p,)
x11.XOpenDisplay.restype = DisplayP
x11.XPending.argtypes = (DisplayP,)
x11.XPending.restype = c_int
x11.XSelectInput.argtypes = (DisplayP, Window, c_long)
x11.XSelectInput.restype = None
x11.XSendEvent.argtypes = (DisplayP, Window, Bool, c_long, XEventP)
x11.XSendEvent.restype = Status
x11.XLockDisplay.argtypes = (DisplayP,)
x11.XLockDisplay.restype = None
x11.XUnlockDisplay.argtypes = (DisplayP,)
x11.XUnlockDisplay.restype = None
def threads_init(gtk=True):
"""Enables multithreading support in Xlib and PyGTK.
See the module docstring for more info.
:Parameters:
gtk : bool
May be set to False to skip the PyGTK module.
"""
# enable X11 multithreading
x11.XInitThreads()
if gtk:
from gtk.gdk import threads_init
threads_init()
class SkypeAPI(SkypeAPIBase):
def __init__(self, opts):
self.logger = logging.getLogger('Skype4Py.api.posix_x11.SkypeAPI')
SkypeAPIBase.__init__(self)
finalize_opts(opts)
# initialize threads if not done already by the user
threads_init(gtk=False)
# init Xlib display
self.disp = x11.XOpenDisplay(None)
if not self.disp:
raise SkypeAPIError('Could not open XDisplay')
self.win_root = x11.XDefaultRootWindow(self.disp)
self.win_self = x11.XCreateSimpleWindow(self.disp, self.win_root,
100, 100, 100, 100, 1, 0, 0)
x11.XSelectInput(self.disp, self.win_root, PropertyChangeMask)
self.win_skype = self.get_skype()
ctrl = '<API key>'
self.atom_msg = x11.XInternAtom(self.disp, ctrl, False)
self.atom_msg_begin = x11.XInternAtom(self.disp, ctrl + '_BEGIN', False)
self.loop_event = threading.Event()
self.loop_timeout = 0.0001
self.loop_break = False
def __del__(self):
if x11:
if hasattr(self, 'disp'):
if hasattr(self, 'win_self'):
x11.XDestroyWindow(self.disp, self.win_self)
x11.XCloseDisplay(self.disp)
def run(self):
self.logger.info('thread started')
# main loop
event = XEvent()
data = ''
while not self.loop_break and x11:
while x11.XPending(self.disp):
self.loop_timeout = 0.0001
x11.XNextEvent(self.disp, byref(event))
# events we get here are already prefiltered by the predicate function
if event.type == ClientMessage:
if event.xclient.format == 8:
if event.xclient.message_type == self.atom_msg_begin:
data = str(event.xclient.data)
elif event.xclient.message_type == self.atom_msg:
if data != '':
data += str(event.xclient.data)
else:
self.logger.warning('Middle of Skype X11 message received with no beginning!')
else:
continue
if len(event.xclient.data) != 20 and data:
self.notify(data.decode('utf-8'))
data = ''
elif event.type == PropertyNotify:
namep = x11.XGetAtomName(self.disp, event.xproperty.atom)
is_inst = (c_char_p(namep).value == '_SKYPE_INSTANCE')
x11.XFree(namep)
if is_inst:
if event.xproperty.state == PropertyNewValue:
self.win_skype = self.get_skype()
# changing attachment status can cause an event handler to be fired, in
# turn it could try to call Attach() and doing this immediately seems to
# confuse Skype (command '#0 NAME xxx' returns '#0 CONNSTATUS OFFLINE' :D);
# to fix this, we give Skype some time to initialize itself
time.sleep(1.0)
self.<API key>(apiAttachAvailable)
elif event.xproperty.state == PropertyDelete:
self.win_skype = None
self.<API key>(<API key>)
self.loop_event.wait(self.loop_timeout)
if self.loop_event.isSet():
self.loop_timeout = 0.0001
elif self.loop_timeout < 1.0:
self.loop_timeout *= 2
self.loop_event.clear()
self.logger.info('thread finished')
def get_skype(self):
"""Returns Skype window ID or None if Skype not running."""
skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True)
if not skype_inst:
return
type_ret = Atom()
format_ret = c_int()
nitems_ret = c_ulong()
bytes_after_ret = c_ulong()
winp = pointer(Window())
fail = x11.XGetWindowProperty(self.disp, self.win_root, skype_inst,
0, 1, False, 33, byref(type_ret), byref(format_ret),
byref(nitems_ret), byref(bytes_after_ret), byref(winp))
if not fail and format_ret.value == 32 and nitems_ret.value == 1:
return winp.contents.value
def close(self):
self.loop_break = True
self.loop_event.set()
while self.isAlive():
time.sleep(0.01)
SkypeAPIBase.close(self)
def set_friendly_name(self, friendly_name):
SkypeAPIBase.set_friendly_name(self, friendly_name)
if self.attachment_status == apiAttachSuccess:
# reattach with the new name
self.<API key>(apiAttachUnknown)
self.attach()
def attach(self, timeout, wait=True):
if self.attachment_status == apiAttachSuccess:
return
self.acquire()
try:
if not self.isAlive():
try:
self.start()
except AssertionError:
raise SkypeAPIError('Skype API closed')
try:
self.wait = True
t = threading.Timer(timeout2float(timeout), lambda: setattr(self, 'wait', False))
if wait:
t.start()
while self.wait:
self.win_skype = self.get_skype()
if self.win_skype is not None:
break
else:
time.sleep(1.0)
else:
raise SkypeAPIError('Skype attach timeout')
finally:
t.cancel()
command = Command('NAME %s' % self.friendly_name, '', True, timeout)
self.release()
try:
self.send_command(command, True)
finally:
self.acquire()
if command.Reply != 'OK':
self.win_skype = None
self.<API key>(apiAttachRefused)
return
self.<API key>(apiAttachSuccess)
finally:
self.release()
command = Command('PROTOCOL %s' % self.protocol, Blocking=True)
self.send_command(command, True)
self.protocol = int(command.Reply.rsplit(None, 1)[-1])
def is_running(self):
return (self.get_skype() is not None)
def startup(self, minimized, nosplash):
# options are not supported as of Skype 1.4 Beta for Linux
if not self.is_running():
if os.fork() == 0: # we're the child
os.setsid()
os.execlp('skype')
def shutdown(self):
from signal import SIGINT
fh = os.popen('ps -o %p --no-heading -C skype')
pid = fh.readline().strip()
fh.close()
if pid:
os.kill(int(pid), SIGINT)
# Skype sometimes doesn't delete the '_SKYPE_INSTANCE' property
skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True)
if skype_inst:
x11.XDeleteProperty(self.disp, self.win_root, skype_inst)
self.win_skype = None
self.<API key>(<API key>)
def send_command(self, command, force=False):
if self.attachment_status != apiAttachSuccess and not force:
self.attach(command.Timeout)
self.push_command(command)
self.notifier.sending_command(command)
cmd = u'#%d %s' % (command.Id, command.Command)
self.logger.debug('sending %s', repr(cmd))
if command.Blocking:
command._event = bevent = threading.Event()
else:
command._timer = timer = threading.Timer(command.timeout2float(), self.pop_command, (command.Id,))
event = XEvent()
event.xclient.type = ClientMessage
event.xclient.display = self.disp
event.xclient.window = self.win_self
event.xclient.message_type = self.atom_msg_begin
event.xclient.format = 8
cmd = cmd.encode('utf-8') + '\x00'
for i in xrange(0, len(cmd), 20):
event.xclient.data = cmd[i:i + 20]
x11.XSendEvent(self.disp, self.win_skype, False, 0, byref(event))
event.xclient.message_type = self.atom_msg
self.loop_event.set()
if command.Blocking:
bevent.wait(command.timeout2float())
if not bevent.isSet():
raise SkypeAPIError('Skype command timeout')
else:
timer.start()
def notify(self, cmd):
self.logger.debug('received %s', repr(cmd))
# Called by main loop for all received Skype commands.
if cmd.startswith(u'
p = cmd.find(u' ')
command = self.pop_command(int(cmd[1:p]))
if command is not None:
command.Reply = cmd[p + 1:]
if command.Blocking:
command._event.set()
else:
command._timer.cancel()
self.notifier.reply_received(command)
else:
self.notifier.<API key>(cmd[p + 1:])
else:
self.notifier.<API key>(cmd) |
package com.blockhaus2000.ipm.technical.interception.exception;
/**
* A {@link TransformException} is thrown if some error occur whilst
* transforming any classes.
*
*/
public class TransformException extends <API key> {
/**
* The serial version UID.
*
*/
private static final long serialVersionUID = <API key>;
/**
* Constructor of TransformException.
*
*/
public TransformException() {
super();
}
/**
* Constructor of TransformException.
*
* @param message
* The detailed error message.
* @param cause
* The cause of this exception.
*/
public TransformException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Constructor of TransformException.
*
* @param message
* The detailed error message.
*/
public TransformException(final String message) {
super(message);
}
/**
* Constructor of TransformException.
*
* @param cause
* The cause of this exception.
*/
public TransformException(final Throwable cause) {
super(cause);
}
} |
package com.hacks.collegebarter.fragments;
import com.hacks.collegebarter.R;
import com.hacks.collegebarter.navdrawer.MainAppActivity;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FollowingFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
// Following constructor
public FollowingFragment() {
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, 4);
this.setArguments(bundle);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.trackitems_fragment,
container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainAppActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
} |
#ifndef ANIMATION_STATE_HPP
#define ANIMATION_STATE_HPP
namespace m2g {
class AnimationState {
public:
AnimationState();
AnimationState( unsigned int firstFrame,
unsigned int lastFrame );
AnimationState( unsigned int firstFrame,
unsigned int lastFrame,
unsigned int backFrame );
bool operator == ( const AnimationState& b ) const;
const unsigned int firstFrame;
const unsigned int lastFrame;
const unsigned int backFrame;
private:
void <API key>() const;
};
} // namespace m2g
#endif // ANIMATION_STATE_HPP |
from operator import itemgetter
import logging
def test_coder():
# original = [1,2,3,3,3,4,18,18,2,3,4,4,4,5]
# original = [1, 2, 3, 3, 3, 4, 18, 18, 2, 3, 4, 4, 4, 5, 44, 44, 45, 46, 46, 46, 49, 49, 49, 45]
original = [1, 2, 0, 0, 0, 0, 3, 3, 3, 4, 18, 18, 2, 3, 4, 4, 4, 5, 44, 44, 45, 46, 46, 46, 49, 49, 49, 45]
encoded = rle_encode(original)
decoded = rle_decode(encoded)
code_matches(original, decoded)
def code_matches(original, decoded):
if len(original) != len(decoded):
logging.error("Gebo at array comparison")
logging.error("orig: %s ", original)
logging.error("dec: %s", decoded)
return
for i in range(0, len(decoded)):
if original[i] != decoded[i]:
logging.error("Gebo at array comparison")
logging.error("orig: %s ", original)
logging.error("dec: %s", decoded)
return
logging.info("hooray")
def rle_encode(memberships):
last_member = None
repeats = 1
rle_str = ''
# ASCII 48 to 57 are digits -> move them above 230 (add 182)
for member in memberships:
if 48 <= member < 58:
member += 182
if last_member is None:
last_member = member
continue
# if member == last_member:
# repeats += 1
if member == last_member:
repeats += 1
else:
if repeats < 2:
rle_str += chr(last_member)
else:
rle_str += str(repeats) + chr(last_member)
repeats = 1
last_member = member
if repeats != 0:
if repeats < 2:
rle_str += chr(last_member)
else:
rle_str += str(repeats) + chr(last_member)
return rle_str
def rle_decode(encoded):
number_str = ''
numbers = list()
for char in encoded:
if 48 <= ord(char) < 58:
number_str += char
else:
if ord(char) >= 230:
char = chr(ord(char) - 182)
if len(number_str) != 0:
repeat = int(number_str)
number_str = ''
for i in range(0, repeat):
numbers.append(ord(char))
else:
numbers.append(ord(char))
return numbers
def rle_encode_as_str(memberships):
last_member = None
repeats = 0
rle_str = ''
# work_array = memberships[:100]
rep_dict = dict()
for member in memberships:
if not last_member:
last_member = member
if member == last_member:
repeats += 1
else:
if repeats < 2:
rle_str += chr(member)
else:
if str(repeats) not in rep_dict:
rep_dict[str(repeats)] = 1
else:
rep_dict[str(repeats)] += 1
rle_str += str(repeats) + chr(member)
repeats = 0
last_member = member
if repeats != 0:
if repeats < 2:
rle_str += chr(member)
else:
rle_str += str(repeats) + chr(member)
distinct_saving = 0
savings = list()
for key in rep_dict.keys():
cost = len(key) + 1
repeats = rep_dict[key]
saving = len(key) * repeats
profit = saving - cost
if profit > 0:
savings.append((key, profit))
distinct_saving += profit
savings.sort(key=itemgetter(1), reverse=True)
# last number is ASCII 57, we're good to go until 255
char_coded = 58
# encoding_table = dict()
enc_str = rle_str
for saving in savings:
# encoding_table[saving[0]] = char_coded
enc_str = enc_str.replace(saving[0], chr(char_coded))
char_coded += 1
if char_coded > 255:
break
print("Orig {} - mod {}".format(len(rle_str), len(enc_str)))
return rle_str
def main():
test_coder()
if __name__ == "__main__":
main() |
<?php
// Text
$_['text_subject'] = 'You have been sent a gift voucher from %s';
$_['text_greeting'] = 'Congratulations, You have received a Gift Certificate worth %s';
$_['text_from'] = 'This Gift Certificate has been sent to you by %s';
$_['text_message'] = 'With a message saying';
$_['text_redeem'] = 'To redeem this Gift Certificate, write down the redemption code which is <b>%s</b> then click on the the link below and purchase the product you wish to use this gift voucher on. You can enter the gift voucher code on the shopping cart page before you click checkout.';
$_['text_footer'] = 'Please reply to this e-mail if you have any questions.'; |
#!/bin/bash
mkdir -p _build
(
cd _build
rm -f moose*.dmg
rm -rf moose-3.0.1-Linux*
cmake -<API key>=/Moose.app ..
make -j4
#cpack -G Bundle
cpack -G DragNDrop -V
7z x moose-3.0.1-Linux-.dmg
) |
// Angular
import '@angular/platform-browser';
import '@angular/<API key>';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';
// RxJS
import 'rxjs';
// Other vendors for example jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...
import '../node_modules/purecss/build/pure.css';
import '../node_modules/purecss/build/<API key>.css';
import './assets/css/style.css'; |
/* CELIA Tools / Shape Abstract Domain */
/* you can redistribute it and/or modify it under the terms of the GNU */
/* Foundation, version 3. */
/* It is distributed in the hope that it will be useful, */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
long int lrand48 (void);
void srand48 (long int seedval);
#include "ushape.h"
#include "ushape_fun.h"
#include "ushape_internal.h"
#include "apron2shape.h"
ap_manager_t *ms; /* shape manager */
shape_internal_t *pr;
size_t realdim = 6 + 3; /* vars x,y,z */
size_t intdim = 3; /* vars _l, _k, d */
size_t SIZE = 4; /* nb of nodes */
char *names_dim[12] = { "_l", "_k", "d", "_data", "_free", "_len",
"_next", "_new", "_null", "x", "xi", "y"
};
#define DIM_NULL 8
#define DIM_X 9
#define DIM_Y 11
#define MAXN 50000
int N = 7;
char b1_[MAXN + 4] = " [";
char b2_[MAXN + 4];
int i_;
typedef enum
{ none = 0, best = 1, exact = 2 } exactness;
exactness flag;
#define LOOP \
{ \
memset(b1_+2,' ',N); b1_[N+2]=']'; b1_[N+3]=0; \
memset(b2_,8,N+3); b2_[N+3]=0; \
for (i_=0;i_<N;i_++) { \
if (N<80) printf("%s%s",b1_,b2_); \
else if (i_) printf("%c",b1_[i_+1]); \
fflush(stdout); \
flag = exact; \
#define FLAG(m) \
if (m->result.flag_exact) ; \
else if (m->result.flag_best && flag==exact) flag = best; \
else flag = none;
#define RESULT(c) b1_[i_+2]=c
#define ERROR_RESULT(msg) ERROR(msg,RESULT('!');)
#define ENDLOOP \
} } \
if (N<80) printf("%s%s\n",b1_,b2_); \
else printf("%c",b1_[i_+2])
void
print_ushape (const char *msg, ushape_t * a)
{
fprintf (stdout, "%s = ", msg);
ushape_fprint (stdout, ms, a, names_dim);
//ushape_fdump(stdout,ms,a);
fprintf (stdout, "\n");
}
/* chose one linexpr within an interval linexpr */
/* TOD0: used? */
ap_linexpr0_t *
random_from_linexpr (ap_linexpr0_t * a)
{
size_t i;
ap_linexpr0_t *l = ap_linexpr0_alloc (AP_LINEXPR_DENSE, a->size);
assert (a->discr == AP_LINEXPR_DENSE);
for (i = 0; i < a->size; i++)
{
switch (a->p.coeff[i].discr)
{
case AP_COEFF_SCALAR:
ap_coeff_set_scalar (l->p.coeff + i, a->p.coeff[i].val.scalar);
break;
case AP_COEFF_INTERVAL:
if (lrand48 () % 10 > 8)
ap_coeff_set_scalar (l->p.coeff + i,
a->p.coeff[i].val.interval->inf);
else
ap_coeff_set_scalar (l->p.coeff + i,
a->p.coeff[i].val.interval->sup);
break;
}
}
switch (a->cst.discr)
{
case AP_COEFF_SCALAR:
ap_coeff_set_scalar (&l->cst, a->cst.val.scalar);
break;
case AP_COEFF_INTERVAL:
if (lrand48 () % 10 > 8)
ap_coeff_set_scalar (&l->cst, a->cst.val.interval->inf);
else
ap_coeff_set_scalar (&l->cst, a->cst.val.interval->sup);
break;
}
return l;
}
/* TODO: used? */
ap_lincons0_t
random_from_lincons (ap_lincons0_t a)
{
return ap_lincons0_make (a.constyp, random_from_linexpr (a.linexpr0), NULL);
}
/* infos */
void
info (void)
{
printf ("ushapes: %s (%s)\n", ms->library, ms->version);
/*
printf("nums: %s (%s wto overflow,%s)\n",NUM_NAME,
num_safe ? "sound" : "unsound",
num_incomplete ? "incomplete" : "complete");
*/
}
/* various tests */
void
test_misc (void)
{
int i;
ushape_t *bot = ushape_bottom (ms, intdim, realdim);
ushape_t *top = ushape_top (ms, intdim, realdim);
ap_dimension_t d1 = ushape_dimension (ms, bot);
ap_dimension_t d2 = ushape_dimension (ms, top);
printf ("\nperforming various tests\n");
if (ushape_check (pr, bot) != '.')
printf ("ushape_bottom failed
if (ushape_check (pr, top) != '.')
printf ("ushape_top failed
if (d1.intdim != intdim || d1.realdim != realdim)
printf ("ushape_dimension failed
if (d2.intdim != intdim || d2.realdim != realdim)
printf ("ushape_dimension failed
if (!ushape_is_bottom (ms, bot))
printf ("ushape_is_bottom failed
if (ushape_is_bottom (ms, top))
printf ("ushape_is_bottom failed
if (ushape_is_top (ms, bot))
printf ("ushape_is_top failed
if (!ushape_is_top (ms, top))
printf ("ushape_is_top failed
if (!ushape_is_leq (ms, bot, top))
printf ("ushape_is_leq failed
if (ushape_is_leq (ms, top, bot))
printf ("ushape_is_leq failed
if (!ushape_is_eq (ms, bot, bot))
printf ("ushape_is_eq failed
if (!ushape_is_eq (ms, top, top))
printf ("ushape_is_eq failed #10\n");
if (ushape_is_eq (ms, bot, top))
printf ("ushape_is_eq failed #11\n");
if (<API key> (ms, bot, pr->cst_ptr_null + 1))
printf ("<API key> #12\n");
if (!<API key> (ms, top, pr->cst_ptr_null + 1))
printf ("<API key> #13\n");
for (i = 0; i < N; i++)
{
ushape_t *o = ushape_random (pr, SIZE, intdim, realdim);
ushape_t *c = ushape_copy (ms, o);
ushape_t *l = ushape_closure (ms, false, o);
ap_dimension_t d = ushape_dimension (ms, o);
if (d.intdim != intdim || d.realdim != realdim)
printf ("ushape_dimension failed #14\n");
if (!ushape_is_leq (ms, bot, o))
printf ("ushape_is_leq failed #15\n");
if (!ushape_is_leq (ms, o, top))
printf ("ushape_is_leq failed #16\n");
if (!ushape_is_eq (ms, o, c))
printf ("ushape_is_eq failed #17\n");
ushape_size (ms, o);
ushape_close (pr, o);
// not implemented
//ushape_minimize(ms,o);
//ushape_canonicalize(ms,o);
//ushape_approximate(ms,o,0);
//ushape_is_minimal(ms,o);
//ushape_is_canonical(ms,o);
ushape_free (ms, o);
ushape_free (ms, c);
ushape_free (ms, l);
}
ushape_free (ms, bot);
ushape_free (ms, top);
}
/* closure */
void
test_closure (void)
{
// printf("\nclosure %s\n",num_incomplete?"":"(c,o expected)");
LOOP
{
ushape_t *o = ushape_random (pr, SIZE, intdim, realdim);
ushape_close (pr, o);
RESULT (ushape_check (pr, o));
ushape_free (ms, o);
} ENDLOOP;
}
/* conversions */
void
<API key> (exprmode_t mode)
{
printf ("\nconversion from %slincons\n", exprname[mode]);
LOOP
{
int dim = 6, nb = 10, i;
ap_abstract0_t *p, *p2;
ushape_t *o, *oo;
ap_lincons0_array_t t = <API key> (nb);
ap_lincons0_array_t tt = <API key> (nb);
for (i = 0; i < nb; i++)
{
t.p[i] = ap_lincons0_make ((lrand48 () % 100 >= 90) ? AP_CONS_EQ :
(lrand48 () % 100 >= 90) ? AP_CONS_SUP :
AP_CONS_SUPEQ,
<API key> (pr, mode, intdim,
realdim), NULL);
tt.p[i] = random_from_lincons (t.p[i]);
}
o = ushape_top (ms, intdim, realdim);
oo = <API key> (ms, true, o, &t);
FLAG (ms);
RESULT (ushape_check (pr, o));
if (ushape_is_eq (ms, o, oo))
RESULT ('x');
if (ushape_is_leq (ms, oo, o))
ERROR_RESULT ("best flag");
ushape_free (ms, o);
ushape_free (ms, oo);
<API key> (&t);
<API key> (&tt);
}
ENDLOOP;
}
/* meet */
void
test_meet (void)
{
printf ("\nmeet %s\n", "(* expected)");
LOOP
{
int dim = 6;
ushape_t *o1, *o2, *o;
o1 = ushape_random (pr, SIZE, intdim, realdim);
o2 = ushape_random (pr, SIZE, intdim, realdim);
o = ushape_meet (ms, false, o1, o2);
FLAG (ms);
RESULT (ushape_check (pr, o));
ushape_check (pr, o1);
ushape_check (pr, o2);
if (!ushape_is_leq (ms, o, o1) || !ushape_is_leq (ms, o, o2))
{
ERROR_RESULT ("not lower bound");
print_ushape ("o1", o1);
print_ushape ("o2", o2);
print_ushape ("o", o);
}
ushape_free (ms, o);
ushape_free (ms, o1);
ushape_free (ms, o2);
}
ENDLOOP;
printf ("\nmeet top %s\n", "(* expected)");
LOOP
{
int dim = 8;
ushape_t *o1, *o2, *o, *oo;
o1 = ushape_random (pr, SIZE, intdim, realdim);
o2 = ushape_top (ms, intdim, realdim);
o = ushape_meet (ms, false, o1, o2);
oo = ushape_meet (ms, false, o, o1);
ushape_check (pr, o1);
ushape_check (pr, o2);
ushape_check (pr, o);
if (!ushape_is_eq (ms, o, o1))
{
ERROR_RESULT ("not eq
print_ushape ("o1", o1);
print_ushape ("o", o);
}
else if (!ushape_is_eq (ms, o, oo))
{
ERROR_RESULT ("not eq
print_ushape ("o1", o1);
print_ushape ("o", o);
print_ushape ("oo", oo);
}
else
RESULT ('*');
ushape_free (ms, o);
ushape_free (ms, o1);
ushape_free (ms, o2);
ushape_free (ms, oo);
}
ENDLOOP;
printf ("\nmeet bot %s\n", "(* expected)");
LOOP
{
int dim = 8;
ushape_t *o1, *o2, *o;
o1 = ushape_random (pr, SIZE, intdim, realdim);
o2 = ushape_bottom (ms, intdim, realdim);
o = ushape_meet (ms, false, o1, o2);
ushape_check (pr, o1);
ushape_check (pr, o2);
ushape_check (pr, o);
if (!ushape_is_bottom (ms, o))
{
ERROR_RESULT ("not bottom");
print_ushape ("o1", o1);
print_ushape ("o", o);
}
else
RESULT ('*');
ushape_free (ms, o);
ushape_free (ms, o1);
ushape_free (ms, o2);
}
ENDLOOP;
}
#define NB_MEET 5
void
test_meet_array (void)
{
printf ("\nmeet array %s\n", "(* expected)");
LOOP
{
int i, dim = 6;
ushape_t *o[NB_MEET], *oo;
for (i = 0; i < NB_MEET; i++)
o[i] = ushape_random (pr, SIZE, intdim, realdim);
oo = ushape_meet_array (ms, o, NB_MEET);
FLAG (ms);
RESULT (ushape_check (pr, oo));
for (i = 0; i < NB_MEET; i++)
if (!ushape_is_leq (ms, oo, o[i]))
ERROR_RESULT ("not lower bound");
for (i = 0; i < NB_MEET; i++)
ushape_free (ms, o[i]);
ushape_free (ms, oo);
}
ENDLOOP;
}
void
test_add_pcons_once (exprmode_t mode, ushape_t * o, pcons0_array_t * array)
{
size_t i, o2size;
ushape_t *o1;
ushape_array_t *o2;
printf ("\n*** meet with pcons:\n");
#ifndef NDEBUG
ushape_fdump (stdout, pr->man, o);
<API key> (stdout, array, o->datadim, o->ptrdim);
#endif
/* apply domain function (underapproximation) */
printf ("\n*** (underapproximation):\n");
o1 = ushape_copy_mem (pr, o);
o2 = <API key> (pr, true, o1, array);
FLAG (ms);
ushape_check (pr, o);
if (o2)
{
for (i = 0; i < o2->size; i++)
{
RESULT (ushape_check (pr, o2->p[i]));
if (!ushape_is_leq (ms, o2->p[i], o))
{
ERROR_RESULT ("not included in");
print_ushape ("o", o);
print_ushape ("o2", o2->p[i]);
}
}
}
ushape_array_clear (pr, o2);
free (o2);
/* apply internal function (exact) */
printf ("\n*** (exact):\n");
o2 = <API key> (pr, false, o, array);
if (o2)
{
for (i = 0; i < o2->size; i++)
{
RESULT (ushape_check (pr, o2->p[i]));
if (!ushape_is_leq (ms, o2->p[i], o))
{
ERROR_RESULT ("not included in");
print_ushape ("o", o);
print_ushape ("o2", o2->p[i]);
}
}
ushape_array_clear (pr, o2);
}
}
void
test_add_lincons (exprmode_t mode)
{
size_t i, nb = 4;
ap_lincons0_array_t ar;
pcons0_array_t *arr;
ushape_t *o;
printf ("\nadd %slincons %s\n", exprname[mode], "(* expected)");
/* predefined graphs and constraints */
/* case (1): top /\ x --> null /\ x == y */
o = ushape_top (ms, intdim, realdim);
ar = <API key> (2);
ar.p[0] =
shape_lincons_x_y_l (AP_CONS_SUPEQ, 1, DIM_X, -1, DIM_NULL, 0, 0, intdim,
realdim);
ar.p[1] =
shape_lincons_x_y_l (AP_CONS_EQ, 1, DIM_X, -1, DIM_Y, 0, 0, intdim,
realdim);
arr = <API key> (pr, &ar, intdim, realdim);
test_add_pcons_once (mode, o, arr);
<API key> (arr);
ushape_free (pr->man, o);
/* case (2): x-->null, x==y /\ y != null */
o = ushape_make (pr, 5, intdim, realdim);
ar = <API key> (1);
ar.p[0] =
shape_lincons_x_y (AP_CONS_DISEQ, DIM_Y, DIM_NULL, intdim, realdim);
arr = <API key> (pr, &ar, intdim, realdim);
test_add_pcons_once (mode, o, arr);
ushape_free (pr->man, o);
/* case (3): x-->y-->null /\ y != null */
o = ushape_make (pr, 6, intdim, realdim);
test_add_pcons_once (mode, o, arr);
ushape_free (pr->man, o);
<API key> (arr);
/* random graphs and constraints */
LOOP
{
ar = <API key> (nb);
o = ushape_random (pr, SIZE, intdim, realdim);
if (lrand48 () % 10 >= 8)
ushape_close (pr, o);
for (i = 0; i < nb; i++)
{
ar.p[i] = ap_lincons0_make ((lrand48 () % 100 >= 80) ? AP_CONS_EQ :
(lrand48 () % 100 >= 80) ? AP_CONS_SUP :
AP_CONS_SUPEQ,
<API key> (pr, mode, intdim,
realdim), NULL);
}
arr = <API key> (pr, &ar, intdim, realdim);
test_add_pcons_once (mode, o, arr);
ushape_free (ms, o);
<API key> (arr);
}
ENDLOOP;
}
void
test_add_tcons (exprmode_t mode)
{
size_t i, nb = 4;
ap_tcons0_array_t ar;
pcons0_array_t *arr;
ushape_t *o;
printf ("\nadd %s tcons %s\n", exprname[mode], "(* expected)");
/* predefined graphs and constraints */
/* case (1): x-->null, x==y /\ x->next != null */
o = ushape_make (pr, 5, intdim, realdim);
ar = <API key> (1);
ar.p[0] =
shape_tcons_x_y (AP_CONS_DISEQ, DIM_X, true, DIM_NULL, false, intdim,
realdim);
arr = <API key> (pr, &ar, intdim, realdim);
test_add_pcons_once (mode, o, arr);
ushape_free (pr->man, o);
<API key> (arr);
/* random graphs and constraints */
LOOP
{
ar = <API key> (nb);
o = ushape_random (pr, SIZE, intdim, realdim);
if (lrand48 () % 10 >= 8)
ushape_close (pr, o);
for (i = 0; i < nb; i++)
{
if (mode == expr_data)
ar.p[i] = ap_tcons0_make ((lrand48 () % 100 >= 80) ? AP_CONS_SUP :
AP_CONS_SUPEQ,
shape_texpr_random (pr, mode, intdim,
realdim), NULL);
else
ar.p[i] = ap_tcons0_make ((lrand48 () % 100 >= 80) ? AP_CONS_EQ :
AP_CONS_DISEQ,
shape_texpr_random (pr, expr_reach,
intdim, realdim),
NULL);
}
<API key> (stdout, &ar, NULL);
arr = <API key> (pr, &ar, intdim, realdim);
test_add_pcons_once (mode, o, arr);
ushape_free (ms, o);
<API key> (arr);
}
ENDLOOP;
}
/* assignments / substitutions */
void
test_assign (int subst, exprmode_t mode)
{
printf ("\n%s %slinexpr %s\n", subst ? "subst" : "assign", exprname[mode],
"(* expected)");
LOOP
{
size_t dim = 6;
ap_dim_t d;
ushape_t *o, *o1;
ap_linexpr0_t *l = <API key> (pr, mode, intdim, realdim);
if (mode != expr_lindata || mode != expr_data)
d = RANDOM_PTRDIM (pr, intdim, realdim);
else
d = lrand48 () % intdim;
o = ushape_random (pr, SIZE, intdim, realdim);
if (lrand48 () % 10 >= 5)
ushape_close (pr, o);
o1 =
subst ? <API key> (ms, false, o, &d, &l, 1,
NULL) :
<API key> (ms, false, o, &d, &l, 1, NULL);
FLAG (ms);
RESULT (ushape_check (pr, o1));
if (ushape_is_eq (ms, o, o1))
ERROR_RESULT ("best flag");
ushape_free (ms, o);
ushape_free (ms, o1);
ap_linexpr0_free (l);
}
ENDLOOP;
}
void
test_assign_texpr (int subst, exprmode_t mode)
{
printf ("\n%s texpr\n", subst ? "subst" : "assign");
LOOP
{
size_t dim = 5;
ap_dim_t d;
ushape_t *o, *o1;
ap_texpr0_t *e = shape_texpr_random (pr, mode, intdim, realdim);
if (mode != expr_lindata || mode != expr_data)
d = RANDOM_PTRDIM (pr, intdim, realdim);
else
d = lrand48 () % intdim;
o = ushape_random (pr, SIZE, intdim, realdim);
if (lrand48 () % 10 >= 5)
ushape_close (pr, o);
o1 =
subst ? <API key> (ms, false, o, &d, &e, 1,
NULL) :
<API key> (ms, false, o, &d, &e, 1, NULL);
FLAG (ms);
RESULT (ushape_check (pr, o1));
if (ushape_is_eq (ms, o, o1))
RESULT ('x');
else
RESULT ('.');
ushape_free (ms, o);
ushape_free (ms, o1);
ap_texpr0_free (e);
}
ENDLOOP;
}
/* hash */
void
test_hash (void)
{
printf ("\nhash\n");
LOOP
{
size_t dim = 5;
ushape_t *oa, *ob;
int ra, rb;
oa = ushape_random (pr, SIZE, intdim, realdim);
ra = ushape_hash (ms, oa);
ob = ushape_copy (ms, oa);
rb = ushape_hash (ms, ob);
RESULT ('.');
if (ra != rb)
ERROR_RESULT ("different hash");
ushape_free (ms, oa);
ushape_free (ms, ob);
}
ENDLOOP;
}
/* main */
void
tests (int algo)
{
int i;
for (i = 0; i < AP_FUNID_SIZE; i++)
{
ms->option.funopt[i].algorithm = algo;
}
printf ("\nstarting tests with algo=%i\n", algo);
/* tests */
test_misc ();
/*
test_serialize();
test_closure();
<API key>();
<API key>(expr_ushape);
<API key>(expr_lin);
<API key>(expr_interv);
test_meet();
test_meet_array();
test_join();
test_join_array();
*/
test_add_lincons (expr_reach);
test_add_lincons (expr_reachl);
test_add_lincons (expr_lindata);
test_add_tcons (expr_next);
test_add_tcons (expr_data);
/*
test_sat_lincons(expr_reach);
test_sat_lincons(expr_reachl);
test_sat_lincons(expr_lindata);
test_widening();
test_widening_thrs();
test_narrowing();
*/
test_assign (0, expr_ptr);
test_assign (0, expr_next);
test_assign (0, expr_lindata);
test_assign (0, expr_deref);
test_assign (0, expr_data);
test_assign (0, expr_deref_data);
/*
test_hash();
*/
}
int
main (int argc, const char **argv)
{
long int seed;
int i;
seed = time (NULL);
for (i = 1; i < argc; i++)
{
if (argv[i][0] == '+')
N = atol (argv[i] + 1);
else
seed = atol (argv[i]);
}
printf ("seed = %ld, N= %i\n", seed, N);
assert (N < MAXN);
/* init */
srand48 (seed);
ms = <API key> ();
if (!ms)
return 1;
for (i = 0; i < AP_EXC_SIZE; i++)
{
ms->option.abort_if_exception[i] = true;
}
pr = <API key> (ms, 0, 0);
info ();
tests (0);
/* quit */
if (pr->error_)
printf ("\n%i error(s)!\n", pr->error_);
else
printf ("\nall tests passed\n");
ap_manager_free (ms);
return 0;
} |
<?php
namespace PPHP\tests\tools\classes\special\storage\relationTable;
<API key>(function ($className){
require_once $_SERVER['DOCUMENT_ROOT'] . '/' . str_replace('\\', '/', $className) . '.php';
});
/**
* Generated by <API key> on 2012-06-16 at 07:18:54.
*/
class PointerTest extends \<API key>{
/**
* @var \PPHP\tools\classes\special\storage\relationTable\Pointer
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp(){
$this->object = new \PPHP\tools\classes\special\storage\relationTable\Pointer(5, 5);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown(){
}
/**
* @covers PPHP\tools\classes\special\storage\relationTable\Pointer::setLine
*/
public function testSetLine(){
$this->object->setLine(1);
$this->assertEquals(5, $this->object->getPosition());
$this->object->setLine(3);
$this->assertEquals(15, $this->object->getPosition());
}
/**
* @covers PPHP\tools\classes\special\storage\relationTable\Pointer::getPosition
*/
public function testGetPosition(){
$this->assertEquals(5, $this->object->getPosition());
}
/**
* @covers PPHP\tools\classes\special\storage\relationTable\Pointer::nextPosition
*/
public function testNextPosition(){
$this->object->nextPosition();
$this->assertEquals(10, $this->object->getPosition());
}
/**
* @covers PPHP\tools\classes\special\storage\relationTable\Pointer::prevPosition
*/
public function testPrevPosition(){
$this->object->nextPosition();
$this->object->prevPosition();
$this->assertEquals(5, $this->object->getPosition());
}
} |
package de.keridos.floodlights.reference;
public class Names {
public static final class Blocks {
public static final String ELECTRIC_FLOODLIGHT = "electricFloodlight";
public static final String <API key> = "<API key>";
public static final String CARBON_FLOODLIGHT = "carbonFloodlight";
public static final String PHANTOM_LIGHT = "blockLight";
}
public static final class Items {
public static final String RAW_FILAMENT = "rawFilament";
public static final String GLOWING_FILAMENT = "glowingFilament";
public static final String <API key> = "<API key>";
public static final String CARBON_DISSOLVER = "carbonDissolver";
public static final String CARBON_LANTERN = "carbonLantern";
public static final String MANTLE = "mantle";
}
public static final class Localizations {
public static final String <API key> = "gui.floodlights:<API key>";
public static final String MODE = "gui.floodlights:mode";
public static final String INVERT = "gui.floodlights:invert";
public static final String TRUE = "gui.floodlights:true";
public static final String FALSE = "gui.floodlights:false";
public static final String STRAIGHT = "gui.floodlights:straight";
public static final String NARROW_CONE = "gui.floodlights:narrowCone";
public static final String WIDE_CONE = "gui.floodlights:wideCone";
public static final String GUI_MINUTES_SHORT = "gui.floodlights:minutesShort";
public static final String GUI_SECONDS_SHORT = "gui.floodlights:secondsShort";
public static final String <API key> = "gui.floodlights:<API key>";
}
public static final class NBT {
public static final String ITEMS = "Items";
public static final String INVERT = "inverted";
public static final String TIMEOUT = "timeout";
public static final String TIME_REMAINING = "timeRemaining";
public static final String STORAGE_EU = "storageEU";
public static final String COLOR = "color";
public static final String MODE = "teState";
public static final String STATE = "teMode";
public static final String WAS_ACTIVE = "wasActive";
public static final String CUSTOM_NAME = "CustomName";
public static final String DIRECTION = "teDirection";
public static final String ROTATION_STATE = "teRotationState";
public static final String OWNER = "owner";
}
} |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>audio-monitor-avr: Data Structures</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">audio-monitor-avr
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="classes.html"><span>Data Structure Index</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Data Structures</div> </div>
</div><!--header
<div class="contents">
<div class="textblock">Here are the data structures with brief descriptions:</div><div class="directory">
<table class="directory">
<tr id="row_0_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="<API key>.html" target="_self">_audio_voltage</a></td><td class="desc"></td></tr>
<tr id="row_1_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="<API key>.html" target="_self">_tag_complex_t</a></td><td class="desc"></td></tr>
<tr id="row_2_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="structmenu__entry__.html" target="_self">menu_entry_</a></td><td class="desc"></td></tr>
<tr id="row_3_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="structmenu__page__.html" target="_self">menu_page_</a></td><td class="desc"></td></tr>
<tr id="row_4_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="structt__debounce.html" target="_self">t_debounce</a></td><td class="desc"></td></tr>
<tr id="row_5_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="structt__keypad.html" target="_self">t_keypad</a></td><td class="desc"></td></tr>
<tr id="row_6_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="structt__menu.html" target="_self">t_menu</a></td><td class="desc"></td></tr>
<tr id="row_7_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="<API key>.html" target="_self">t_operational</a></td><td class="desc"></td></tr>
<tr id="row_8_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="structt__output.html" target="_self">t_output</a></td><td class="desc"></td></tr>
<tr id="row_9_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span class="icona"><span class="icon">C</span></span><a class="el" href="structt__persistent.html" target="_self">t_persistent</a></td><td class="desc"></td></tr>
</table>
</div><!-- directory -->
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Sun Feb 14 2016 11:34:34 for audio-monitor-avr by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html> |
package org.fdroid.fdroid.views.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import org.fdroid.fdroid.AppListAdapter;
import org.fdroid.fdroid.R;
import org.fdroid.fdroid.views.AppListView;
public class <API key> extends AppListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
AppListView view = new AppListView(getActivity());
view.setOrientation(LinearLayout.HORIZONTAL);
view.setWeightSum(1f);
ListView lvCategories = new ListView(getActivity());
// Giving it an ID lets the default save/restore state
// functionality do its stuff.
lvCategories.setId(R.id.categoryListView);
lvCategories.setAdapter(getAppListManager().<API key>());
lvCategories.<API key>(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
String category = parent.getItemAtPosition(pos).toString();
getAppListManager().setCurrentCategory(category);
}
});
LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
p1.weight = 0.7f;
view.addView(lvCategories, p1);
ListView list = createAppListView();
view.setAppList(list);
LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
p2.weight = 0.3f;
view.addView(list, p2);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
protected AppListAdapter getAppListAdapter() {
return getAppListManager().getAvailableAdapter();
}
} |
\section{transceiver\_\-mac.c File Reference}
\label{transceiver__mac_8c}\index{transceiver_mac.c@{transceiver\_\-mac.c}}
{\tt \#include $<$inttypes.h$>$}\par
{\tt \#include \char`\"{}transceiver\_\-spi.h\char`\"{}}\par
{\tt \#include \char`\"{}transceiver\_\-mac.h\char`\"{}}\par
Include dependency graph for transceiver\_\-mac.c:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=272pt]{<API key>}
\end{center}
\end{figure}
\subsection*{Functions}
\begin{CompactItemize}
\item
void {\bf MC13192\_\-init} ()
\begin{CompactList}\small\item\em Initialize the MC13192 TODO: write detailed code description! \item\end{CompactList}\item
void {\bf MC13192\_\-update\_\-state} (void)
\begin{CompactList}\small\item\em Update the state variable to reflect the state of MC13192. \item\end{CompactList}\item
void {\bf cca\_\-modus} (void)
\item
void {\bf init\_\-rx\_\-pkt\_\-mode} (void)
\begin{CompactList}\small\item\em switch MC13192 to receive mode TODO: write detailed code description! \item\end{CompactList}\item
int {\bf get\_\-rx\_\-pkt} ({\bf rx\_\-packet\_\-t} $\ast$rx\_\-packet)
\begin{CompactList}\small\item\em read a data paket from MC13192 \item\end{CompactList}\item
int {\bf tx\_\-pkt\_\-mode} ({\bf tx\_\-packet\_\-t} $\ast$tx\_\-packet)
\begin{CompactList}\small\item\em send a data packet TODO: write detailed code description! \item\end{CompactList}\end{CompactItemize}
\subsection*{Variables}
\begin{CompactItemize}
\item
unsigned char {\bf mc13192\_\-mode}
\item
unsigned char {\bf mc13192\_\-state}
\end{CompactItemize} |
Authentication Flow
- Configure email. Define these values in your `.env` or in your environment variable: `SMTP_CONNECTION`, `REDIS_URL`, `REGISTRATION_EMAIL` and `SUPPORT_EMAIL`. Checkout (Mailgun)[http://mailgun.com] for free transactional email for your domain.
- Send `POST` request to `auth/signup` with `email` and `password` in request body(json).
- The user's passwords hash and email gets stored in redis for 48 hours. A link with validity upto 48 hours is sent to the users email.
- When the user verifies her account by clicking the link in the email, A user is created with her credentials.
- To login, a user has to send `email`, and `password`. A token is generated using the users and sent back to the user.
- The user can authenticate herself using the token in the `Authentication` header, the value format being, `Bearer <token>` |
'
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'This class was auto-generated by the <API key>
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.<API key>("System.Resources.Tools.<API key>", "4.0.0.0"), _
Global.System.Diagnostics.<API key>(), _
Global.System.Runtime.CompilerServices.<API key>(), _
Global.Microsoft.VisualBasic.<API key>()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.<API key>(Global.System.ComponentModel.<API key>.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("GNUplot.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.<API key>(Global.System.ComponentModel.<API key>.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace |
package edu.kit.cloudSimStorage.storageModel.resourceUtilization;
import edu.kit.cloudSimStorage.helper.FileSizeHelper;
import org.cloudbus.cloudsim.core.CloudSim;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
/** @author Tobias Sturm, 6/21/13 4:35 PM */
@Root
public class FirstFitAllocation implements <API key> {
//the absolute maxAmountPerTime. available amount of the resource
@Attribute(name = "maxRate")
private double maxAmountPerTime;
private UtilizationSequence utilization;
/**
* Create a resource, that has the given rate [amount/ms^-1].
*
* @param maxRate the max possible rate of this resource
*/
public FirstFitAllocation(@Attribute(name = "maxRate") double maxRate) {
this.maxAmountPerTime = maxRate;
utilization = new UtilizationSequence();
}
/**
* More convenient way to create an instance
*
* @param volumePerSecond for example 100MB/s -> 100
* @param magnitude magnitude of volume
* @return new instance with given limitations (in byte / ms)
*/
public static <API key> create(int volumePerSecond, FileSizeHelper.Magnitude magnitude) {
return new FirstFitAllocation(FileSizeHelper.toBytes(volumePerSecond, magnitude) * 1000);
}
@Override
public UtilizationSequence use(double amount, double maxRate) {
return use(CloudSim.<API key>().getTimeInMillis(), amount, maxRate);
}
@Override
public UtilizationSequence use(double amount) {
return use(CloudSim.<API key>().getTimeInMillis(), amount, maxAmountPerTime);
}
@Override
public UtilizationSequence use(long start, double amount) {
return use(start, amount, maxAmountPerTime);
}
@Override
public UtilizationSequence use(long start, double amount, double maxRate) {
UtilizationSequence result = new UtilizationSequence();
long from = start;
double remainingAmount = amount;
double rate = Math.min(maxRate, maxAmountPerTime);
while (remainingAmount > 0 && utilization.<API key>(from)) {
double limitation = utilization.getValuesAt(from + 1);
double <API key> = Math.min(maxAmountPerTime - limitation, rate);
//sequence won't change before variable {@code to}. Take complete block, or so much time inside the block to work off remainingAmount.
long to = utilization.<API key>(from);
long sampleDuration = Math.min(to - from, (long) (remainingAmount / rate));
if (sampleDuration > 0 && <API key> > 0) {
remainingAmount -= sampleDuration * <API key>;
<API key> use = new <API key>(from, from + sampleDuration, <API key>);
utilization.insertSample(use);
result.insertSample(use);
}
from = to;
}
if (remainingAmount > rate) {
long duration = (long) (remainingAmount / rate);
remainingAmount -= duration * rate;
<API key> use = new <API key>(from, from + duration, rate);
utilization.insertSample(use);
result.insertSample(use);
}
assert remainingAmount < maxRate;
return result;
}
@Override
public long <API key>(long time) {
long probe = time;
while (maxAmountPerTime - utilization.getValuesAt(probe) <= (maxAmountPerTime / 1000)) {//Utilization has to drop below 99.9%
probe = utilization.<API key>(probe);
}
return probe;
}
@Override
public void removeSamplesBefore(long time) {
utilization.optimize(time);
}
@Override
public double getValueAt(long time) {
return utilization.getValuesAt(time);
}
@Override
public double getMaxPossible() {
return maxAmountPerTime;
}
} |
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#include <linux/of_dma.h>
#define TI_XBAR_DRA7 0
#define TI_XBAR_AM335X 1
static const u32 ti_xbar_type[] =
{
[TI_XBAR_DRA7] = TI_XBAR_DRA7,
[TI_XBAR_AM335X] = TI_XBAR_AM335X,
};
static const struct of_device_id ti_dma_xbar_match[] =
{
{
.compatible = "ti,dra7-dma-crossbar",
.data = &ti_xbar_type[TI_XBAR_DRA7],
},
{
.compatible = "ti,<API key>",
.data = &ti_xbar_type[TI_XBAR_AM335X],
},
{},
};
/* Crossbar on AM335x/AM437x family */
#define <API key> 64
struct ti_am335x_xbar_data
{
void __iomem *iomem;
struct dma_router dmarouter;
u32 xbar_events; /* maximum number of events to select in xbar */
u32 dma_requests; /* number of DMA requests on eDMA */
};
struct ti_am335x_xbar_map
{
u16 dma_line;
u16 mux_val;
};
static inline void <API key>(void __iomem *iomem, int event, u16 val)
{
writeb_relaxed(val & 0x1f, iomem + event);
}
static void ti_am335x_xbar_free(struct device *dev, void *route_data)
{
struct ti_am335x_xbar_data *xbar = dev_get_drvdata(dev);
struct ti_am335x_xbar_map *map = route_data;
dev_dbg(dev, "Unmapping XBAR event %u on channel %u\n",
map->mux_val, map->dma_line);
<API key>(xbar->iomem, map->dma_line, 0);
kfree(map);
}
static void *<API key>(struct of_phandle_args *dma_spec,
struct of_dma *ofdma)
{
struct platform_device *pdev = <API key>(ofdma->of_node);
struct ti_am335x_xbar_data *xbar = <API key>(pdev);
struct ti_am335x_xbar_map *map;
if (dma_spec->args_count != 3)
{
return ERR_PTR(-EINVAL);
}
if (dma_spec->args[2] >= xbar->xbar_events)
{
dev_err(&pdev->dev, "Invalid XBAR event number: %d\n",
dma_spec->args[2]);
return ERR_PTR(-EINVAL);
}
if (dma_spec->args[0] >= xbar->dma_requests)
{
dev_err(&pdev->dev, "Invalid DMA request line number: %d\n",
dma_spec->args[0]);
return ERR_PTR(-EINVAL);
}
/* The of_node_put() will be done in the core for the node */
dma_spec->np = of_parse_phandle(ofdma->of_node, "dma-masters", 0);
if (!dma_spec->np)
{
dev_err(&pdev->dev, "Can't get DMA master\n");
return ERR_PTR(-EINVAL);
}
map = kzalloc(sizeof(*map), GFP_KERNEL);
if (!map)
{
of_node_put(dma_spec->np);
return ERR_PTR(-ENOMEM);
}
map->dma_line = (u16)dma_spec->args[0];
map->mux_val = (u16)dma_spec->args[2];
dma_spec->args[2] = 0;
dma_spec->args_count = 2;
dev_dbg(&pdev->dev, "Mapping XBAR event%u to DMA%u\n",
map->mux_val, map->dma_line);
<API key>(xbar->iomem, map->dma_line, map->mux_val);
return map;
}
static const struct of_device_id <API key>[] =
{
{ .compatible = "ti,edma3-tpcc", },
{},
};
static int <API key>(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
const struct of_device_id *match;
struct device_node *dma_node;
struct ti_am335x_xbar_data *xbar;
struct resource *res;
void __iomem *iomem;
int i, ret;
if (!node)
{
return -ENODEV;
}
xbar = devm_kzalloc(&pdev->dev, sizeof(*xbar), GFP_KERNEL);
if (!xbar)
{
return -ENOMEM;
}
dma_node = of_parse_phandle(node, "dma-masters", 0);
if (!dma_node)
{
dev_err(&pdev->dev, "Can't get DMA master node\n");
return -ENODEV;
}
match = of_match_node(<API key>, dma_node);
if (!match)
{
dev_err(&pdev->dev, "DMA master is not supported\n");
return -EINVAL;
}
if (<API key>(dma_node, "dma-requests",
&xbar->dma_requests))
{
dev_info(&pdev->dev,
"Missing XBAR output information, using %u.\n",
<API key>);
xbar->dma_requests = <API key>;
}
of_node_put(dma_node);
if (<API key>(node, "dma-requests", &xbar->xbar_events))
{
dev_info(&pdev->dev,
"Missing XBAR input information, using %u.\n",
<API key>);
xbar->xbar_events = <API key>;
}
res = <API key>(pdev, IORESOURCE_MEM, 0);
iomem = <API key>(&pdev->dev, res);
if (IS_ERR(iomem))
{
return PTR_ERR(iomem);
}
xbar->iomem = iomem;
xbar->dmarouter.dev = &pdev->dev;
xbar->dmarouter.route_free = ti_am335x_xbar_free;
<API key>(pdev, xbar);
/* Reset the crossbar */
for (i = 0; i < xbar->dma_requests; i++)
{
<API key>(xbar->iomem, i, 0);
}
ret = <API key>(node, <API key>,
&xbar->dmarouter);
return ret;
}
/* Crossbar on DRA7xx family */
#define <API key> 127
#define TI_DRA7_XBAR_INPUTS 256
struct ti_dra7_xbar_data
{
void __iomem *iomem;
struct dma_router dmarouter;
struct mutex mutex;
unsigned long *dma_inuse;
u16 safe_val; /* Value to rest the crossbar lines */
u32 xbar_requests; /* number of DMA requests connected to XBAR */
u32 dma_requests; /* number of DMA requests forwarded to DMA */
u32 dma_offset;
};
struct ti_dra7_xbar_map
{
u16 xbar_in;
int xbar_out;
};
static inline void ti_dra7_xbar_write(void __iomem *iomem, int xbar, u16 val)
{
writew_relaxed(val, iomem + (xbar * 2));
}
static void ti_dra7_xbar_free(struct device *dev, void *route_data)
{
struct ti_dra7_xbar_data *xbar = dev_get_drvdata(dev);
struct ti_dra7_xbar_map *map = route_data;
dev_dbg(dev, "Unmapping XBAR%u (was routed to %d)\n",
map->xbar_in, map->xbar_out);
ti_dra7_xbar_write(xbar->iomem, map->xbar_out, xbar->safe_val);
mutex_lock(&xbar->mutex);
clear_bit(map->xbar_out, xbar->dma_inuse);
mutex_unlock(&xbar->mutex);
kfree(map);
}
static void *<API key>(struct of_phandle_args *dma_spec,
struct of_dma *ofdma)
{
struct platform_device *pdev = <API key>(ofdma->of_node);
struct ti_dra7_xbar_data *xbar = <API key>(pdev);
struct ti_dra7_xbar_map *map;
if (dma_spec->args[0] >= xbar->xbar_requests)
{
dev_err(&pdev->dev, "Invalid XBAR request number: %d\n",
dma_spec->args[0]);
return ERR_PTR(-EINVAL);
}
/* The of_node_put() will be done in the core for the node */
dma_spec->np = of_parse_phandle(ofdma->of_node, "dma-masters", 0);
if (!dma_spec->np)
{
dev_err(&pdev->dev, "Can't get DMA master\n");
return ERR_PTR(-EINVAL);
}
map = kzalloc(sizeof(*map), GFP_KERNEL);
if (!map)
{
of_node_put(dma_spec->np);
return ERR_PTR(-ENOMEM);
}
mutex_lock(&xbar->mutex);
map->xbar_out = find_first_zero_bit(xbar->dma_inuse,
xbar->dma_requests);
mutex_unlock(&xbar->mutex);
if (map->xbar_out == xbar->dma_requests)
{
dev_err(&pdev->dev, "Run out of free DMA requests\n");
kfree(map);
return ERR_PTR(-ENOMEM);
}
set_bit(map->xbar_out, xbar->dma_inuse);
map->xbar_in = (u16)dma_spec->args[0];
dma_spec->args[0] = map->xbar_out + xbar->dma_offset;
dev_dbg(&pdev->dev, "Mapping XBAR%u to DMA%d\n",
map->xbar_in, map->xbar_out);
ti_dra7_xbar_write(xbar->iomem, map->xbar_out, map->xbar_in);
return map;
}
#define TI_XBAR_EDMA_OFFSET 0
#define TI_XBAR_SDMA_OFFSET 1
static const u32 ti_dma_offset[] =
{
[TI_XBAR_EDMA_OFFSET] = 0,
[TI_XBAR_SDMA_OFFSET] = 1,
};
static const struct of_device_id <API key>[] =
{
{
.compatible = "ti,omap4430-sdma",
.data = &ti_dma_offset[TI_XBAR_SDMA_OFFSET],
},
{
.compatible = "ti,edma3",
.data = &ti_dma_offset[TI_XBAR_EDMA_OFFSET],
},
{
.compatible = "ti,edma3-tpcc",
.data = &ti_dma_offset[TI_XBAR_EDMA_OFFSET],
},
{},
};
static inline void <API key>(int offset, int len, unsigned long *p)
{
for (; len > 0; len
{
clear_bit(offset + (len - 1), p);
}
}
static int ti_dra7_xbar_probe(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
const struct of_device_id *match;
struct device_node *dma_node;
struct ti_dra7_xbar_data *xbar;
struct property *prop;
struct resource *res;
u32 safe_val;
int sz;
void __iomem *iomem;
int i, ret;
if (!node)
{
return -ENODEV;
}
xbar = devm_kzalloc(&pdev->dev, sizeof(*xbar), GFP_KERNEL);
if (!xbar)
{
return -ENOMEM;
}
dma_node = of_parse_phandle(node, "dma-masters", 0);
if (!dma_node)
{
dev_err(&pdev->dev, "Can't get DMA master node\n");
return -ENODEV;
}
match = of_match_node(<API key>, dma_node);
if (!match)
{
dev_err(&pdev->dev, "DMA master is not supported\n");
return -EINVAL;
}
if (<API key>(dma_node, "dma-requests",
&xbar->dma_requests))
{
dev_info(&pdev->dev,
"Missing XBAR output information, using %u.\n",
<API key>);
xbar->dma_requests = <API key>;
}
of_node_put(dma_node);
xbar->dma_inuse = devm_kcalloc(&pdev->dev,
BITS_TO_LONGS(xbar->dma_requests),
sizeof(unsigned long), GFP_KERNEL);
if (!xbar->dma_inuse)
{
return -ENOMEM;
}
if (<API key>(node, "dma-requests", &xbar->xbar_requests))
{
dev_info(&pdev->dev,
"Missing XBAR input information, using %u.\n",
TI_DRA7_XBAR_INPUTS);
xbar->xbar_requests = TI_DRA7_XBAR_INPUTS;
}
if (!<API key>(node, "ti,dma-safe-map", &safe_val))
{
xbar->safe_val = (u16)safe_val;
}
prop = of_find_property(node, "ti,<API key>", &sz);
if (prop)
{
const char pname[] = "ti,<API key>";
u32 (*rsv_events)[2];
size_t nelm = sz / sizeof(*rsv_events);
int i;
if (!nelm)
{
return -EINVAL;
}
rsv_events = kcalloc(nelm, sizeof(*rsv_events), GFP_KERNEL);
if (!rsv_events)
{
return -ENOMEM;
}
ret = <API key>(node, pname, (u32 *)rsv_events,
nelm * 2);
if (ret)
{
return ret;
}
for (i = 0; i < nelm; i++)
{
<API key>(rsv_events[i][0], rsv_events[i][1],
xbar->dma_inuse);
}
kfree(rsv_events);
}
res = <API key>(pdev, IORESOURCE_MEM, 0);
iomem = <API key>(&pdev->dev, res);
if (IS_ERR(iomem))
{
return PTR_ERR(iomem);
}
xbar->iomem = iomem;
xbar->dmarouter.dev = &pdev->dev;
xbar->dmarouter.route_free = ti_dra7_xbar_free;
xbar->dma_offset = *(u32 *)match->data;
mutex_init(&xbar->mutex);
<API key>(pdev, xbar);
/* Reset the crossbar */
for (i = 0; i < xbar->dma_requests; i++)
{
if (!test_bit(i, xbar->dma_inuse))
{
ti_dra7_xbar_write(xbar->iomem, i, xbar->safe_val);
}
}
ret = <API key>(node, <API key>,
&xbar->dmarouter);
if (ret)
{
/* Restore the defaults for the crossbar */
for (i = 0; i < xbar->dma_requests; i++)
{
if (!test_bit(i, xbar->dma_inuse))
{
ti_dra7_xbar_write(xbar->iomem, i, i);
}
}
}
return ret;
}
static int ti_dma_xbar_probe(struct platform_device *pdev)
{
const struct of_device_id *match;
int ret;
match = of_match_node(ti_dma_xbar_match, pdev->dev.of_node);
if (unlikely(!match))
{
return -EINVAL;
}
switch (*(u32 *)match->data)
{
case TI_XBAR_DRA7:
ret = ti_dra7_xbar_probe(pdev);
break;
case TI_XBAR_AM335X:
ret = <API key>(pdev);
break;
default:
dev_err(&pdev->dev, "Unsupported crossbar\n");
ret = -ENODEV;
break;
}
return ret;
}
static struct platform_driver ti_dma_xbar_driver =
{
.driver = {
.name = "ti-dma-crossbar",
.of_match_table = of_match_ptr(ti_dma_xbar_match),
},
.probe = ti_dma_xbar_probe,
};
static int omap_dmaxbar_init(void)
{
return <API key>(&ti_dma_xbar_driver);
}
arch_initcall(omap_dmaxbar_init); |
#include "nouveau_drv.h"
#include "nouveau_dma.h"
#include "nouveau_fence.h"
#include <nvif/if0004.h>
struct nv04_fence_chan
{
struct nouveau_fence_chan base;
};
struct nv04_fence_priv
{
struct nouveau_fence_priv base;
};
static int
nv04_fence_emit(struct nouveau_fence *fence)
{
struct nouveau_channel *chan = fence->channel;
int ret = RING_SPACE(chan, 2);
if (ret == 0)
{
BEGIN_NV04(chan, NvSubSw, 0x0150, 1);
OUT_RING (chan, fence->base.seqno);
FIRE_RING (chan);
}
return ret;
}
static int
nv04_fence_sync(struct nouveau_fence *fence,
struct nouveau_channel *prev, struct nouveau_channel *chan)
{
return -ENODEV;
}
static u32
nv04_fence_read(struct nouveau_channel *chan)
{
struct <API key> args = {};
WARN_ON(nvif_object_mthd(&chan->nvsw, NV04_NVSW_GET_REF,
&args, sizeof(args)));
return args.ref;
}
static void
<API key>(struct nouveau_channel *chan)
{
struct nv04_fence_chan *fctx = chan->fence;
<API key>(&fctx->base);
chan->fence = NULL;
<API key>(&fctx->base);
}
static int
<API key>(struct nouveau_channel *chan)
{
struct nv04_fence_chan *fctx = kzalloc(sizeof(*fctx), GFP_KERNEL);
if (fctx)
{
<API key>(chan, &fctx->base);
fctx->base.emit = nv04_fence_emit;
fctx->base.sync = nv04_fence_sync;
fctx->base.read = nv04_fence_read;
chan->fence = fctx;
return 0;
}
return -ENOMEM;
}
static void
nv04_fence_destroy(struct nouveau_drm *drm)
{
struct nv04_fence_priv *priv = drm->fence;
drm->fence = NULL;
kfree(priv);
}
int
nv04_fence_create(struct nouveau_drm *drm)
{
struct nv04_fence_priv *priv;
priv = drm->fence = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
{
return -ENOMEM;
}
priv->base.dtor = nv04_fence_destroy;
priv->base.context_new = <API key>;
priv->base.context_del = <API key>;
priv->base.contexts = 15;
priv->base.context_base = fence_context_alloc(priv->base.contexts);
return 0;
} |
#include "<API key>.h"
#include "<API key>.h"
static <API key> <API key> CC_NOTUSED = {
{ 0, 0 },
-1 /* (SIZE(1..65535)) */};
<API key> <API key> CC_NOTUSED = {
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
{ APC_CONSTRAINED, 16, 16, 1, 65535 } /* (SIZE(1..65535)) */,
0, 0 /* No PER value map */
};
asn_TYPE_member_t <API key>[] = {
{ ATF_POINTER, 0, 0,
(<API key> | (16 << 2)),
0,
&<API key>,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
""
},
};
static const ber_tlv_tag_t <API key>[] = {
(<API key> | (16 << 2))
};
<API key> <API key> = {
sizeof(struct <API key>),
offsetof(struct <API key>, _asn_ctx),
0, /* XER encoding is <API key> */
};
<API key> <API key> = {
"<API key>",
"<API key>",
&asn_OP_SEQUENCE_OF,
<API key>,
sizeof(<API key>)
/sizeof(<API key>[0]),
<API key>, /* Same as above */
sizeof(<API key>)
/sizeof(<API key>[0]),
{ &<API key>, &<API key>, <API key> },
<API key>,
1, /* Single element */
&<API key> /* Additional specs */
}; |
echo off
echo Process the ASN files in the directory ../conf/sigtran/%1 : please confirm ?
pause
del /F /Q .\binaryNotes\java\com\devoteam\srit\xmlloader\sigtran\ap\%1
mkdir .\binaryNotes\java\com\devoteam\srit\xmlloader\sigtran\ap\%1 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(__file__)
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret_here'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.contenttypes',
'grappelli.dashboard',
'grappelli',
'django.contrib.admin',
'mutual_funds.registration',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# debug
# 'debug_toolbar',
# 'debug_panel',
'django.contrib.sites',
# third party apps
'django_countries',
'djcelery_email',
'rest_framework',
'memoize',
'ckeditor',
'imagekit',
'bootstrap3',
'captcha',
'django_select2',
'widget_tweaks',
# local apps
'mutual_funds.finance',
'mutual_funds.landing',
'mutual_funds.accounts',
'mutual_funds.company',
]
SITE_ID = 1
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.<API key>,
'django.contrib.auth.middleware.Session<API key>,
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.<API key>',
# 'debug_toolbar.middleware.<API key>', # classic debug
# 'debug_panel.middleware.<API key>', # api based debug + classic + chromeext
'async_messages.middleware.AsyncMiddleware',
]
ROOT_URLCONF = 'mutual_funds.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mutual_funds.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_name',
'USER': 'user_name',
'PASSWORD': 'somepass',
'HOST': '127.0.0.1',
}
}
# Password validation
<API key> = [
{
'NAME': 'django.contrib.auth.password_validation.<API key>',
},
{
'NAME': 'django.contrib.auth.password_validation.<API key>',
},
{
'NAME': 'django.contrib.auth.password_validation.<API key>',
},
{
'NAME': 'django.contrib.auth.password_validation.<API key>',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = (
('en', 'English'),
('ru', 'Русский'),
)
# Translations
LOCALE_PATHS = [
os.path.join(BASE_DIR, "locale"),
]
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = '/var/webapps/mutual_funds/www/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Cache
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
# select2 Set the cache backend to select2
<API key> = 'default'
# Media
MEDIA_URL = '/media/'
MEDIA_ROOT = '/var/webapps/mutual_funds/www/media/'
# Grapelli Admin Theme
<API key> = 'FundExpert Project'
<API key> = 'mutual_funds.dashboard.<API key>'
# CKeditor
<API key> = "uploads/"
<API key> = 'pillow'
CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
CKEDITOR_CONFIGS = {
'default': {
'toolbar': None
}
}
# Registration Redux
<API key> = 1
<API key> = True
<API key> = True
LOGIN_REDIRECT_URL = "landing:main_page"
# Recaptcha
<API key> = 'somekey'
<API key> = 'other-key'
RECAPTCHA_USE_SSL = True
NOCAPTCHA = True
# Email
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'lol.com@gmail.com'
EMAIL_HOST_PASSWORD = 'lolpass'
EMAIL_PORT = 587
# Django countries
COUNTRIES_FIRST = ['RU', 'KZ', 'BY', 'UA']
# Django money
CURRENCIES = ('USD', 'EUR')
# CELERY SETTINGS
BROKER_URL = 'redis://localhost:6379/0'
<API key> = ['json']
<API key> = 'json'
<API key> = 'json'
<API key> = 'redis://localhost:6379/0'
# Trustnet access
TRUSTNET_USERNAME = "othermail@gmail.com"
TRUSTNET_PASSWORD = "otherpass"
# Rest Framework
REST_FRAMEWORK = {
'<API key>': (
'rest_framework.renderers.JSONRenderer',
)
}
# # Debug-Toolbar conf
# INTERNAL_IPS = ('172.16.0.59', '127.0.0.1', '0.0.0.0', '10.0.2.15', '10.0.2.2')
# # Be careful it will show toolbar forany IP
# def show_toolbar(request):
# return True
# <API key> = {
# '<API key>': 'mutual_funds.settings.show_toolbar',
# Celery Email
EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' |
/**
* Valere Versnip Design
*
* @project MultiSensor_bsp
* @file temp_ds18b20.c
* @author TimB
* @date 21-mei-2016
* @brief Brief.
*
* Description
*/
#include "temp_ds18b20.h"
/**
* Do one step of the crc calculation.
*
* This function does one byte crc calculation using Polynomial: x^8 + x^5 + x^4 + 1 (0x8C).
* @param crc current crc
* @param data new databyte
* @return crc
*/
static uint8_t temp_ds18b20_crc(uint8_t crc, uint8_t data)
{
uint8_t i;
crc = crc ^ data;
for (i = 0; i < 8; i++)
{
if (crc & 0x01)
crc = (crc >> 1) ^ 0x8C;
else
crc >>= 1;
}
return crc;
}
/**
* Check the current raw data, in the databuffer for crc.
*
* @param p_temp temp_ds18b20 device
* @param rom_ram true: romcheck, false: scratchpad ram check
* @return true: crc OK, false NOT OK
*/
static bool <API key>(temp_ds18b20_t *p_temp, bool rom_ram)
{
bool checkcrc = false;
uint8_t i, end;
uint8_t crc;
if(rom_ram)
{
end = 8; /* if rom check, there should be 8 valid databytes in the buffer */
}
else
{
end = 9; /* if ram check, there should be 9 valid databytes in the buffer */
}
/* first reset crc */
crc = 0;
for(i = 0; i < end; i++)
{
crc = temp_ds18b20_crc(crc, p_temp->data[i]);
}
/* crc should be zero here */
if(!crc)
{
checkcrc = true;
}
return checkcrc;
}
/**
* statemachine for temperature conversion.
*
* @note this should be called periodically by higher level routines
* @param p_temp
* @return status_ok if succeeded (otherwise check status.h for details).
*/
static status_t <API key>(temp_ds18b20_t *p_temp)
{
status_t status = status_ok;
bool bit;
uint32_t currenttime;
static uint8_t i;
uint8_t crc;
int16_t rawtemp;
switch(p_temp->state)
{
/* idle state */
case <API key>:
/* if we need to start a conversion */
if(p_temp->start)
{
/* set the running flag */
p_temp->running = true;
/* reset done and start flag */
p_temp->start = false;
p_temp->ready = false;
/* go to the send reset state */
p_temp->state = <API key>;
/* also reset i and crc */
i = 0;
crc = 0;
}
break;
/* send reset state */
case <API key>:
/* send the reset command */
status = ONEWIRE_reset(p_temp->p_onewire);
/* go to the send conver t state*/
p_temp->state = <API key>;
break;
/* send skiprom command state */
case <API key>:
/* send the skip rom command */
status = ONEWIRE_writebyte(p_temp->p_onewire, <API key>); /* always ok */
/* go to the send conver t state*/
p_temp->state = <API key>;
break;
/* send convert t command state */
case <API key>:
/* send the convert t command */
status = ONEWIRE_writebyte(p_temp->p_onewire, <API key>); /* always ok */
/* take a timestamp */
SYSTICK_GetTicks(&p_temp->timestamp);
/* go to the send wait for conversion state*/
p_temp->state = <API key>;
break;
/* wait for the conversion to finish */
case <API key>:
/* wait for <API key> time */
/* get current time */
SYSTICK_GetTicks(¤ttime);
if(currenttime - p_temp->timestamp > <API key>)
{
/* if conversion is ready, go to the wait for ok to readout state */
p_temp->state = <API key>;
}
break;
/* wait for OK to readout */
case <API key>:
/* if a higherlevel routine triggers ok to readout the scratchpad */
if(p_temp->oktoreadout)
{
/* immediately reset the ok to readout flag */
p_temp->oktoreadout = false;
/* and go to the sendreset2 state, to start reading out the scratchpad */
p_temp->state = <API key>;
}
break;
/* send second reset state */
case <API key>:
/* send the reset command */
status = ONEWIRE_reset(p_temp->p_onewire);
/* go to the read send read scratchpad command state*/
p_temp->state = <API key>;
break;
/* send second skiprom command state */
case <API key>:
/* send the skip rom command */
status = ONEWIRE_writebyte(p_temp->p_onewire, <API key>); /* always ok */
/* go to the send conver t state*/
p_temp->state = <API key>;
break;
/* send the read scratchpad command */
case <API key>:
/* send the reset command */
status = ONEWIRE_writebyte(p_temp->p_onewire, <API key>); /* always ok */
/* go to the read scratchpad state*/
p_temp->state = <API key>;
break;
/* read the entire scratchpad */
case <API key>:
/* there are 9 bytes to read */
for(; i<9; ) /* i has been reset in the idle state, when we receive start command */
{
status = ONEWIRE_readbyte(p_temp->p_onewire, &p_temp->data[i]); /* always ok */
i++;
break; /* break, so we go out of the loop */
}
/* if we have read 9 bytes, go to the crc */
if(i >= 9)
{
p_temp->state = <API key>;
}
break;
/* crc calcualtion */
case <API key>:
/* check the crc */
crc = 0;
for(i = 0; i<9; i++) /* i has been reset in the idle state, when we receive start command */
{
crc = temp_ds18b20_crc(crc, p_temp->data[i]);
}
/* crc should be zero */
if(crc)
{
status = temp_ds18b20_ramcrc;
}
else
{
/* if crc ok, go to store state */
p_temp->state = <API key>;
}
break;
/* store the result */
case <API key>:
/* reset frac and dec parts */
p_temp->temperature_int = 0;
p_temp->temperature_frac = 0;
/* get raw temp */
rawtemp = 0;
rawtemp |= p_temp->data[1];
rawtemp <<= 8;
rawtemp |= p_temp->data[0];
/* if the result is negative */
if(rawtemp & 0x8000) /* if the MSB of the MSBYTE is 1, then the result is negative */
{
rawtemp = ~rawtemp + 1;
p_temp->temperature_int = ~(((rawtemp >> 4) & 0x7F) - 1);
p_temp->temperature_frac = ((rawtemp & 0x000F) * 625);
}
/* if the result is positive */
else
{
p_temp->temperature_int = ((rawtemp >> 4) & 0x7F);
p_temp->temperature_frac = ((rawtemp & 0x000F) * 625);
}
/* set the done flag, reset the running and start flag */
p_temp->start = false;
p_temp->running = false;
p_temp->ready = true;
/* go back to the idle state */
p_temp->state = <API key>;
break;
default:
p_temp->state = temp_ds18b20_state;
break;
}
/* if the status is not ok, reset everything and go to idle state */
if(status != status_ok)
{
p_temp->running = false;
p_temp->start = false;
p_temp->ready = false;
p_temp->state = <API key>;
/* and fill in 0xFFFF in temp register */
p_temp->temperature_int = 0xFFFF;
p_temp->temperature_frac = 0xFFFF;
}
/* ALWAYS CLEAR THE OK TO READOUT BIT, if we were not ready this time, too bad, wait for the next explicit oktoreadout */
p_temp->oktoreadout = false;
return status;
}
/**
* Initialize the temp_ds18b20 device.
*
* @note we will get the devices unique 48bit serial code over onewire, and store it in the struct as well.
* @param p_temp
* @param p_config
* @return status_ok if succeeded (otherwise check status.h for details).
*/
status_t TEMP_DS18B20_Init(temp_ds18b20_t *p_temp, <API key> *p_config)
{
status_t status = status_ok;
/* populate the struct */
p_temp->id = p_config->id;
p_temp->p_onewire = p_config->p_onewire;
p_temp->temperature_int = 0;
p_temp->temperature_frac = 0;
p_temp->state = <API key>;
p_temp->oktoreadout = false;
/* get the serialnumber over onewire, and store in struct */
status = <API key>(p_temp);
return status;
}
/**
* Get the serialnumber over onewire.
*
* @param p_temp temp_ds18b20 device
* @return status_ok if succeeded (otherwise check status.h for details).
*/
status_t <API key>(temp_ds18b20_t *p_temp)
{
status_t status = status_ok;
uint8_t i;
bool crccheck;
/* First send onewire reset pulse */
status = ONEWIRE_reset(p_temp->p_onewire);
/* if succeeded (if we detect presence) */
if(status == status_ok)
{
/* send the READ_ROM command */
status = ONEWIRE_writebyte(p_temp->p_onewire, <API key>); /* always ok */
/* then read back 8 values */
for(i = 0; i < 8; i++)
{
status = ONEWIRE_readbyte(p_temp->p_onewire, &p_temp->data[i]); /* always ok */
}
/* then do a crc check */
crccheck = <API key>(p_temp, true);
/* crccheck should be true */
if(!crccheck)
{
status = temp_ds18b20_romcrc;
}
}
if(status == status_ok)
{
/* if crc is ok, store the serialnumber in the struct */
p_temp->serialnumber = 0;
for(i = 6; i >= 1; i
{
p_temp->serialnumber = (p_temp->serialnumber << 8) | p_temp->data[i];
}
}
/* and compensate the systick msTicks for lost interrupts. (above routine takes +/- 7ms) */
SYSTICK_IncTicks(7);
return status;
}
/**
* Start a conversion cycle.
*
* @param p_temp temp_ds18b20 device
* @return status_ok if succeeded (otherwise check status.h for details).
*/
status_t TEMP_DS18B20_Start(temp_ds18b20_t *p_temp)
{
status_t status = status_ok;
/* check if it is not already running */
if(p_temp->running)
{
status = <API key>;
}
else
{
p_temp->start = true;
}
return status;
}
/**
* Get the last converted result.
*
* @note this function will immediately reset the ready flag
* @param p_temp temp_ds18b20 device
* @param p_temperature_int pointer to integer result (can be NULL if not needed)
* @param p_temperature_frac pointer to fractional result (can be NULL if not needed)
* @return status_ok if succeeded (otherwise check status.h for details).
*/
status_t <API key>(temp_ds18b20_t *p_temp, int16_t *p_temperature_int, uint16_t *p_temperature_fraq)
{
status_t status = status_ok;
/* check if result is ready */
if(p_temp->ready)
{
/* immediately reset the ready flag */
p_temp->ready = false;
/* and store in pointer if needed */
<API key>(p_temperature_int, p_temp->temperature_int);
<API key>(p_temperature_fraq, p_temp->temperature_frac);
}
/* not ready */
else
{
status = <API key>;
}
return status;
}
/**
* Run0 function for the temp_ds18b20 device.
*
* @note this function should be called periodically by higherlevel routines
* @param p_temp temp_ds18b20 device
* @return status_ok if succeeded (otherwise check status.h for details).
*/
status_t TEMP_DS18B20_Run0(temp_ds18b20_t *p_temp)
{
status_t status = status_ok;
status = <API key>(p_temp);
return status;
}
/**
* Get the ready flag.
*
* @param p_temp temp ds18b20 device
* @param p_ready pointer to result
* @return status_ok
*/
status_t <API key>(temp_ds18b20_t *p_temp, bool *p_ready)
{
status_t status = status_ok;
*p_ready = p_temp->ready;
return status;
}
/**
* Get the running flag.
*
* @param p_temp temp ds18b20 device
* @param p_running pointer to result
* @return status_ok
*/
status_t <API key>(temp_ds18b20_t *p_temp, bool *p_running)
{
status_t status = status_ok;
*p_running = p_temp->running;
return status;
}
/**
* Signal the statemachine, that it is OK to start reading the scratchpad, so we can control when to do this in time.
* @param p_temp temp ds18b20 device
* @return status_ok
*/
status_t <API key>(temp_ds18b20_t *p_temp)
{
status_t status = status_ok;
p_temp->oktoreadout = true;
return status;
}
/* End of file temp_ds18b20.c */ |
$(".submit-btn").click(function(){
if ( !HTMLFormElement.prototype.reportValidity ) {
HTMLFormElement.prototype.reportValidity = function() {
var subBtn = this.querySelector("span[id=subBtn]");
subBtn.click();
return;
}
};
var title = document.querySelector("input[name=title]");
var description = document.querySelector("textarea[name=description]");
var contactName = document.querySelector("input[name=contactName]");
var msg = '';
if(title.value.length > 20) {
msg = '20';
}
title.setCustomValidity(msg);
if(description.value.length < 15) {
msg = '15';
}
description.setCustomValidity(msg);
if(contactName.value.length > 10){
msg = '10';
}
contactName.setCustomValidity(msg);
$.tlj.postForm('#ShPostForm', location.pathname, function(data){
console.log(data);
if(data.result){
location.href = '/user/sh/mypost';
}else{
alert(errorCode[data.message]);
}
});
});
//$(".submit-btn").click(function(){
// var data = $("#ShPostForm").serialize();
// $(".dialog").jqm({
// overlayClass: 'jqmOverlay'
// $.ajax({
// type:"POST",
// data:data,
// url: location.pathname,
// success:function(data){
// $(".tlj_modal_content").html(data.message);
// $('.dialog').jqmShow();
// if(data.result){
// setTimeout(function(){
// location.href = "/user/sh/mypost";
// },500);
/*
* del img uploaded
*
*/
$('.img-list-wrapper').delegate('.btn-img-del','click', function(){
if( $('.img-list-item').length == 4) {
$('.img-list-btn').toggle();
}
var $img = $(this).parent('li');
$img.remove()
var picIds = $('input[name=picIds]').val().split(';');
for( var i = 0;i < picIds.length; i++){
if( $img.data('pid') == picIds[i] ) {
picIds.splice(i,1);
break;
}
}
$('input[name=picIds]').val(picIds.join(';'));
});
/* upload img list init*/
var initImgList = function() {
var ids = $('input[name=picIds]').val().split(';');
if(ids[0] != '') {
ids.forEach(function(data) {
$('<li class="img-list-item" data-pid="'
+ data
+ '">'
+ '<img src="/static/images/users/'
+ data
+ '" class="img-list-img"/>'
+ '<span class="btn-img-del">x</span>'
+ '</li>').insertBefore('.img-list-btn');
})
if(ids.length > 3) {
$('.img-list-btn').toggle();
}
}
}
initImgList(); |
-- Type: PROCEDURE; Owner: DEAPP; Name: DUMP_TABLE_TO_CSV
CREATE OR REPLACE PROCEDURE "DEAPP"."DUMP_TABLE_TO_CSV" ( p_tname in varchar2,
p_dir in varchar2,
p_filename in varchar2 )
is
l_output utl_file.file_type;
l_theCursor integer default dbms_sql.open_cursor;
l_columnValue varchar2(4000);
l_status integer;
l_query varchar2(1000)
default 'select * from ' || p_tname;
l_colCnt number := 0;
l_separator varchar2(1);
l_descTbl dbms_sql.desc_tab;
begin
l_output := utl_file.fopen( p_dir, p_filename, 'w' );
execute immediate 'alter session set nls_date_format=''dd-mon-yyyy hh24:mi:ss''
';
dbms_sql.parse( l_theCursor, l_query, dbms_sql.native );
dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl );
for i in 1 .. l_colCnt loop
utl_file.put( l_output, l_separator || '"' || l_descTbl(i).col_name || '"'
);
dbms_sql.define_column( l_theCursor, i, l_columnValue, 4000 );
l_separator := ',';
end loop;
utl_file.new_line( l_output );
l_status := dbms_sql.execute(l_theCursor);
while ( dbms_sql.fetch_rows(l_theCursor) > 0 ) loop
l_separator := '';
for i in 1 .. l_colCnt loop
dbms_sql.column_value( l_theCursor, i, l_columnValue );
utl_file.put( l_output, l_separator || l_columnValue );
l_separator := ',';
end loop;
utl_file.new_line( l_output );
end loop;
dbms_sql.close_cursor(l_theCursor);
utl_file.fclose( l_output );
execute immediate 'alter session set nls_date_format=''dd-MON-yy'' ';
exception
when others then
execute immediate 'alter session set nls_date_format=''dd-MON-yy'' ';
raise;
end;
/ |
#ifndef MPV_CLIENT_API_H_
#define MPV_CLIENT_API_H_
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* The version is incremented on each API change. The 16 lower bits form the
* minor version number, and the 16 higher bits the major version number. If
* the API becomes incompatible to previous versions, the major version
* number is incremented. This affects only C part, and not properties and
* options.
*
* Every API bump is described in DOCS/client-api-changes.rst
*
* You can use MPV_MAKE_VERSION() and compare the result with integer
* relational operators (<, >, <=, >=).
*/
#define MPV_MAKE_VERSION(major, minor) (((major) << 16) | (minor) | 0UL)
#define <API key> MPV_MAKE_VERSION(1, 24)
/**
* Return the <API key> the mpv source has been compiled with.
*/
unsigned long <API key>(void);
/**
* Client context used by the client API. Every client has its own private
* handle.
*/
typedef struct mpv_handle mpv_handle;
/**
* List of error codes than can be returned by API functions. 0 and positive
* return values always mean success, negative values are always errors.
*/
typedef enum mpv_error {
/**
* No error happened (used to signal successful operation).
* Keep in mind that many API functions returning error codes can also
* return positive values, which also indicate success. API users can
* hardcode the fact that ">= 0" means success.
*/
MPV_ERROR_SUCCESS = 0,
/**
* The event ringbuffer is full. This means the client is choked, and can't
* receive any events. This can happen when too many asynchronous requests
* have been made, but not answered. Probably never happens in practice,
* unless the mpv core is frozen for some reason, and the client keeps
* making asynchronous requests. (Bugs in the client API implementation
* could also trigger this, e.g. if events become "lost".)
*/
<API key> = -1,
/**
* Memory allocation failed.
*/
MPV_ERROR_NOMEM = -2,
/**
* The mpv core wasn't configured and initialized yet. See the notes in
* mpv_create().
*/
<API key> = -3,
/**
* Generic catch-all error if a parameter is set to an invalid or
* unsupported value. This is used if there is no better error code.
*/
<API key> = -4,
/**
* Trying to set an option that doesn't exist.
*/
<API key> = -5,
/**
* Trying to set an option using an unsupported MPV_FORMAT.
*/
<API key> = -6,
/**
* Setting the option failed. Typically this happens if the provided option
* value could not be parsed.
*/
<API key> = -7,
/**
* The accessed property doesn't exist.
*/
<API key> = -8,
/**
* Trying to set or get a property using an unsupported MPV_FORMAT.
*/
<API key> = -9,
/**
* The property exists, but is not available. This usually happens when the
* associated subsystem is not active, e.g. querying audio parameters while
* audio is disabled.
*/
<API key> = -10,
/**
* Error setting or getting a property.
*/
<API key> = -11,
/**
* General error when running a command with mpv_command and similar.
*/
MPV_ERROR_COMMAND = -12,
/**
* Generic error on loading (usually used with mpv_event_end_file.error).
*/
<API key> = -13,
/**
* Initializing the audio output failed.
*/
<API key> = -14,
/**
* Initializing the video output failed.
*/
<API key> = -15,
/**
* There was no audio or video data to play. This also happens if the
* file was recognized, but did not contain any audio or video streams,
* or no streams were selected.
*/
<API key> = -16,
/**
* When trying to load the file, the file format could not be determined,
* or the file was too broken to open it.
*/
<API key> = -17,
/**
* Generic error for signaling that certain system requirements are not
* fulfilled.
*/
<API key> = -18,
/**
* The API function which was called is a stub only.
*/
<API key> = -19,
/**
* Unspecified error.
*/
MPV_ERROR_GENERIC = -20
} mpv_error;
/**
* Return a string describing the error. For unknown errors, the string
* "unknown error" is returned.
*
* @param error error number, see enum mpv_error
* @return A static string describing the error. The string is completely
* static, i.e. doesn't need to be deallocated, and is valid forever.
*/
const char *mpv_error_string(int error);
/**
* General function to deallocate memory returned by some of the API functions.
* Call this only if it's explicitly documented as allowed. Calling this on
* mpv memory not owned by the caller will lead to undefined behavior.
*
* @param data A valid pointer returned by the API, or NULL.
*/
void mpv_free(void *data);
/**
* Return the name of this client handle. Every client has its own unique
* name, which is mostly used for user interface purposes.
*
* @return The client name. The string is read-only and is valid until the
* mpv_handle is destroyed.
*/
const char *mpv_client_name(mpv_handle *ctx);
/**
* Create a new mpv instance and an associated client API handle to control
* the mpv instance. This instance is in a pre-initialized state,
* and needs to be initialized to be actually used with most other API
* functions.
*
* Some API functions will return <API key> in the uninitialized
* state. You can call mpv_set_property() (or <API key>() and
* other variants, and before mpv 0.21.0 mpv_set_option() etc.) to set initial
* options. After this, call mpv_initialize() to start the player, and then use
* e.g. mpv_command() to start playback of a file.
*
* The point of separating handle creation and actual initialization is that
* you can configure things which can't be changed during runtime.
*
* Unlike the command line player, this will have initial settings suitable
* for embedding in applications. The following settings are different:
* - stdin/stdout/stderr and the terminal will never be accessed. This is
* equivalent to setting the --no-terminal option.
* (Technically, this also suppresses C signal handling.)
* - No config files will be loaded. This is roughly equivalent to using
* --no-config. Since libmpv 1.15, you can actually re-enable this option,
* which will make libmpv load config files during mpv_initialize(). If you
* do this, you are strongly encouraged to set the "config-dir" option too.
* (Otherwise it will load the mpv command line player's config.)
* - Idle mode is enabled, which means the playback core will enter idle mode
* if there are no more files to play on the internal playlist, instead of
* exiting. This is equivalent to the --idle option.
* - Disable parts of input handling.
* - Most of the different settings can be viewed with the command line player
* by running "mpv --show-profile=libmpv".
*
* All this assumes that API users want a mpv instance that is strictly
* isolated from the command line player's configuration, user settings, and
* so on. You can re-enable disabled features by setting the appropriate
* options.
*
* The mpv command line parser is not available through this API, but you can
* set individual options with mpv_set_property(). Files for playback must be
* loaded with mpv_command() or others.
*
* Note that you should avoid doing concurrent accesses on the uninitialized
* client handle. (Whether concurrent access is definitely allowed or not has
* yet to be decided.)
*
* @return a new mpv client API handle. Returns NULL on error. Currently, this
* can happen in the following situations:
* - out of memory
* - LC_NUMERIC is not set to "C" (see general remarks)
*/
mpv_handle *mpv_create(void);
/**
* Initialize an uninitialized mpv instance. If the mpv instance is already
* running, an error is retuned.
*
* This function needs to be called to make full use of the client API if the
* client API handle was created with mpv_create().
*
* Only the following options require to be set _before_ mpv_initialize():
* - options which are only read at initialization time:
* - config
* - config-dir
* - input-conf
* - load-scripts
* - script
* - <API key>
* - input-app-events (OSX)
* - all encoding mode options
*
* @return error code
*/
int mpv_initialize(mpv_handle *ctx);
/**
* Disconnect and destroy the mpv_handle. ctx will be deallocated with this
* API call. This leaves the player running. If you want to be sure that the
* player is terminated, send a "quit" command, and wait until the
* MPV_EVENT_SHUTDOWN event is received, or use <API key>().
*/
void mpv_detach_destroy(mpv_handle *ctx);
/**
* Similar to mpv_detach_destroy(), but brings the player and all clients down
* as well, and waits until all of them are destroyed. This function blocks. The
* advantage over mpv_detach_destroy() is that while mpv_detach_destroy() merely
* detaches the client handle from the player, this function quits the player,
* waits until all other clients are destroyed (i.e. all mpv_handles are
* detached), and also waits for the final termination of the player.
*
* Since mpv_detach_destroy() is called somewhere on the way, it's not safe to
* call other functions concurrently on the same context.
*
* If this is called on a mpv_handle that was not created with mpv_create(),
* this function will merely send a quit command and then call
* mpv_detach_destroy(), without waiting for the actual shutdown.
*/
void <API key>(mpv_handle *ctx);
/**
* Create a new client handle connected to the same player core as ctx. This
* context has its own event queue, its own mpv_request_event() state, its own
* <API key>() state, its own set of observed properties, and
* its own state for asynchronous operations. Otherwise, everything is shared.
*
* This handle should be destroyed with mpv_detach_destroy() if no longer
* needed. The core will live as long as there is at least 1 handle referencing
* it. Any handle can make the core quit, which will result in every handle
* receiving MPV_EVENT_SHUTDOWN.
*
* This function can not be called before the main handle was initialized with
* mpv_initialize(). The new handle is always initialized, unless ctx=NULL was
* passed.
*
* @param ctx Used to get the reference to the mpv core; handle-specific
* settings and parameters are not used.
* If NULL, this function behaves like mpv_create() (ignores name).
* @param name The client name. This will be returned by mpv_client_name(). If
* the name is already in use, or contains non-alphanumeric
* characters (other than '_'), the name is modified to fit.
* If NULL, an arbitrary name is automatically chosen.
* @return a new handle, or NULL on error
*/
mpv_handle *mpv_create_client(mpv_handle *ctx, const char *name);
/**
* Load a config file. This loads and parses the file, and sets every entry in
* the config file's default section as if <API key>() is called.
*
* The filename should be an absolute path. If it isn't, the actual path used
* is unspecified. (Note: an absolute path starts with '/' on UNIX.) If the
* file wasn't found, <API key> is returned.
*
* If a fatal error happens when parsing a config file, <API key>
* is returned. Errors when setting options as well as other types or errors
* are ignored (even if options do not exist). You can still try to capture
* the resulting error messages with <API key>(). Note that it's
* possible that some options were successfully set even if any of these errors
* happen.
*
* @param filename absolute path to the config file on the local filesystem
* @return error code
*/
int <API key>(mpv_handle *ctx, const char *filename);
/**
* This does nothing since mpv 0.23.0 (API version 1.24). Below is the
* description of the old behavior.
*
* Stop the playback thread. This means the core will stop doing anything, and
* only run and answer to client API requests. This is sometimes useful; for
* example, no new frame will be queued to the video output, so doing requests
* which have to wait on the video output can run instantly.
*
* Suspension is reentrant and recursive for convenience. Any thread can call
* the suspend function multiple times, and the playback thread will remain
* suspended until the last thread resumes it. Note that during suspension, all
* clients still have concurrent access to the core, which is serialized through
* a single mutex.
*
* Call mpv_resume() to resume the playback thread. You must call mpv_resume()
* for each mpv_suspend() call. Calling mpv_resume() more often than
* mpv_suspend() is not allowed.
*
* Calling this on an uninitialized player (see mpv_create()) will deadlock.
*
* @deprecated This function, as well as mpv_resume(), are deprecated, and
* will stop doing anything soon. Their semantics were never
* well-defined, and their usefulness is extremely limited. The
* calls will remain stubs in order to keep ABI compatibility.
*/
void mpv_suspend(mpv_handle *ctx);
/**
* See mpv_suspend().
*/
void mpv_resume(mpv_handle *ctx);
/**
* Return the internal time in microseconds. This has an arbitrary start offset,
* but will never wrap or go backwards.
*
* Note that this is always the real time, and doesn't necessarily have to do
* with playback time. For example, playback could go faster or slower due to
* playback speed, or due to playback being paused. Use the "time-pos" property
* instead to get the playback status.
*
* Unlike other libmpv APIs, this can be called at absolutely any time (even
* within wakeup callbacks), as long as the context is valid.
*/
int64_t mpv_get_time_us(mpv_handle *ctx);
/**
* Data format for options and properties. The API functions to get/set
* properties and options support multiple formats, and this enum describes
* them.
*/
typedef enum mpv_format {
/**
* Invalid. Sometimes used for empty values.
*/
MPV_FORMAT_NONE = 0,
/**
* The basic type is char*. It returns the raw property string, like
* using ${=property} in input.conf (see input.rst).
*
* NULL isn't an allowed value.
*
* Warning: although the encoding is usually UTF-8, this is not always the
* case. File tags often store strings in some legacy codepage,
* and even filenames don't necessarily have to be in UTF-8 (at
* least on Linux). If you pass the strings to code that requires
* valid UTF-8, you have to sanitize it in some way.
* On Windows, filenames are always UTF-8, and libmpv converts
* between UTF-8 and UTF-16 when using win32 API functions. See
* the "Encoding of filenames" section for details.
*
* Example for reading:
*
* char *result = NULL;
* if (mpv_get_property(ctx, "property", MPV_FORMAT_STRING, &result) < 0)
* goto error;
* printf("%s\n", result);
* mpv_free(result);
*
* Or just use <API key>().
*
* Example for writing:
*
* char *value = "the new value";
* // yep, you pass the address to the variable
* // (needed for symmetry with other types and mpv_get_property)
* mpv_set_property(ctx, "property", MPV_FORMAT_STRING, &value);
*
* Or just use <API key>().
*
*/
MPV_FORMAT_STRING = 1,
/**
* The basic type is char*. It returns the OSD property string, like
* using ${property} in input.conf (see input.rst). In many cases, this
* is the same as the raw string, but in other cases it's formatted for
* display on OSD. It's intended to be human readable. Do not attempt to
* parse these strings.
*
* Only valid when doing read access. The rest works like MPV_FORMAT_STRING.
*/
<API key> = 2,
/**
* The basic type is int. The only allowed values are 0 ("no")
* and 1 ("yes").
*
* Example for reading:
*
* int result;
* if (mpv_get_property(ctx, "property", MPV_FORMAT_FLAG, &result) < 0)
* goto error;
* printf("%s\n", result ? "true" : "false");
*
* Example for writing:
*
* int flag = 1;
* mpv_set_property(ctx, "property", MPV_FORMAT_FLAG, &flag);
*/
MPV_FORMAT_FLAG = 3,
/**
* The basic type is int64_t.
*/
MPV_FORMAT_INT64 = 4,
/**
* The basic type is double.
*/
MPV_FORMAT_DOUBLE = 5,
/**
* The type is mpv_node.
*
* For reading, you usually would pass a pointer to a stack-allocated
* mpv_node value to mpv, and when you're done you call
* <API key>(&node).
* You're expected not to write to the data - if you have to, copy it
* first (which you have to do manually).
*
* For writing, you construct your own mpv_node, and pass a pointer to the
* API. The API will never write to your data (and copy it if needed), so
* you're free to use any form of allocation or memory management you like.
*
* Warning: when reading, always check the mpv_node.format member. For
* example, properties might change their type in future versions
* of mpv, or sometimes even during runtime.
*
* Example for reading:
*
* mpv_node result;
* if (mpv_get_property(ctx, "property", MPV_FORMAT_NODE, &result) < 0)
* goto error;
* printf("format=%d\n", (int)result.format);
* <API key>(&result).
*
* Example for writing:
*
* mpv_node value;
* value.format = MPV_FORMAT_STRING;
* value.u.string = "hello";
* mpv_set_property(ctx, "property", MPV_FORMAT_NODE, &value);
*/
MPV_FORMAT_NODE = 6,
/**
* Used with mpv_node only. Can usually not be used directly.
*/
<API key> = 7,
/**
* See <API key>.
*/
MPV_FORMAT_NODE_MAP = 8,
/**
* A raw, untyped byte array. Only used only with mpv_node, and only in
* some very special situations. (Currently, only for the screenshot-raw
* command.)
*/
<API key> = 9
} mpv_format;
/**
* Generic data storage.
*
* If mpv writes this struct (e.g. via mpv_get_property()), you must not change
* the data. In some cases (mpv_get_property()), you have to free it with
* <API key>(). If you fill this struct yourself, you're also
* responsible for freeing it, and you must not call <API key>().
*/
typedef struct mpv_node {
union {
char *string; /** valid if format==MPV_FORMAT_STRING */
int flag; /** valid if format==MPV_FORMAT_FLAG */
int64_t int64; /** valid if format==MPV_FORMAT_INT64 */
double double_; /** valid if format==MPV_FORMAT_DOUBLE */
/**
* valid if format==<API key>
* or if format==MPV_FORMAT_NODE_MAP
*/
struct mpv_node_list *list;
/**
* valid if format==<API key>
*/
struct mpv_byte_array *ba;
} u;
/**
* Type of the data stored in this struct. This value rules what members in
* the given union can be accessed. The following formats are currently
* defined to be allowed in mpv_node:
*
* MPV_FORMAT_STRING (u.string)
* MPV_FORMAT_FLAG (u.flag)
* MPV_FORMAT_INT64 (u.int64)
* MPV_FORMAT_DOUBLE (u.double_)
* <API key> (u.list)
* MPV_FORMAT_NODE_MAP (u.list)
* <API key> (u.ba)
* MPV_FORMAT_NONE (no member)
*
* If you encounter a value you don't know, you must not make any
* assumptions about the contents of union u.
*/
mpv_format format;
} mpv_node;
/**
* (see mpv_node)
*/
typedef struct mpv_node_list {
/**
* Number of entries. Negative values are not allowed.
*/
int num;
/**
* <API key>:
* values[N] refers to value of the Nth item
*
* MPV_FORMAT_NODE_MAP:
* values[N] refers to value of the Nth key/value pair
*
* If num > 0, values[0] to values[num-1] (inclusive) are valid.
* Otherwise, this can be NULL.
*/
mpv_node *values;
/**
* <API key>:
* unused (typically NULL), access is not allowed
*
* MPV_FORMAT_NODE_MAP:
* keys[N] refers to key of the Nth key/value pair. If num > 0, keys[0] to
* keys[num-1] (inclusive) are valid. Otherwise, this can be NULL.
* The keys are in random order. The only guarantee is that keys[N] belongs
* to the value values[N]. NULL keys are not allowed.
*/
char **keys;
} mpv_node_list;
/**
* (see mpv_node)
*/
typedef struct mpv_byte_array {
/**
* Pointer to the data. In what format the data is stored is up to whatever
* uses <API key>.
*/
void *data;
/**
* Size of the data pointed to by ptr.
*/
size_t size;
} mpv_byte_array;
/**
* Frees any data referenced by the node. It doesn't free the node itself.
* Call this only if the mpv client API set the node. If you constructed the
* node yourself (manually), you have to free it yourself.
*
* If node->format is MPV_FORMAT_NONE, this call does nothing. Likewise, if
* the client API sets a node with this format, this function doesn't need to
* be called. (This is just a clarification that there's no danger of anything
* strange happening in these cases.)
*/
void <API key>(mpv_node *node);
/**
* Set an option. Note that you can't normally set options during runtime. It
* works in uninitialized state (see mpv_create()), and in some cases in at
* runtime.
*
* Using a format other than MPV_FORMAT_NODE is equivalent to constructing a
* mpv_node with the given format and data, and passing the mpv_node to this
* function.
*
* Note: this is semi-deprecated. For most purposes, this is not needed anymore.
* Starting with mpv version 0.21.0 (version 1.23) most options can be set
* with mpv_set_property() (and related functions), and even before
* mpv_initialize(). In some obscure corner cases, using this function
* to set options might still be required (see below, and also section
* "Inconsistencies between options and properties" on the manpage). Once
* these are resolved, the option setting functions might be fully
* deprecated.
*
* The following options still need to be set either _before_
* mpv_initialize() with mpv_set_property() (or related functions), or
* with mpv_set_option() (or related functions) at any time:
* - options shadowed by deprecated properties:
* - demuxer (property deprecated in 0.21.0)
* - idle (property deprecated in 0.21.0)
* - fps (property deprecated in 0.21.0)
* - cache (property deprecated in 0.21.0)
* - length (property deprecated in 0.10.0)
* - audio-samplerate (property deprecated in 0.10.0)
* - audio-channels (property deprecated in 0.10.0)
* - audio-format (property deprecated in 0.10.0)
* - deprecated options shadowed by properties:
* - chapter (option deprecated in 0.21.0)
* - playlist-pos (option deprecated in 0.21.0)
* The deprecated properties will be removed in mpv 0.23.0.
*
* @param name Option name. This is the same as on the mpv command line, but
* without the leading "--".
* @param format see enum mpv_format.
* @param[in] data Option value (according to the format).
* @return error code
*/
int mpv_set_option(mpv_handle *ctx, const char *name, mpv_format format,
void *data);
/**
* Convenience function to set an option to a string value. This is like
* calling mpv_set_option() with MPV_FORMAT_STRING.
*
* @return error code
*/
int <API key>(mpv_handle *ctx, const char *name, const char *data);
/**
* Send a command to the player. Commands are the same as those used in
* input.conf, except that this function takes parameters in a pre-split
* form.
*
* The commands and their parameters are documented in input.rst.
*
* @param[in] args NULL-terminated list of strings. Usually, the first item
* is the command, and the following items are arguments.
* @return error code
*/
int mpv_command(mpv_handle *ctx, const char **args);
/**
* Same as mpv_command(), but allows passing structured data in any format.
* In particular, calling mpv_command() is exactly like calling
* mpv_command_node() with the format set to <API key>, and
* every arg passed in order as MPV_FORMAT_STRING.
*
* @param[in] args mpv_node with format set to <API key>; each entry
* is an argument using an arbitrary format (the format must be
* compatible to the used command). Usually, the first item is
* the command name (as MPV_FORMAT_STRING).
* @param[out] result Optional, pass NULL if unused. If not NULL, and if the
* function succeeds, this is set to command-specific return
* data. You must call <API key>() to free it
* (again, only if the command actually succeeds).
* Currently, no command uses this, but that can change in
* the future.
* @return error code (the result parameter is not set on error)
*/
int mpv_command_node(mpv_handle *ctx, mpv_node *args, mpv_node *result);
/**
* Same as mpv_command, but use input.conf parsing for splitting arguments.
* This is slightly simpler, but also more error prone, since arguments may
* need quoting/escaping.
*/
int mpv_command_string(mpv_handle *ctx, const char *args);
/**
* Same as mpv_command, but run the command asynchronously.
*
* Commands are executed asynchronously. You will receive a
* <API key> event. (This event will also have an
* error code set if running the command failed.)
*
* @param reply_userdata the value mpv_event.reply_userdata of the reply will
* be set to (see section about asynchronous calls)
* @param args NULL-terminated list of strings (see mpv_command())
* @return error code (if parsing or queuing the command fails)
*/
int mpv_command_async(mpv_handle *ctx, uint64_t reply_userdata,
const char **args);
/**
* Same as mpv_command_node(), but run it asynchronously. Basically, this
* function is to mpv_command_node() what mpv_command_async() is to
* mpv_command().
*
* See mpv_command_async() for details. Retrieving the result is not
* supported yet.
*
* @param reply_userdata the value mpv_event.reply_userdata of the reply will
* be set to (see section about asynchronous calls)
* @param args as in mpv_command_node()
* @return error code (if parsing or queuing the command fails)
*/
int <API key>(mpv_handle *ctx, uint64_t reply_userdata,
mpv_node *args);
/**
* Set a property to a given value. Properties are essentially variables which
* can be queried or set at runtime. For example, writing to the pause property
* will actually pause or unpause playback.
*
* If the format doesn't match with the internal format of the property, access
* usually will fail with <API key>. In some cases, the data
* is automatically converted and access succeeds. For example, MPV_FORMAT_INT64
* is always converted to MPV_FORMAT_DOUBLE, and access using MPV_FORMAT_STRING
* usually invokes a string parser. The same happens when calling this function
* with MPV_FORMAT_NODE: the underlying format may be converted to another
* type if possible.
*
* Using a format other than MPV_FORMAT_NODE is equivalent to constructing a
* mpv_node with the given format and data, and passing the mpv_node to this
* function. (Before API version 1.21, this was different.)
*
* Note: starting with mpv 0.21.0 (client API version 1.23), this can be used to
* set options in general. It even can be used before mpv_initialize()
* has been called. If called before mpv_initialize(), setting properties
* not backed by options will result in <API key>.
* In some cases, properties and options still conflict. In these cases,
* mpv_set_property() accesses the options before mpv_initialize(), and
* the properties after mpv_initialize(). These conflicts will be removed
* in mpv 0.23.0. See mpv_set_option() for further remarks.
*
* @param name The property name. See input.rst for a list of properties.
* @param format see enum mpv_format.
* @param[in] data Option value.
* @return error code
*/
int mpv_set_property(mpv_handle *ctx, const char *name, mpv_format format,
void *data);
/**
* Convenience function to set a property to a string value.
*
* This is like calling mpv_set_property() with MPV_FORMAT_STRING.
*/
int <API key>(mpv_handle *ctx, const char *name, const char *data);
int <API key>(mpv_handle *ctx, uint64_t reply_userdata,
const char *name, mpv_format format, void *data);
/**
* Read the value of the given property.
*
* If the format doesn't match with the internal format of the property, access
* usually will fail with <API key>. In some cases, the data
* is automatically converted and access succeeds. For example, MPV_FORMAT_INT64
* is always converted to MPV_FORMAT_DOUBLE, and access using MPV_FORMAT_STRING
* usually invokes a string formatter.
*
* @param name The property name.
* @param format see enum mpv_format.
* @param[out] data Pointer to the variable holding the option value. On
* success, the variable will be set to a copy of the option
* value. For formats that require dynamic memory allocation,
* you can free the value with mpv_free() (strings) or
* <API key>() (MPV_FORMAT_NODE).
* @return error code
*/
int mpv_get_property(mpv_handle *ctx, const char *name, mpv_format format,
void *data);
/**
* Return the value of the property with the given name as string. This is
* equivalent to mpv_get_property() with MPV_FORMAT_STRING.
*
* See MPV_FORMAT_STRING for character encoding issues.
*
* On error, NULL is returned. Use mpv_get_property() if you want fine-grained
* error reporting.
*
* @param name The property name.
* @return Property value, or NULL if the property can't be retrieved. Free
* the string with mpv_free().
*/
char *<API key>(mpv_handle *ctx, const char *name);
/**
* Return the property as "OSD" formatted string. This is the same as
* <API key>, but using <API key>.
*
* @return Property value, or NULL if the property can't be retrieved. Free
* the string with mpv_free().
*/
char *<API key>(mpv_handle *ctx, const char *name);
/**
* Get a property asynchronously. You will receive the result of the operation
* as well as the property data with the <API key> event.
* You should check the mpv_event.error field on the reply event.
*
* @param reply_userdata see section about asynchronous calls
* @param name The property name.
* @param format see enum mpv_format.
* @return error code if sending the request failed
*/
int <API key>(mpv_handle *ctx, uint64_t reply_userdata,
const char *name, mpv_format format);
/**
* Get a notification whenever the given property changes. You will receive
* updates as <API key>. Note that this is not very precise:
* for some properties, it may not send updates even if the property changed.
* This depends on the property, and it's a valid feature request to ask for
* better update handling of a specific property. (For some properties, like
* ``clock``, which shows the wall clock, this mechanism doesn't make too
* much sense anyway.)
*
* Property changes are coalesced: the change events are returned only once the
* event queue becomes empty (e.g. mpv_wait_event() would block or return
* MPV_EVENT_NONE), and then only one event per changed property is returned.
*
* Normally, change events are sent only if the property value changes according
* to the requested format. mpv_event_property will contain the property value
* as data member.
*
* Warning: if a property is unavailable or retrieving it caused an error,
* MPV_FORMAT_NONE will be set in mpv_event_property, even if the
* format parameter was set to a different value. In this case, the
* mpv_event_property.data field is invalid.
*
* If the property is observed with the format parameter set to MPV_FORMAT_NONE,
* you get low-level notifications whether the property _may_ have changed, and
* the data member in mpv_event_property will be unset. With this mode, you
* will have to determine yourself whether the property really changd. On the
* other hand, this mechanism can be faster and uses less resources.
*
* Observing a property that doesn't exist is allowed. (Although it may still
* cause some sporadic change events.)
*
* Keep in mind that you will get change notifications even if you change a
* property yourself. Try to avoid endless feedback loops, which could happen
* if you react to the change notifications triggered by your own change.
*
* @param reply_userdata This will be used for the mpv_event.reply_userdata
* field for the received <API key>
* events. (Also see section about asynchronous calls,
* although this function is somewhat different from
* actual asynchronous calls.)
* If you have no use for this, pass 0.
* Also see <API key>().
* @param name The property name.
* @param format see enum mpv_format. Can be MPV_FORMAT_NONE to omit values
* from the change events.
* @return error code (usually fails only on OOM or unsupported format)
*/
int <API key>(mpv_handle *mpv, uint64_t reply_userdata,
const char *name, mpv_format format);
/**
* Undo <API key>(). This will remove all observed properties for
* which the given number was passed as reply_userdata to <API key>.
*
* @param <API key> ID that was passed to <API key>
* @return negative value is an error code, >=0 is number of removed properties
* on success (includes the case when 0 were removed)
*/
int <API key>(mpv_handle *mpv, uint64_t <API key>);
typedef enum mpv_event_id {
/**
* Nothing happened. Happens on timeouts or sporadic wakeups.
*/
MPV_EVENT_NONE = 0,
/**
* Happens when the player quits. The player enters a state where it tries
* to disconnect all clients. Most requests to the player will fail, and
* mpv_wait_event() will always return instantly (returning new shutdown
* events if no other events are queued). The client should react to this
* and quit with mpv_detach_destroy() as soon as possible.
*/
MPV_EVENT_SHUTDOWN = 1,
/**
* See <API key>().
*/
<API key> = 2,
/**
* Reply to a <API key>() request.
* See also mpv_event and mpv_event_property.
*/
<API key> = 3,
/**
* Reply to a <API key>() request.
* (Unlike <API key>, mpv_event_property is not used.)
*/
<API key> = 4,
/**
* Reply to a mpv_command_async() request.
*/
<API key> = 5,
/**
* Notification before playback start of a file (before the file is loaded).
*/
<API key> = 6,
/**
* Notification after playback end (after the file was unloaded).
* See also mpv_event and mpv_event_end_file.
*/
MPV_EVENT_END_FILE = 7,
/**
* Notification when the file has been loaded (headers were read etc.), and
* decoding starts.
*/
<API key> = 8,
/**
* The list of video/audio/subtitle tracks was changed. (E.g. a new track
* was found. This doesn't necessarily indicate a track switch; for this,
* <API key> is used.)
*
* @deprecated This is equivalent to using <API key>() on the
* "track-list" property. The event is redundant, and might
* be removed in the far future.
*/
<API key> = 9,
/**
* A video/audio/subtitle track was switched on or off.
*
* @deprecated This is equivalent to using <API key>() on the
* "vid", "aid", and "sid" properties. The event is redundant,
* and might be removed in the far future.
*/
<API key> = 10,
/**
* Idle mode was entered. In this mode, no file is played, and the playback
* core waits for new commands. (The command line player normally quits
* instead of entering idle mode, unless --idle was specified. If mpv
* was started with mpv_create(), idle mode is enabled by default.)
*/
MPV_EVENT_IDLE = 11,
/**
* Playback was paused. This indicates the user pause state.
*
* The user pause state is the state the user requested (changed with the
* "pause" property). There is an internal pause state too, which is entered
* if e.g. the network is too slow (the "core-idle" property generally
* indicates whether the core is playing or waiting).
*
* This event is sent whenever any pause states change, not only the user
* state. You might get multiple events in a row while these states change
* independently. But the event ID sent always indicates the user pause
* state.
*
* If you don't want to deal with this, use <API key>() on the
* "pause" property and ignore MPV_EVENT_PAUSE/UNPAUSE. Likewise, the
* "core-idle" property tells you whether video is actually playing or not.
*
* @deprecated The event is redundant with <API key>() as
* mentioned above, and might be removed in the far future.
*/
MPV_EVENT_PAUSE = 12,
/**
* Playback was unpaused. See MPV_EVENT_PAUSE for not so obvious details.
*
* @deprecated The event is redundant with <API key>() as
* explained in the MPV_EVENT_PAUSE comments, and might be
* removed in the far future.
*/
MPV_EVENT_UNPAUSE = 13,
/**
* Sent every time after a video frame is displayed. Note that currently,
* this will be sent in lower frequency if there is no video, or playback
* is paused - but that will be removed in the future, and it will be
* restricted to video frames only.
*/
MPV_EVENT_TICK = 14,
/**
* @deprecated This was used internally with the internal "script_dispatch"
* command to dispatch keyboard and mouse input for the OSC.
* It was never useful in general and has been completely
* replaced with "script-binding".
* This event never happens anymore, and is included in this
* header only for compatibility.
*/
<API key> = 15,
/**
* Triggered by the script-message input command. The command uses the
* first argument of the command as client name (see mpv_client_name()) to
* dispatch the message, and passes along all arguments starting from the
* second argument as strings.
* See also mpv_event and <API key>.
*/
<API key> = 16,
/**
* Happens after video changed in some way. This can happen on resolution
* changes, pixel format changes, or video filter changes. The event is
* sent after the video filters and the VO are reconfigured. Applications
* embedding a mpv window should listen to this event in order to resize
* the window if needed.
* Note that this event can happen sporadically, and you should check
* yourself whether the video parameters really changed before doing
* something expensive.
*/
<API key> = 17,
/**
* Similar to <API key>. This is relatively uninteresting,
* because there is no such thing as audio output embedding.
*/
<API key> = 18,
/**
* Happens when metadata (like file tags) is possibly updated. (It's left
* unspecified whether this happens on file start or only when it changes
* within a file.)
*
* @deprecated This is equivalent to using <API key>() on the
* "metadata" property. The event is redundant, and might
* be removed in the far future.
*/
<API key> = 19,
/**
* Happens when a seek was initiated. Playback stops. Usually it will
* resume with <API key> as soon as the seek is finished.
*/
MPV_EVENT_SEEK = 20,
/**
* There was a discontinuity of some sort (like a seek), and playback
* was reinitialized. Usually happens after seeking, or ordered chapter
* segment switches. The main purpose is allowing the client to detect
* when a seek request is finished.
*/
<API key> = 21,
/**
* Event sent due to <API key>().
* See also mpv_event and mpv_event_property.
*/
<API key> = 22,
/**
* Happens when the current chapter changes.
*
* @deprecated This is equivalent to using <API key>() on the
* "chapter" property. The event is redundant, and might
* be removed in the far future.
*/
<API key> = 23,
/**
* Happens if the internal per-mpv_handle ringbuffer overflows, and at
* least 1 event had to be dropped. This can happen if the client doesn't
* read the event queue quickly enough with mpv_wait_event(), or if the
* client makes a very large number of asynchronous calls at once.
*
* Event delivery will continue normally once this event was returned
* (this forces the client to empty the queue completely).
*/
<API key> = 24
// Internal note: adjust INTERNAL_EVENT_BASE when adding new events.
} mpv_event_id;
/**
* Return a string describing the event. For unknown events, NULL is returned.
*
* Note that all events actually returned by the API will also yield a non-NULL
* string with this function.
*
* @param event event ID, see see enum mpv_event_id
* @return A static string giving a short symbolic name of the event. It
* consists of lower-case alphanumeric characters and can include "-"
* characters. This string is suitable for use in e.g. scripting
* interfaces.
* The string is completely static, i.e. doesn't need to be deallocated,
* and is valid forever.
*/
const char *mpv_event_name(mpv_event_id event);
typedef struct mpv_event_property {
/**
* Name of the property.
*/
const char *name;
/**
* Format of the data field in the same struct. See enum mpv_format.
* This is always the same format as the requested format, except when
* the property could not be retrieved (unavailable, or an error happened),
* in which case the format is MPV_FORMAT_NONE.
*/
mpv_format format;
/**
* Received property value. Depends on the format. This is like the
* pointer argument passed to mpv_get_property().
*
* For example, for MPV_FORMAT_STRING you get the string with:
*
* char *value = *(char **)(event_property->data);
*
* Note that this is set to NULL if retrieving the property failed (the
* format will be MPV_FORMAT_NONE).
* See mpv_event.error for the status.
*/
void *data;
} mpv_event_property;
/**
* Numeric log levels. The lower the number, the more important the message is.
* MPV_LOG_LEVEL_NONE is never used when receiving messages. The string in
* the comment after the value is the name of the log level as used for the
* <API key>() function.
* Unused numeric values are unused, but reserved for future use.
*/
typedef enum mpv_log_level {
MPV_LOG_LEVEL_NONE = 0, /// "no" - disable absolutely all messages
MPV_LOG_LEVEL_FATAL = 10, /// "fatal" - critical/aborting errors
MPV_LOG_LEVEL_ERROR = 20, /// "error" - simple errors
MPV_LOG_LEVEL_WARN = 30, /// "warn" - possible problems
MPV_LOG_LEVEL_INFO = 40, /// "info" - informational message
MPV_LOG_LEVEL_V = 50, /// "v" - noisy informational message
MPV_LOG_LEVEL_DEBUG = 60, /// "debug" - very noisy technical information
MPV_LOG_LEVEL_TRACE = 70, /// "trace" - extremely noisy
} mpv_log_level;
typedef struct <API key> {
/**
* The module prefix, identifies the sender of the message. As a special
* case, if the message buffer overflows, this will be set to the string
* "overflow" (which doesn't appear as prefix otherwise), and the text
* field will contain an informative message.
*/
const char *prefix;
/**
* The log level as string. See <API key>() for possible
* values. The level "no" is never used here.
*/
const char *level;
/**
* The log message. It consists of 1 line of text, and is terminated with
* a newline character. (Before API version 1.6, it could contain multiple
* or partial lines.)
*/
const char *text;
/**
* The same contents as the level field, but as a numeric ID.
* Since API version 1.6.
*/
mpv_log_level log_level;
} <API key>;
Since API version 1.9.
typedef enum mpv_end_file_reason {
/**
* The end of file was reached. Sometimes this may also happen on
* incomplete or corrupted files, or if the network connection was
* interrupted when playing a remote file. It also happens if the
* playback range was restricted with --end or --frames or similar.
*/
<API key> = 0,
/**
* Playback was stopped by an external action (e.g. playlist controls).
*/
<API key> = 2,
/**
* Playback was stopped by the quit command or player shutdown.
*/
<API key> = 3,
/**
* Some kind of error happened that lead to playback abort. Does not
* necessarily happen on incomplete or broken files (in these cases, both
* <API key> or <API key> are possible).
*
* mpv_event_end_file.error will be set.
*/
<API key> = 4,
/**
* The file was a playlist or similar. When the playlist is read, its
* entries will be appended to the playlist after the entry of the current
* file, the entry of the current file is removed, and a MPV_EVENT_END_FILE
* event is sent with reason set to <API key>. Then
* playback continues with the playlist contents.
* Since API version 1.18.
*/
<API key> = 5,
} mpv_end_file_reason;
typedef struct mpv_event_end_file {
/**
* Corresponds to the values in enum mpv_end_file_reason (the "int" type
* will be replaced with mpv_end_file_reason on the next ABI bump).
*
* Unknown values should be treated as unknown.
*/
int reason;
/**
* If reason==<API key>, this contains a mpv error code
* (one of MPV_ERROR_...) giving an approximate reason why playback
* failed. In other cases, this field is 0 (no error).
* Since API version 1.9.
*/
int error;
} mpv_event_end_file;
/** @deprecated see <API key> for remarks
*/
typedef struct <API key> {
int arg0;
const char *type;
} <API key>;
typedef struct <API key> {
/**
* Arbitrary arguments chosen by the sender of the message. If num_args > 0,
* you can access args[0] through args[num_args - 1] (inclusive). What
* these arguments mean is up to the sender and receiver.
* None of the valid items are NULL.
*/
int num_args;
const char **args;
} <API key>;
typedef struct mpv_event {
/**
* One of mpv_event. Keep in mind that later ABI compatible releases might
* add new event types. These should be ignored by the API user.
*/
mpv_event_id event_id;
/**
* This is mainly used for events that are replies to (asynchronous)
* requests. It contains a status code, which is >= 0 on success, or < 0
* on error (a mpv_error value). Usually, this will be set if an
* asynchronous request fails.
* Used for:
* <API key>
* <API key>
* <API key>
*/
int error;
/**
* If the event is in reply to a request (made with this API and this
* API handle), this is set to the reply_userdata parameter of the request
* call. Otherwise, this field is 0.
* Used for:
* <API key>
* <API key>
* <API key>
* <API key>
*/
uint64_t reply_userdata;
/**
* The meaning and contents of the data member depend on the event_id:
* <API key>: mpv_event_property*
* <API key>: mpv_event_property*
* <API key>: <API key>*
* <API key>: <API key>*
* MPV_EVENT_END_FILE: mpv_event_end_file*
* other: NULL
*
* Note: future enhancements might add new event structs for existing or new
* event types.
*/
void *data;
} mpv_event;
/**
* Enable or disable the given event.
*
* Some events are enabled by default. Some events can't be disabled.
*
* (Informational note: currently, all events are enabled by default, except
* MPV_EVENT_TICK.)
*
* @param event See enum mpv_event_id.
* @param enable 1 to enable receiving this event, 0 to disable it.
* @return error code
*/
int mpv_request_event(mpv_handle *ctx, mpv_event_id event, int enable);
/**
* Enable or disable receiving of log messages. These are the messages the
* command line player prints to the terminal. This call sets the minimum
* required log level for a message to be received with <API key>.
*
* @param min_level Minimal log level as string. Valid log levels:
* no fatal error warn info v debug trace
* The value "no" disables all messages. This is the default.
* An exception is the value "terminal-default", which uses the
* log level as set by the "--msg-level" option. This works
* even if the terminal is disabled. (Since API version 1.19.)
* Also see mpv_log_level.
*/
int <API key>(mpv_handle *ctx, const char *min_level);
/**
* Wait for the next event, or until the timeout expires, or if another thread
* makes a call to mpv_wakeup(). Passing 0 as timeout will never wait, and
* is suitable for polling.
*
* The internal event queue has a limited size (per client handle). If you
* don't empty the event queue quickly enough with mpv_wait_event(), it will
* overflow and silently discard further events. If this happens, making
* asynchronous requests will fail as well (with <API key>).
*
* Only one thread is allowed to call this on the same mpv_handle at a time.
* The API won't complain if more than one thread calls this, but it will cause
* race conditions in the client when accessing the shared mpv_event struct.
* Note that most other API functions are not restricted by this, and no API
* function internally calls mpv_wait_event(). Additionally, concurrent calls
* to different mpv_handles are always safe.
*
* @param timeout Timeout in seconds, after which the function returns even if
* no event was received. A MPV_EVENT_NONE is returned on
* timeout. A value of 0 will disable waiting. Negative values
* will wait with an infinite timeout.
* @return A struct containing the event ID and other data. The pointer (and
* fields in the struct) stay valid until the next mpv_wait_event()
* call, or until the mpv_handle is destroyed. You must not write to
* the struct, and all memory referenced by it will be automatically
* released by the API on the next mpv_wait_event() call, or when the
* context is destroyed. The return value is never NULL.
*/
mpv_event *mpv_wait_event(mpv_handle *ctx, double timeout);
/**
* Interrupt the current mpv_wait_event() call. This will wake up the thread
* currently waiting in mpv_wait_event(). If no thread is waiting, the next
* mpv_wait_event() call will return immediately (this is to avoid lost
* wakeups).
*
* mpv_wait_event() will receive a MPV_EVENT_NONE if it's woken up due to
* this call. But note that this dummy event might be skipped if there are
* already other events queued. All what counts is that the waiting thread
* is woken up at all.
*/
void mpv_wakeup(mpv_handle *ctx);
/**
* Set a custom function that should be called when there are new events. Use
* this if blocking in mpv_wait_event() to wait for new events is not feasible.
*
* Keep in mind that the callback will be called from foreign threads. You
* must not make any assumptions of the environment, and you must return as
* soon as possible. You are not allowed to call any client API functions
* inside of the callback. In particular, you should not do any processing in
* the callback, but wake up another thread that does all the work. It's also
* possible that the callback is called from a thread while a mpv API function
* is called (i.e. it can be reentrant).
*
* In general, the client API expects you to call mpv_wait_event() to receive
* notifications, and the wakeup callback is merely a helper utility to make
* this easier in certain situations. Note that it's possible that there's
* only one wakeup callback invocation for multiple events. You should call
* mpv_wait_event() with no timeout until MPV_EVENT_NONE is reached, at which
* point the event queue is empty.
*
* If you actually want to do processing in a callback, spawn a thread that
* does nothing but call mpv_wait_event() in a loop and dispatches the result
* to a callback.
*
* Only one wakeup callback can be set.
*
* @param cb function that should be called if a wakeup is required
* @param d arbitrary userdata passed to cb
*/
void <API key>(mpv_handle *ctx, void (*cb)(void *d), void *d);
/**
* Return a UNIX file descriptor referring to the read end of a pipe. This
* pipe can be used to wake up a poll() based processing loop. The purpose of
* this function is very similar to <API key>(), and provides
* a primitive mechanism to handle coordinating a foreign event loop and the
* libmpv event loop. The pipe is non-blocking. It's closed when the mpv_handle
* is destroyed. This function always returns the same value (on success).
*
* This is in fact implemented using the same underlying code as for
* <API key>() (though they don't conflict), and it is as if each
* callback invocation writes a single 0 byte to the pipe. When the pipe
* becomes readable, the code calling poll() (or select()) on the pipe should
* read all contents of the pipe and then call mpv_wait_event(c, 0) until
* no new events are returned. The pipe contents do not matter and can just
* be discarded. There is not necessarily one byte per readable event in the
* pipe. For example, the pipes are non-blocking, and mpv won't block if the
* pipe is full. Pipes are normally limited to 4096 bytes, so if there are
* more than 4096 events, the number of readable bytes can not equal the number
* of events queued. Also, it's possible that mpv does not write to the pipe
* once it's guaranteed that the client was already signaled. See the example
* below how to do it correctly.
*
* Example:
*
* int pipefd = mpv_get_wakeup_pipe(mpv);
* if (pipefd < 0)
* error();
* while (1) {
* struct pollfd pfds[1] = {
* { .fd = pipefd, .events = POLLIN },
* };
* // Wait until there are possibly new mpv events.
* poll(pfds, 1, -1);
* if (pfds[0].revents & POLLIN) {
* // Empty the pipe. Doing this before calling mpv_wait_event()
* // ensures that no wakeups are missed. It's not so important to
* // make sure the pipe is really empty (it will just cause some
* // additional wakeups in unlikely corner cases).
* char unused[256];
* read(pipefd, unused, sizeof(unused));
* while (1) {
* mpv_event *ev = mpv_wait_event(mpv, 0);
* // If MPV_EVENT_NONE is received, the event queue is empty.
* if (ev->event_id == MPV_EVENT_NONE)
* break;
* // Process the event.
* ...
* }
* }
* }
*
* @return A UNIX FD of the read end of the wakeup pipe, or -1 on error.
* On MS Windows/MinGW, this will always return -1.
*/
int mpv_get_wakeup_pipe(mpv_handle *ctx);
/**
* Block until all asynchronous requests are done. This affects functions like
* mpv_command_async(), which return immediately and return their result as
* events.
*
* This is a helper, and somewhat equivalent to calling mpv_wait_event() in a
* loop until all known asynchronous requests have sent their reply as event,
* except that the event queue is not emptied.
*
* In case you called mpv_suspend() before, this will also forcibly reset the
* suspend counter of the given handle.
*/
void <API key>(mpv_handle *ctx);
typedef enum mpv_sub_api {
/**
* For using mpv's OpenGL renderer on an external OpenGL context.
* mpv_get_sub_api(<API key>) returns <API key>*.
* This context can be used with mpv_opengl_cb_* functions.
* Will return NULL if unavailable (if OpenGL support was not compiled in).
* See opengl_cb.h for details.
*/
<API key> = 1
} mpv_sub_api;
/**
* This is used for additional APIs that are not strictly part of the core API.
* See the individual mpv_sub_api member values.
*/
void *mpv_get_sub_api(mpv_handle *ctx, mpv_sub_api sub_api);
#ifdef __cplusplus
}
#endif
#endif |
#ifndef EVE_LOG_H
#define EVE_LOG_H
#include <string>
#include <vector>
#include <exception>
#include <stdexcept>
#include <regex>
namespace Eve
{
const std::regex rexp_docking("Requested to dock at ([a-zA-Z0-9\\-\\s]+) (M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})) - (([a-zA-Z0-9\\s]+) - )?([a-zA-Z0-9\\s]+) station", std::regex_constants::ECMAScript);
const std::regex rexp_undocking("Undocking from ([a-zA-Z0-9\\-\\s]+) (M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})) - ((Moon [0-9]+) - )?([a-zA-Z0-9\\-\\s]+) to ([a-zA-Z0-9\\-\\s]+) solar system", std::regex::ECMAScript);
const std::regex rexp_planets("([a-zA-Z0-9\\-\\s]+) (M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))", std::regex_constants::ECMAScript);
const std::regex rexp_jumping("Jumping from ([a-zA-Z0-9\\s\\-]+) to ([a-zA-Z0-9\\s\\-]+)", std::regex_constants::ECMAScript);
class LogFileError: public std::runtime_error {
public:
LogFileError() : runtime_error("Log file error") {}
const char * what () const throw ()
{
return "Error trying to access the log file";
}
};
class EveEvent {
public:
static const int e_none = 0;
static const int e_docking = 1;
static const int e_docked = 2;
static const int e_undocking = 3;
static const int e_jump = 4;
EveEvent();
EveEvent(const std::string system);
EveEvent(const std::string system, const std::string planet, const std::string moon, const std::string station, const int evt);
const std::string getSystem();
const std::string getPlanet();
const std::string getMoon();
const std::string getStation();
const int getEvent();
private:
std::string _system;
std::string _planet;
std::string _moon;
std::string _station;
int _event;
};
bool getCharFromLogFile(std::string logFile, std::string & charName);
/**
* Get a list of available characters, based on their appearance in EVE log files
* @return QStringList List of character names
*/
bool <API key>(std::string logFile, std::vector<std::string> & charNames);
EveEvent getEventFromLogLine(std::string logLine);
};
#endif |
// SuperTuxKart - a fun racing game with go-kart
// This program is free software; you can redistribute it and/or
// as published by the Free Software Foundation; either version 3
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
#include "post_processing.hpp"
#include "config/user_config.hpp"
#include "graphics/callbacks.hpp"
#include "graphics/camera.hpp"
#include "graphics/central_settings.hpp"
#include "graphics/glwrap.hpp"
#include "graphics/gl_headers.hpp"
#include "graphics/irr_driver.hpp"
#include "graphics/mlaa_areamap.hpp"
#include "graphics/shaders.hpp"
#include "graphics/shared_gpu_objects.hpp"
#include "graphics/stk_mesh_scene_node.hpp"
#include "graphics/weather.hpp"
#include "io/file_manager.hpp"
#include "karts/abstract_kart.hpp"
#include "karts/kart_model.hpp"
#include "modes/world.hpp"
#include "physics/physics.hpp"
#include "race/race_manager.hpp"
#include "tracks/track.hpp"
#include "utils/log.hpp"
#include "utils/profiler.hpp"
#include "utils/cpp2011.hpp"
#include <SViewFrustum.h>
using namespace video;
using namespace scene;
class <API key> : public TextureShader<<API key>, 1,
core::vector2df>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "gaussian3h.frag");
assignUniforms("pixel");
assignSamplerNames(0, "tex", <API key>);
} // <API key>
void render(const FrameBuffer &auxiliary, float inv_width,
float inv_height)
{
setTextureUnits(auxiliary.getRTT()[0]);
<API key>(core::vector2df(inv_width, inv_height));
} // render
}; // <API key>
class <API key> : public TextureShader<<API key>, 1,
core::vector2df,
std::vector<float> >
{
public:
GLuint m_dest_tu;
<API key>()
{
#if !defined(USE_GLES2)
loadProgram(OBJECT, GL_COMPUTE_SHADER, "blurshadowV.comp");
m_dest_tu = 1;
assignUniforms("pixel", "weights");
assignSamplerNames(0, "source", <API key>);
assignTextureUnit(m_dest_tu, "dest");
#endif
} // <API key>
}; // <API key>
class <API key> : public TextureShader<<API key>, 1,
core::vector2df, float>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "gaussian6v.frag");
assignUniforms("pixel", "sigma");
assignSamplerNames(0, "tex", <API key>);
} // <API key>
void render(GLuint layer_tex, int width, int height, float sigma_v)
{
setTextureUnits(layer_tex);
<API key>(core::vector2df(1.f / width, 1.f / height),
sigma_v);
} // render
}; // <API key>
class <API key> : public TextureShader<<API key>, 1,
core::vector2df>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "gaussian3v.frag");
assignUniforms("pixel");
assignSamplerNames(0, "tex", <API key>);
} // <API key>
void render(const FrameBuffer &in_fbo, float inv_width, float inv_height)
{
setTextureUnits(in_fbo.getRTT()[0]);
<API key>(core::vector2df(inv_width, inv_height));
} // render
}; // <API key>
#if !defined(USE_GLES2)
class <API key> : public TextureShader<<API key>, 1,
core::vector2df,
std::vector<float> >
{
public:
GLuint m_dest_tu;
<API key>()
{
loadProgram(OBJECT, GL_COMPUTE_SHADER, "gaussian6v.comp");
m_dest_tu = 1;
assignUniforms("pixel", "weights");
assignSamplerNames(0, "source", <API key>);
assignTextureUnit(m_dest_tu, "dest");
} // <API key>
}; // <API key>
class <API key> : public TextureShader<<API key>, 1,
core::vector2df,
std::vector<float> >
{
public:
GLuint m_dest_tu;
<API key>()
{
loadProgram(OBJECT, GL_COMPUTE_SHADER, "gaussian6h.comp");
m_dest_tu = 1;
assignUniforms("pixel", "weights");
assignSamplerNames(0, "source", <API key>);
assignTextureUnit(m_dest_tu, "dest");
} // <API key>
}; // <API key>
class <API key> : public TextureShader<<API key>, 1,
core::vector2df,
std::vector<float> >
{
public:
GLuint m_dest_tu;
<API key>()
{
loadProgram(OBJECT, GL_COMPUTE_SHADER, "blurshadowH.comp");
m_dest_tu = 1;
assignUniforms("pixel", "weights");
assignSamplerNames(0, "source", <API key>);
assignTextureUnit(m_dest_tu, "dest");
} // <API key>
}; // <API key>
#endif
class <API key> : public TextureShader<<API key>, 1,
core::vector2df, float>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "gaussian6h.frag");
assignUniforms("pixel", "sigma");
assignSamplerNames(0, "tex", <API key>);
} // <API key>
void render(const FrameBuffer &fb, int width, int height, float sigma_h)
{
setTextureUnits(fb.getRTT()[0]);
<API key>(
core::vector2df(1.f / width,
1.f / height),
sigma_h);
} // renderq
}; // <API key>
class <API key> : public TextureShader<<API key>, 2,
core::vector2df>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "bilateralH.frag");
assignUniforms("pixel");
assignSamplerNames(0, "tex", <API key>,
1, "depth", <API key>);
} // <API key>
void render(const FrameBuffer &fb, int width, int height)
{
setTextureUnits(fb.getRTT()[0],
irr_driver->getFBO(FBO_LINEAR_DEPTH).getRTT()[0] );
<API key>(core::vector2df(1.0f/width, 1.0f/height));
} // render
}; // <API key>
class <API key> : public TextureShader<<API key>, 2,
core::vector2df>
{
public:
GLuint m_dest_tu;
<API key>()
{
#if !defined(USE_GLES2)
loadProgram(OBJECT, GL_COMPUTE_SHADER, "bilateralH.comp");
m_dest_tu = 2;
assignUniforms("pixel");
assignSamplerNames(0, "source", <API key>,
1, "depth", <API key>);
assignTextureUnit(m_dest_tu, "dest");
#endif
} // <API key>
void render(const FrameBuffer &fb, const FrameBuffer &auxiliary,
int width, int height)
{
#if !defined(USE_GLES2)
use();
glBindSampler(m_dest_tu, 0);
setTextureUnits(fb.getRTT()[0],
irr_driver->getFBO(FBO_LINEAR_DEPTH).getRTT()[0]);
glBindImageTexture(m_dest_tu, auxiliary.getRTT()[0], 0, false,
0, GL_WRITE_ONLY, GL_R16F);
setUniforms(core::vector2df(1.0f/width, 1.0f/height));
glDispatchCompute((int)width / 8 + 1, (int)height / 8 + 1, 1);
#endif
} // render
}; // <API key>
class <API key> : public TextureShader<<API key>, 2,
core::vector2df>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "bilateralV.frag");
assignUniforms("pixel");
assignSamplerNames(0, "tex", <API key>,
1, "depth", <API key>);
} // <API key>
void render(const FrameBuffer &auxiliary, int width, int height)
{
setTextureUnits(auxiliary.getRTT()[0],
irr_driver->getFBO(FBO_LINEAR_DEPTH).getRTT()[0]);
<API key>(core::vector2df(1.0f/width, 1.0f/height));
} // render
}; // <API key>
class <API key> : public TextureShader<<API key>, 2,
core::vector2df>
{
public:
GLuint m_dest_tu;
<API key>()
{
#if !defined(USE_GLES2)
loadProgram(OBJECT, GL_COMPUTE_SHADER, "bilateralV.comp");
m_dest_tu = 2;
assignUniforms("pixel");
assignSamplerNames(0, "source", <API key>,
1, "depth", <API key>);
assignTextureUnit(m_dest_tu, "dest");
#endif
} // <API key>
void render(const FrameBuffer &auxiliary, const FrameBuffer &fb,
int width, int height)
{
#if !defined(USE_GLES2)
use();
glBindSampler(m_dest_tu, 0);
setTextureUnits(auxiliary.getRTT()[0],
irr_driver->getFBO(FBO_LINEAR_DEPTH).getRTT()[0]);
glBindImageTexture(m_dest_tu, fb.getRTT()[0], 0, false, 0,
GL_WRITE_ONLY, GL_R16F);
setUniforms(core::vector2df(1.0f/width, 1.0f/height));
glDispatchCompute((int)fb.getWidth() / 8 + 1,
(int)fb.getHeight() / 8 + 1, 1);
#endif
} // render
}; // <API key>
class BloomShader : public TextureShader<BloomShader, 1, float>
{
public:
BloomShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "bloom.frag");
assignUniforms("scale");
assignSamplerNames(0, "tex", ST_NEAREST_FILTERED);
} // BloomShader
void render(GLuint in)
{
BloomShader::getInstance()->setTextureUnits(in);
<API key>(UserConfigParams::m_scale_rtts_factor);
} // render
}; // BloomShader
static video::ITexture *lensDustTex = 0;
class BloomBlendShader : public TextureShader<BloomBlendShader, 4>
{
public:
BloomBlendShader()
{
if (!lensDustTex)
lensDustTex = irr_driver->getTexture(FileManager::TEXTURE, "gfx_lensDust_a.png");
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "bloomblend.frag");
assignUniforms();
assignSamplerNames(0, "tex_128", <API key>,
1, "tex_256", <API key>,
2, "tex_512", <API key>,
3, "tex_dust", <API key>);
} // BloomBlendShader
void render()
{
setTextureUnits(irr_driver-><API key>(RTT_BLOOM_128),
irr_driver-><API key>(RTT_BLOOM_256),
irr_driver-><API key>(RTT_BLOOM_512),
getTextureGLuint(lensDustTex));
<API key>();
} // render
}; // BloomBlendShader
class LensBlendShader : public TextureShader<LensBlendShader, 3>
{
public:
LensBlendShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "lensblend.frag");
assignUniforms();
assignSamplerNames(0, "tex_128", <API key>,
1, "tex_256", <API key>,
2, "tex_512", <API key>);
} // LensBlendShader
void render()
{
setTextureUnits(irr_driver-><API key>(RTT_LENS_128),
irr_driver-><API key>(RTT_LENS_256),
irr_driver-><API key>(RTT_LENS_512));
<API key>();
} // render
}; // LensBlendShader
class ToneMapShader : public TextureShader<ToneMapShader, 1, float>
{
public:
ToneMapShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "tonemap.frag");
assignUniforms("vignette_weight");
assignSamplerNames(0, "text", ST_NEAREST_FILTERED);
} // ToneMapShader
void render(const FrameBuffer &fbo, GLuint rtt, float vignette_weight)
{
fbo.bind();
setTextureUnits(rtt);
<API key>(vignette_weight);
} // render
}; // ToneMapShader
class DepthOfFieldShader : public TextureShader<DepthOfFieldShader, 2>
{
public:
DepthOfFieldShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "dof.frag");
assignUniforms();
assignSamplerNames(0, "tex", <API key>,
1, "dtex", ST_NEAREST_FILTERED);
} // DepthOfFieldShader
void render(const FrameBuffer &fb, GLuint rtt)
{
fb.bind();
setTextureUnits(rtt, irr_driver-><API key>());
<API key>();
} // render
}; // DepthOfFieldShader
class IBLShader : public TextureShader<IBLShader, 3>
{
public:
IBLShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "IBL.frag");
assignUniforms();
assignSamplerNames(0, "ntex", ST_NEAREST_FILTERED,
1, "dtex", ST_NEAREST_FILTERED,
2, "probe", <API key>);
} // IBLShader
}; // IBLShader
class DegradedIBLShader : public TextureShader<DegradedIBLShader, 1>
{
public:
DegradedIBLShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "degraded_ibl.frag");
assignUniforms();
assignSamplerNames(0, "ntex", ST_NEAREST_FILTERED);
} // DegradedIBLShader
}; // DegradedIBLShader
class RHDebug : public Shader<RHDebug, core::matrix4, core::vector3df>
{
public:
GLuint m_tu_shr, m_tu_shg, m_tu_shb;
RHDebug()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "rhdebug.vert",
GL_FRAGMENT_SHADER, "rhdebug.frag");
assignUniforms("rh_matrix", "extents");
m_tu_shr = 0;
m_tu_shg = 1;
m_tu_shb = 2;
assignTextureUnit(m_tu_shr, "SHR", m_tu_shg, "SHG",
m_tu_shb, "SHB");
} // RHDebug
}; // RHDebug
class <API key>
: public TextureShader<<API key>, 5,
core::matrix4, core::matrix4, core::vector3df >
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "gi.frag");
assignUniforms("rh_matrix", "inv_rh_matrix", "extents");
assignSamplerNames(0, "ntex", ST_NEAREST_FILTERED,
1, "dtex", ST_NEAREST_FILTERED,
2, "SHR", <API key>,
3, "SHG", <API key>,
4, "SHB", <API key>);
} // <API key>
void render(const core::matrix4 &rh_matrix,
const core::vector3df &rh_extend, const FrameBuffer &fb)
{
core::matrix4 inv_rh_matrix;
rh_matrix.getInverse(inv_rh_matrix);
glDisable(GL_DEPTH_TEST);
setTextureUnits(irr_driver-><API key>(<API key>),
irr_driver-><API key>(),
fb.getRTT()[0], fb.getRTT()[1], fb.getRTT()[2]);
<API key>(rh_matrix, inv_rh_matrix, rh_extend);
} // render
}; // <API key>
class PassThroughShader : public TextureShader<PassThroughShader, 1, int, int>
{
public:
PassThroughShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "passthrough.frag");
assignUniforms("width", "height");
assignSamplerNames(0, "tex", <API key>);
} // PassThroughShader
void render(GLuint tex, unsigned width, unsigned height)
{
PassThroughShader::getInstance()->setTextureUnits(tex);
<API key>(width, height);
} // render
}; // PassThroughShader
class <API key> : public Shader<<API key>, int>
{
private:
GLuint m_tu_texture;
GLuint m_vao;
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "layertexturequad.frag");
m_tu_texture = 0;
assignUniforms("layer");
assignTextureUnit(m_tu_texture, "tex");
m_vao = createVAO();
} // <API key>
void bindVertexArray()
{
glBindVertexArray(m_vao);
} // bindVertexArray
void activateTexture()
{
glActiveTexture(GL_TEXTURE0 + m_tu_texture);
} // activateTexture
}; // <API key>
class <API key> : public TextureShader<<API key>, 1,
float, float>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "linearizedepth.frag");
assignUniforms("zn", "zf");
assignSamplerNames(0, "texture", <API key>);
} // <API key>
void render()
{
setTextureUnits(irr_driver-><API key>());
scene::ICameraSceneNode *c = irr_driver->getSceneManager()->getActiveCamera();
<API key>(c->getNearValue(), c->getFarValue() );
} // render
}; // <API key>
class GlowShader : public TextureShader < GlowShader, 1 >
{
private:
GLuint m_vao;
public:
GlowShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "glow.frag");
assignUniforms();
assignSamplerNames(0, "tex", <API key>);
m_vao = createVAO();
} // GlowShader
void render(unsigned tex)
{
use();
glBindVertexArray(m_vao);
setTextureUnits(tex);
setUniforms();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
} // render
}; // GlowShader
class SSAOShader : public TextureShader<SSAOShader, 1, float, float, float>
{
public:
SSAOShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "ssao.frag");
assignUniforms("radius", "k", "sigma");
assignSamplerNames(0, "dtex", ST_SEMI_TRILINEAR);
} // SSAOShader
void render()
{
setTextureUnits(irr_driver-><API key>(RTT_LINEAR_DEPTH));
glGenerateMipmap(GL_TEXTURE_2D);
<API key>(irr_driver->getSSAORadius(),
irr_driver->getSSAOK(),
irr_driver->getSSAOSigma());
} // render
}; // SSAOShader
class MotionBlurShader : public TextureShader<MotionBlurShader, 2,
core::matrix4, core::vector2df,
float, float>
{
public:
MotionBlurShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "motion_blur.frag");
assignUniforms("previous_viewproj", "center", "boost_amount",
"mask_radius");
assignSamplerNames(0, "color_buffer", <API key>,
1, "dtex", ST_NEAREST_FILTERED);
} // MotionBlurShader
void render(const FrameBuffer &fb, float boost_time)
{
setTextureUnits(fb.getRTT()[0], irr_driver-><API key>());
Camera *cam = Camera::getActiveCamera();
// Todo : use a previousPVMatrix per cam, not global
<API key>(cam->getPreviousPVMatrix(),
core::vector2df(0.5, 0.5),
boost_time, // Todo : should be framerate dependent=
0.15f);
} // render
}; // MotionBlurShader
class GodFadeShader : public TextureShader<GodFadeShader, 1, video::SColorf>
{
public:
GodFadeShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "godfade.frag");
assignUniforms("col");
assignSamplerNames(0, "tex", <API key>);
} // GodFadeShader
void render(GLuint tex, const SColor &col)
{
setTextureUnits(tex);
<API key>(col);
} // render
}; // GodFadeShader
class GodRayShader : public TextureShader<GodRayShader, 1, core::vector2df>
{
public:
GodRayShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "godray.frag");
assignUniforms("sunpos");
assignSamplerNames(0, "tex", <API key>);
} // GodRayShader
void render(GLuint tex, const core::vector2df &sunpos)
{
setTextureUnits(tex);
<API key>(sunpos);
} // render
}; // GodRayShader
class <API key>
: public TextureShader<<API key>, 1, core::vector2df>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "mlaa_color1.frag");
assignUniforms("PIXEL_SIZE");
assignSamplerNames(0, "colorMapG", ST_NEAREST_FILTERED);
} // <API key>
void render(const core::vector2df &pixel_size)
{
use();
setTextureUnits(irr_driver-><API key>(RTT_MLAA_COLORS));
<API key>(pixel_size);
} // render
}; // <API key>
class <API key> : public TextureShader<<API key>,
2, core::vector2df>
{
public:
<API key>()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "mlaa_blend2.frag");
assignUniforms("PIXEL_SIZE");
assignSamplerNames(0, "edgesMap", <API key>,
1, "areaMap", ST_NEAREST_FILTERED);
} // <API key>
void render(video::ITexture *area_map, const core::vector2df &pixel_size)
{
use();
setTextureUnits(irr_driver-><API key>(RTT_MLAA_TMP),
getTextureGLuint(area_map));
<API key>(pixel_size);
} // render
}; // <API key>
class MLAAGatherSHader : public TextureShader<MLAAGatherSHader, 2,
core::vector2df>
{
public:
MLAAGatherSHader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "mlaa_neigh3.frag");
assignUniforms("PIXEL_SIZE");
assignSamplerNames(0, "blendMap", ST_NEAREST_FILTERED,
1, "colorMap", ST_NEAREST_FILTERED);
} // MLAAGatherSHader
void render(const core::vector2df &pixel_size)
{
use();
setTextureUnits(irr_driver-><API key>(RTT_MLAA_BLEND),
irr_driver-><API key>(RTT_MLAA_TMP));
<API key>(pixel_size);
} // render
}; // MLAAGatherSHader
class SunLightShader : public TextureShader<SunLightShader, 2,
core::vector3df, video::SColorf>
{
public:
SunLightShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "sunlight.frag");
assignSamplerNames(0, "ntex", ST_NEAREST_FILTERED,
1, "dtex", ST_NEAREST_FILTERED);
assignUniforms("direction", "col");
} // SunLightShader
void render(const core::vector3df &direction, const video::SColorf &col)
{
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glBlendFunc(GL_ONE, GL_ONE);
glBlendEquation(GL_FUNC_ADD);
setTextureUnits(irr_driver-><API key>(<API key>),
irr_driver-><API key>());
<API key>(direction, col);
} // render
}; // SunLightShader
class LightningShader : public TextureShader<LightningShader, 1,
core::vector3df>
{
public:
LightningShader()
{
loadProgram(OBJECT, GL_VERTEX_SHADER, "screenquad.vert",
GL_FRAGMENT_SHADER, "lightning.frag");
assignUniforms("intensity");
} // LightningShader
void render(core::vector3df intensity)
{
<API key>(intensity);
} // render
}; // LightningShader
PostProcessing::PostProcessing(IVideoDriver* video_driver)
{
// Initialization
m_material.Wireframe = false;
m_material.Lighting = false;
m_material.ZWriteEnable = false;
m_material.ZBuffer = ECFN_ALWAYS;
m_material.setFlag(<API key>, true);
for (u32 i = 0; i < <API key>; ++i)
{
m_material.TextureLayer[i].TextureWrapU =
m_material.TextureLayer[i].TextureWrapV = ETC_CLAMP_TO_EDGE;
}
// Load the MLAA area map
io::IReadFile *areamap = irr_driver->getDevice()->getFileSystem()->
<API key>((void *) AreaMap33, sizeof(AreaMap33),
"AreaMap33", false);
if (!areamap)
{
Log::fatal("postprocessing", "Failed to load the areamap");
return;
}
m_areamap = irr_driver->getVideoDriver()->getTexture(areamap);
areamap->drop();
} // PostProcessing
PostProcessing::~PostProcessing()
{
// TODO: do we have to delete/drop anything?
} // ~PostProcessing
/** Initialises post processing at the (re-)start of a race. This sets up
* the vertices, normals and texture coordinates for each
*/
void PostProcessing::reset()
{
const u32 n = Camera::getNumCameras();
m_boost_time.resize(n);
m_vertices.resize(n);
m_center.resize(n);
m_direction.resize(n);
MotionBlurProvider * const cb =
(MotionBlurProvider *) Shaders::getCallback(ES_MOTIONBLUR);
for(unsigned int i=0; i<n; i++)
{
m_boost_time[i] = 0.0f;
const core::recti &vp = Camera::getCamera(i)->getViewport();
// Map viewport to [-1,1] x [-1,1]. First define the coordinates
// left, right, top, bottom:
float right = vp.LowerRightCorner.X < (int)irr_driver->getActualScreenSize().Width
? 0.0f : 1.0f;
float left = vp.UpperLeftCorner.X > 0.0f ? 0.0f : -1.0f;
float top = vp.UpperLeftCorner.Y > 0.0f ? 0.0f : 1.0f;
float bottom = vp.LowerRightCorner.Y < (int)irr_driver->getActualScreenSize().Height
? 0.0f : -1.0f;
// Use left etc to define 4 vertices on which the rendered screen
// will be displayed:
m_vertices[i].v0.Pos = core::vector3df(left, bottom, 0);
m_vertices[i].v1.Pos = core::vector3df(left, top, 0);
m_vertices[i].v2.Pos = core::vector3df(right, top, 0);
m_vertices[i].v3.Pos = core::vector3df(right, bottom, 0);
// Define the texture coordinates of each vertex, which must
// be in [0,1]x[0,1]
m_vertices[i].v0.TCoords = core::vector2df(left ==-1.0f ? 0.0f : 0.5f,
bottom==-1.0f ? 0.0f : 0.5f);
m_vertices[i].v1.TCoords = core::vector2df(left ==-1.0f ? 0.0f : 0.5f,
top == 1.0f ? 1.0f : 0.5f);
m_vertices[i].v2.TCoords = core::vector2df(right == 0.0f ? 0.5f : 1.0f,
top == 1.0f ? 1.0f : 0.5f);
m_vertices[i].v3.TCoords = core::vector2df(right == 0.0f ? 0.5f : 1.0f,
bottom==-1.0f ? 0.0f : 0.5f);
// Set normal and color:
core::vector3df normal(0,0,1);
m_vertices[i].v0.Normal = m_vertices[i].v1.Normal =
m_vertices[i].v2.Normal = m_vertices[i].v3.Normal = normal;
SColor white(0xFF, 0xFF, 0xFF, 0xFF);
m_vertices[i].v0.Color = m_vertices[i].v1.Color =
m_vertices[i].v2.Color = m_vertices[i].v3.Color = white;
m_center[i].X=(m_vertices[i].v0.TCoords.X
+m_vertices[i].v2.TCoords.X) * 0.5f;
// Center is around 20 percent from bottom of screen:
const float tex_height = m_vertices[i].v1.TCoords.Y
- m_vertices[i].v0.TCoords.Y;
m_direction[i].X = m_center[i].X;
m_direction[i].Y = m_vertices[i].v0.TCoords.Y + 0.7f*tex_height;
<API key>(i, 0.2f);
cb->setDirection(i, m_direction[i].X, m_direction[i].Y);
cb->setMaxHeight(i, m_vertices[i].v1.TCoords.Y);
} // for i <number of cameras
} // reset
void PostProcessing::<API key>(const u32 num, const float y)
{
MotionBlurProvider * const cb =
(MotionBlurProvider *) Shaders::getCallback(ES_MOTIONBLUR);
const float tex_height =
m_vertices[num].v1.TCoords.Y - m_vertices[num].v0.TCoords.Y;
m_center[num].Y = m_vertices[num].v0.TCoords.Y + y * tex_height;
cb->setCenter(num, m_center[num].X, m_center[num].Y);
} // <API key>
/** Setup some PP data.
*/
void PostProcessing::begin()
{
m_any_boost = false;
for (u32 i = 0; i < m_boost_time.size(); i++)
m_any_boost |= m_boost_time[i] > 0.01f;
} // begin
/** Set the boost amount according to the speed of the camera */
void PostProcessing::giveBoost(unsigned int camera_index)
{
if (CVS->isGLSL())
{
m_boost_time[camera_index] = 0.75f;
MotionBlurProvider * const cb =
(MotionBlurProvider *)Shaders::getCallback(ES_MOTIONBLUR);
cb->setBoostTime(camera_index, m_boost_time[camera_index]);
}
} // giveBoost
/** Updates the boost times for all cameras, called once per frame.
* \param dt Time step size.
*/
void PostProcessing::update(float dt)
{
if (!CVS->isGLSL())
return;
MotionBlurProvider* const cb =
(MotionBlurProvider*) Shaders::getCallback(ES_MOTIONBLUR);
if (cb == NULL) return;
for (unsigned int i=0; i<m_boost_time.size(); i++)
{
if (m_boost_time[i] > 0.0f)
{
m_boost_time[i] -= dt;
if (m_boost_time[i] < 0.0f) m_boost_time[i] = 0.0f;
}
cb->setBoostTime(i, m_boost_time[i]);
}
} // update
static void renderBloom(GLuint in)
{
BloomShader::getInstance()->render(in);
} // renderBloom
void PostProcessing::renderEnvMap(GLuint skybox)
{
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);
if (UserConfigParams::m_degraded_IBL)
{
DegradedIBLShader::getInstance()->use();
glBindVertexArray(SharedGPUObjects::<API key>());
DegradedIBLShader::getInstance()
->setTextureUnits(irr_driver
-><API key>(<API key>));
DegradedIBLShader::getInstance()->setUniforms();
}
else
{
IBLShader::getInstance()->use();
glBindVertexArray(SharedGPUObjects::<API key>());
IBLShader::getInstance()->setTextureUnits(
irr_driver-><API key>(<API key>),
irr_driver-><API key>(), skybox);
IBLShader::getInstance()->setUniforms();
}
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(<API key>, 0);
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
} // renderEnvMap
void PostProcessing::renderRHDebug(unsigned SHR, unsigned SHG, unsigned SHB,
const core::matrix4 &rh_matrix,
const core::vector3df &rh_extend)
{
#if !defined(USE_GLES2)
glEnable(<API key>);
RHDebug::getInstance()->use();
glActiveTexture(GL_TEXTURE0 + RHDebug::getInstance()->m_tu_shr);
glBindTexture(GL_TEXTURE_3D, SHR);
glActiveTexture(GL_TEXTURE0 + RHDebug::getInstance()->m_tu_shg);
glBindTexture(GL_TEXTURE_3D, SHG);
glActiveTexture(GL_TEXTURE0 + RHDebug::getInstance()->m_tu_shb);
glBindTexture(GL_TEXTURE_3D, SHB);
RHDebug::getInstance()->setUniforms(rh_matrix, rh_extend);
glDrawArrays(GL_POINTS, 0, 32 * 16 * 32);
glDisable(<API key>);
#endif
} // renderRHDebug
void PostProcessing::renderGI(const core::matrix4 &rh_matrix,
const core::vector3df &rh_extend,
const FrameBuffer &fb)
{
<API key>::getInstance()->render(rh_matrix,
rh_extend,
fb);
} // renderGI
void PostProcessing::renderSunlight(const core::vector3df &direction,
const video::SColorf &col)
{
SunLightShader::getInstance()->render(direction, col);
} // renderSunlight
static std::vector<float> getGaussianWeight(float sigma, size_t count)
{
float g0, g1, g2, total;
std::vector<float> weights;
g0 = 1.f / (sqrtf(2.f * 3.14f) * sigma);
g1 = exp(-.5f / (sigma * sigma));
g2 = g1 * g1;
total = g0;
for (unsigned i = 0; i < count; i++)
{
weights.push_back(g0);
g0 *= g1;
g1 *= g2;
total += 2 * g0;
}
for (float &weight : weights)
weight /= total;
return weights;
} // getGaussianWeight
void PostProcessing::renderGaussian3Blur(const FrameBuffer &in_fbo,
const FrameBuffer &auxiliary)
{
assert(in_fbo.getWidth() == auxiliary.getWidth() &&
in_fbo.getHeight() == auxiliary.getHeight());
float inv_width = 1.0f / in_fbo.getWidth();
float inv_height = 1.0f / in_fbo.getHeight();
{
auxiliary.bind();
<API key>::getInstance()->render(in_fbo, inv_width,
inv_height);
}
{
in_fbo.bind();
<API key>::getInstance()->render(auxiliary, inv_width,
inv_height);
}
} // renderGaussian3Blur
void PostProcessing::<API key>(FrameBuffer &in_fbo,
size_t layer, float sigma_h,
float sigma_v)
{
#if !defined(USE_GLES2)
GLuint layer_tex;
glGenTextures(1, &layer_tex);
glTextureView(layer_tex, GL_TEXTURE_2D, in_fbo.getRTT()[0],
GL_R32F, 0, 1, layer, 1);
if (!CVS-><API key>())
{
// Used as temp
irr_driver->getFBO(FBO_SCALAR_1024).bind();
<API key>::getInstance()
->render(layer_tex, UserConfigParams::<API key>,
UserConfigParams::<API key>, sigma_v);
in_fbo.bindLayer(layer);
<API key>::getInstance()
->render(irr_driver->getFBO(FBO_SCALAR_1024),
UserConfigParams::<API key>,
UserConfigParams::<API key>, sigma_h);
}
else
{
const std::vector<float> &weightsV = getGaussianWeight(sigma_v, 7);
glMemoryBarrier(<API key>);
<API key>::getInstance()->use();
<API key>::getInstance()->setTextureUnits(layer_tex);
glBindSampler(<API key>::getInstance()->m_dest_tu, 0);
glBindImageTexture(<API key>::getInstance()->m_dest_tu,
irr_driver->getFBO(FBO_SCALAR_1024).getRTT()[0], 0,
false, 0, GL_WRITE_ONLY, GL_R32F);
<API key>::getInstance()->setUniforms
(core::vector2df(1.f / UserConfigParams::<API key>,
1.f / UserConfigParams::<API key>),
weightsV);
glDispatchCompute((int)UserConfigParams::<API key> / 8 + 1,
(int)UserConfigParams::<API key> / 8 + 1, 1);
const std::vector<float> &weightsH = getGaussianWeight(sigma_h, 7);
glMemoryBarrier( <API key>
| <API key>);
<API key>::getInstance()->use();
<API key>::getInstance()
->setTextureUnits(irr_driver->getFBO(FBO_SCALAR_1024).getRTT()[0]);
glBindSampler(<API key>::getInstance()->m_dest_tu, 0);
glBindImageTexture(<API key>::getInstance()->m_dest_tu,
layer_tex, 0, false, 0, GL_WRITE_ONLY, GL_R32F);
<API key>::getInstance()->setUniforms
(core::vector2df(1.f / UserConfigParams::<API key>,
1.f / UserConfigParams::<API key>),
weightsH);
glDispatchCompute((int)UserConfigParams::<API key> / 8 + 1,
(int)UserConfigParams::<API key> / 8 + 1, 1);
glMemoryBarrier(<API key>);
}
glDeleteTextures(1, &layer_tex);
#endif
} // <API key>
void PostProcessing::renderGaussian6Blur(const FrameBuffer &in_fbo,
const FrameBuffer &auxiliary, float sigma_v,
float sigma_h)
{
assert(in_fbo.getWidth() == auxiliary.getWidth() &&
in_fbo.getHeight() == auxiliary.getHeight());
float inv_width = 1.0f / in_fbo.getWidth();
float inv_height = 1.0f / in_fbo.getHeight();
if (!CVS-><API key>())
{
auxiliary.bind();
<API key>::getInstance()
->render(in_fbo.getRTT()[0], in_fbo.getWidth(), in_fbo.getWidth(),
sigma_v);
in_fbo.bind();
<API key>::getInstance()->setTextureUnits(auxiliary.getRTT()[0]);
<API key>::getInstance()->render(auxiliary, in_fbo.getWidth(),
in_fbo.getHeight(), sigma_h);
}
#if !defined(USE_GLES2)
else
{
const std::vector<float> &weightsV = getGaussianWeight(sigma_v, 7);
glMemoryBarrier(<API key>);
<API key>::getInstance()->use();
<API key>::getInstance()
->setTextureUnits(in_fbo.getRTT()[0]);
glBindSampler(<API key>::getInstance()->m_dest_tu, 0);
glBindImageTexture(<API key>::getInstance()->m_dest_tu,
auxiliary.getRTT()[0], 0, false, 0,
GL_WRITE_ONLY, GL_RGBA16F);
<API key>::getInstance()
->setUniforms(core::vector2df(inv_width, inv_height), weightsV);
glDispatchCompute((int)in_fbo.getWidth() / 8 + 1,
(int)in_fbo.getHeight() / 8 + 1, 1);
const std::vector<float> &weightsH = getGaussianWeight(sigma_h, 7);
glMemoryBarrier( <API key>
| <API key>);
<API key>::getInstance()->use();
<API key>::getInstance()
->setTextureUnits(auxiliary.getRTT()[0]);
glBindSampler(<API key>::getInstance()->m_dest_tu, 0);
glBindImageTexture(<API key>::getInstance()->m_dest_tu,
in_fbo.getRTT()[0], 0, false, 0,
GL_WRITE_ONLY, GL_RGBA16F);
<API key>::getInstance()
->setUniforms(core::vector2df(inv_width, inv_height), weightsH);
glDispatchCompute((int)in_fbo.getWidth() / 8 + 1,
(int)in_fbo.getHeight() / 8 + 1, 1);
glMemoryBarrier(<API key>);
}
#endif
} // renderGaussian6Blur
void PostProcessing::<API key>(const FrameBuffer &in_fbo,
const FrameBuffer &auxiliary)
{
assert(in_fbo.getWidth() == auxiliary.getWidth() &&
in_fbo.getHeight() == auxiliary.getHeight());
auxiliary.bind();
<API key>::getInstance()->render(in_fbo, in_fbo.getWidth(),
in_fbo.getHeight(), 2.0f );
in_fbo.bind();
<API key>::getInstance()->render(auxiliary, in_fbo.getWidth(),
in_fbo.getHeight(), 2.0f);
} // <API key>
void PostProcessing::<API key>(const FrameBuffer &in_fbo,
const FrameBuffer &auxiliary)
{
assert(in_fbo.getWidth() == auxiliary.getWidth() &&
in_fbo.getHeight() == auxiliary.getHeight());
#if !defined(USE_GLES2)
if (CVS-><API key>())
glMemoryBarrier(<API key>);
#endif
{
if (!CVS-><API key>())
{
auxiliary.bind();
<API key>::getInstance()->render(in_fbo,
in_fbo.getWidth(),
in_fbo.getHeight());
}
else
{
<API key>::getInstance()->render(in_fbo,
auxiliary,
in_fbo.getWidth(),
in_fbo.getHeight());
}
}
#if !defined(USE_GLES2)
if (CVS-><API key>())
glMemoryBarrier(<API key>);
#endif
{
if (!CVS-><API key>())
{
in_fbo.bind();
<API key>::getInstance()->render(auxiliary,
in_fbo.getWidth(),
in_fbo.getHeight());
}
else
{
<API key>::getInstance()->render(auxiliary,
in_fbo,
in_fbo.getWidth(),
in_fbo.getHeight());
}
}
#if !defined(USE_GLES2)
if (CVS-><API key>())
glMemoryBarrier(<API key>);
#endif
} // <API key>
void PostProcessing::renderPassThrough(GLuint tex, unsigned width,
unsigned height)
{
PassThroughShader::getInstance()->render(tex, width, height);
} // renderPassThrough
void PostProcessing::renderTextureLayer(unsigned tex, unsigned layer)
{
<API key>::getInstance()->use();
<API key>::getInstance()->bindVertexArray();
<API key>::getInstance()->activateTexture();
glBindTexture(GL_TEXTURE_2D_ARRAY, tex);
glTexParameteri(GL_TEXTURE_2D_ARRAY, <API key>, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, <API key>, GL_LINEAR);
<API key>::getInstance()->setUniforms(layer);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
} // renderTextureLayer
void PostProcessing::renderGlow(unsigned tex)
{
GlowShader::getInstance()->render(tex);
} // renderGlow
void PostProcessing::renderSSAO()
{
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
// Generate linear depth buffer
irr_driver->getFBO(FBO_LINEAR_DEPTH).bind();
<API key>::getInstance()->render();
irr_driver->getFBO(FBO_SSAO).bind();
SSAOShader::getInstance()->render();
} // renderSSAO
void PostProcessing::renderMotionBlur(unsigned , const FrameBuffer &in_fbo,
FrameBuffer &out_fbo)
{
MotionBlurProvider * const cb =
(MotionBlurProvider *)Shaders::getCallback(ES_MOTIONBLUR);
Camera *cam = Camera::getActiveCamera();
unsigned camID = cam->getIndex();
scene::ICameraSceneNode * const camnode = cam->getCameraSceneNode();
// Calculate the kart's Y position on screen
if (cam->getKart())
{
const core::vector3df pos = cam->getKart()->getNode()->getPosition();
float ndc[4];
core::matrix4 trans = camnode->getProjectionMatrix();
trans *= camnode->getViewMatrix();
trans.transformVect(ndc, pos);
const float karty = (ndc[1] / ndc[3]) * 0.5f + 0.5f;
<API key>(camID, karty);
}
else
<API key>(camID, 0.5f);
out_fbo.bind();
glClear(GL_COLOR_BUFFER_BIT);
float boost_time = cb->getBoostTime(cam->getIndex()) * 10;
MotionBlurShader::getInstance()->render(in_fbo, boost_time);
} // renderMotionBlur
static void renderDoF(const FrameBuffer &fbo, GLuint rtt)
{
DepthOfFieldShader::getInstance()->render(fbo, rtt);
} // renderDoF
void PostProcessing::applyMLAA()
{
const core::vector2df &PIXEL_SIZE =
core::vector2df(1.0f / UserConfigParams::m_width,
1.0f / UserConfigParams::m_height);
irr_driver->getFBO(FBO_MLAA_TMP).bind();
glEnable(GL_STENCIL_TEST);
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(<API key> | GL_COLOR_BUFFER_BIT);
glStencilFunc(GL_ALWAYS, 1, ~0);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
// Pass 1: color edge detection
<API key>::getInstance()->render(PIXEL_SIZE);
glStencilFunc(GL_EQUAL, 1, ~0);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// Pass 2: blend weights
irr_driver->getFBO(FBO_MLAA_BLEND).bind();
glClear(GL_COLOR_BUFFER_BIT);
<API key>::getInstance()->render(m_areamap, PIXEL_SIZE);
// Blit in to tmp1
FrameBuffer::Blit(irr_driver->getFBO(FBO_MLAA_COLORS),
irr_driver->getFBO(FBO_MLAA_TMP));
// Pass 3: gather
irr_driver->getFBO(FBO_MLAA_COLORS).bind();
MLAAGatherSHader::getInstance()->render(PIXEL_SIZE);
// Done.
glDisable(GL_STENCIL_TEST);
} // applyMLAA
void PostProcessing::renderLightning(core::vector3df intensity)
{
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glBlendEquation(GL_FUNC_ADD);
LightningShader::getInstance()->render(intensity);
glDisable(GL_BLEND);
}
/** Render the post-processed scene */
FrameBuffer *PostProcessing::render(scene::ICameraSceneNode * const camnode,
bool isRace)
{
FrameBuffer *in_fbo = &irr_driver->getFBO(FBO_COLORS);
FrameBuffer *out_fbo = &irr_driver->getFBO(FBO_TMP1_WITH_DS);
// Each effect uses these as named, and sets them up for the next effect.
// This allows chaining effects where some may be disabled.
// As the original color shouldn't be touched, the first effect
// can't be disabled.
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
World *world = World::getWorld();
Physics *physics = world ? world->getPhysics() : NULL;
if (isRace && UserConfigParams::m_dof && (physics == NULL || !physics->isDebug()))
{
<API key>("- DoF", 0xFF, 0x00, 0x00);
ScopedGPUTimer Timer(irr_driver->getGPUTimer(Q_DOF));
renderDoF(*out_fbo, in_fbo->getRTT()[0]);
std::swap(in_fbo, out_fbo);
<API key>();
}
{
<API key>("- Godrays", 0xFF, 0x00, 0x00);
ScopedGPUTimer Timer(irr_driver->getGPUTimer(Q_GODRAYS));
bool hasgodrays = false;
if (World::getWorld() != NULL)
hasgodrays = World::getWorld()->getTrack()->hasGodRays();
if (isRace && UserConfigParams::m_light_shaft && hasgodrays)
{
Track* track = World::getWorld()->getTrack();
glEnable(GL_DEPTH_TEST);
// Grab the sky
out_fbo->bind();
glClear(GL_COLOR_BUFFER_BIT);
// irr_driver->renderSkybox(camnode);
// Set the sun's color
const SColor col = track->getGodRaysColor();
// The sun interposer
STKMeshSceneNode *sun = irr_driver->getSunInterposer();
sun->setGlowColors(col);
sun->setPosition(track->getGodRaysPosition());
sun-><API key>();
irr_driver->setPhase(GLOW_PASS);
sun->render();
glDisable(GL_DEPTH_TEST);
// Fade to quarter
irr_driver->getFBO(FBO_QUARTER1).bind();
glViewport(0, 0, irr_driver->getActualScreenSize().Width / 4,
irr_driver->getActualScreenSize().Height / 4);
GodFadeShader::getInstance()->render(out_fbo->getRTT()[0], col);
// Blur
renderGaussian3Blur(irr_driver->getFBO(FBO_QUARTER1),
irr_driver->getFBO(FBO_QUARTER2));
// Calculate the sun's position in texcoords
const core::vector3df pos = track->getGodRaysPosition();
float ndc[4];
core::matrix4 trans = camnode->getProjectionMatrix();
trans *= camnode->getViewMatrix();
trans.transformVect(ndc, pos);
const float texh =
m_vertices[0].v1.TCoords.Y - m_vertices[0].v0.TCoords.Y;
const float texw =
m_vertices[0].v3.TCoords.X - m_vertices[0].v0.TCoords.X;
const float sunx = ((ndc[0] / ndc[3]) * 0.5f + 0.5f) * texw;
const float suny = ((ndc[1] / ndc[3]) * 0.5f + 0.5f) * texh;
// Rays please
irr_driver->getFBO(FBO_QUARTER2).bind();
GodRayShader::getInstance()
->render(irr_driver-><API key>(RTT_QUARTER1),
core::vector2df(sunx, suny) );
// Blur
renderGaussian3Blur(irr_driver->getFBO(FBO_QUARTER2),
irr_driver->getFBO(FBO_QUARTER1));
// Blend
glEnable(GL_BLEND);
glBlendColor(0., 0., 0., track->getGodRaysOpacity());
glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE);
glBlendEquation(GL_FUNC_ADD);
in_fbo->bind();
renderPassThrough(irr_driver-><API key>(RTT_QUARTER2),
in_fbo->getWidth(), in_fbo->getHeight());
glDisable(GL_BLEND);
}
<API key>();
}
// Simulate camera defects from there
{
<API key>("- Bloom", 0xFF, 0x00, 0x00);
ScopedGPUTimer Timer(irr_driver->getGPUTimer(Q_BLOOM));
if (isRace && UserConfigParams::m_bloom && (physics == NULL || !physics->isDebug()))
{
glClear(<API key>);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
FrameBuffer::Blit(*in_fbo, irr_driver->getFBO(FBO_BLOOM_1024),
GL_COLOR_BUFFER_BIT, GL_LINEAR);
irr_driver->getFBO(FBO_BLOOM_512).bind();
renderBloom(irr_driver-><API key>(RTT_BLOOM_1024));
// Downsample
FrameBuffer::Blit(irr_driver->getFBO(FBO_BLOOM_512),
irr_driver->getFBO(FBO_BLOOM_256),
GL_COLOR_BUFFER_BIT, GL_LINEAR);
FrameBuffer::Blit(irr_driver->getFBO(FBO_BLOOM_256),
irr_driver->getFBO(FBO_BLOOM_128),
GL_COLOR_BUFFER_BIT, GL_LINEAR);
// Copy for lens flare
FrameBuffer::Blit(irr_driver->getFBO(FBO_BLOOM_512),
irr_driver->getFBO(FBO_LENS_512),
GL_COLOR_BUFFER_BIT, GL_LINEAR);
FrameBuffer::Blit(irr_driver->getFBO(FBO_BLOOM_256),
irr_driver->getFBO(FBO_LENS_256),
GL_COLOR_BUFFER_BIT, GL_LINEAR);
FrameBuffer::Blit(irr_driver->getFBO(FBO_BLOOM_128),
irr_driver->getFBO(FBO_LENS_128),
GL_COLOR_BUFFER_BIT, GL_LINEAR);
// Blur
renderGaussian6Blur(irr_driver->getFBO(FBO_BLOOM_512),
irr_driver->getFBO(FBO_TMP_512), 1., 1.);
renderGaussian6Blur(irr_driver->getFBO(FBO_BLOOM_256),
irr_driver->getFBO(FBO_TMP_256), 1., 1.);
renderGaussian6Blur(irr_driver->getFBO(FBO_BLOOM_128),
irr_driver->getFBO(FBO_TMP_128), 1., 1.);
<API key>(irr_driver->getFBO(FBO_LENS_512),
irr_driver->getFBO(FBO_TMP_512));
<API key>(irr_driver->getFBO(FBO_LENS_256),
irr_driver->getFBO(FBO_TMP_256));
<API key>(irr_driver->getFBO(FBO_LENS_128),
irr_driver->getFBO(FBO_TMP_128));
// Additively blend on top of tmp1
in_fbo->bind();
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glBlendEquation(GL_FUNC_ADD);
BloomBlendShader::getInstance()->render();
LensBlendShader::getInstance()->render();
glDisable(GL_BLEND);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
} // end if bloom
<API key>();
}
//computeLogLuminance(in_rtt);
{
<API key>("- Tonemap", 0xFF, 0x00, 0x00);
ScopedGPUTimer Timer(irr_driver->getGPUTimer(Q_TONEMAP));
// only enable vignette during race
ToneMapShader::getInstance()->render(*out_fbo, in_fbo->getRTT()[0],
isRace ? 1.0f : 0.0f);
std::swap(in_fbo, out_fbo);
<API key>();
}
{
<API key>("- Motion blur", 0xFF, 0x00, 0x00);
ScopedGPUTimer Timer(irr_driver->getGPUTimer(Q_MOTIONBLUR));
MotionBlurProvider * const cb =
(MotionBlurProvider *)Shaders::getCallback(ES_MOTIONBLUR);
if (isRace && UserConfigParams::m_motionblur && World::getWorld() &&
cb->getBoostTime(Camera::getActiveCamera()->getIndex()) > 0.) // motion blur
{
renderMotionBlur(0, *in_fbo, *out_fbo);
std::swap(in_fbo, out_fbo);
}
<API key>();
}
// Handle lightning rendering
{
<API key>("- Lightning", 0xFF, 0x00, 0x00);
ScopedGPUTimer Timer(irr_driver->getGPUTimer(Q_LIGHTNING));
if (World::getWorld() != NULL)
{
Weather* m_weather = World::getWorld()->getWeather();
if (m_weather != NULL && m_weather->shouldLightning())
{
renderLightning(m_weather->getIntensity());
}
}
<API key>();
}
// Workaround a bug with srgb fbo on sandy bridge windows
if (!CVS-><API key>())
return in_fbo;
glEnable(GL_FRAMEBUFFER_SRGB);
irr_driver->getFBO(FBO_MLAA_COLORS).bind();
renderPassThrough(in_fbo->getRTT()[0],
irr_driver->getFBO(FBO_MLAA_COLORS).getWidth(),
irr_driver->getFBO(FBO_MLAA_COLORS).getHeight());
out_fbo = &irr_driver->getFBO(FBO_MLAA_COLORS);
if (UserConfigParams::m_mlaa) // MLAA. Must be the last pp filter.
{
<API key>("- MLAA", 0xFF, 0x00, 0x00);
ScopedGPUTimer Timer(irr_driver->getGPUTimer(Q_MLAA));
applyMLAA();
<API key>();
}
glDisable(GL_FRAMEBUFFER_SRGB);
return out_fbo;
} // render |
package com.yc.sy.mapper;
import java.util.List;
import com.yc.sy.entity.Guest;
public interface GuestMapper {
public List<Guest> getGuest();
public int insertGuest(Guest guest);
public List<Guest> listGuest();
public int deleteMes(Integer gid);
public Guest getMesById(Integer gid);
} |
/**
* class MenuMiniMap
*/
#ifndef MENU_MINI_MAP_H
#define MENU_MINI_MAP_H
#include "CommonIncludes.h"
#include "Utils.h"
class MapCollision;
class WidgetLabel;
class MenuMiniMap : public Menu {
private:
Color color_wall;
Color color_obst;
Color color_hero;
Sprite *map_surface;
Point map_size;
Rect pos;
WidgetLabel *label;
void createMapSurface();
void renderIso(const FPoint& hero_pos);
void renderOrtho(const FPoint& hero_pos);
void prerenderOrtho(MapCollision *collider);
void prerenderIso(MapCollision *collider);
public:
MenuMiniMap();
~MenuMiniMap();
void align();
void render();
void render(const FPoint& hero_pos);
void prerender(MapCollision *collider, int map_w, int map_h);
void setMapTitle(const std::string& map_title);
};
#endif |
<!
Copyright (C) 2016 phantombot.tv
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http:
@author IllusionaryOne
<!-- This is outside of the accordion, so will always be on top of the tab -->
<!-- Accordion object. Each section is separated by an <h3 /> header and the content is to be enclosed in <div />. -->
<div id="noticesAccordion">
<h3>Notices & Settings</h3>
<div>
<div id="<API key>" />
<div id="_noticeConfigPanel">
<table>
<tr class="textList">
<td>Toggle Chat Notices</td>
<td style="width: 25px"><div id="chatNoticeMode" /></td>
<td style="width: 25px">
<div data-toggle="tooltip" title="Toggle" class="button"
onclick="$.toggleChatNotice();"><i class="fa fa-refresh" />
</div>
</td>
</tr>
</table>
<table>
<tr class="textList">
<td>Toggle Offline Chat Notices</td>
<td style="width: 25px"><div id="<API key>" /></td>
<td style="width: 25px">
<div data-toggle="tooltip" title="Toggle" class="button"
onclick="$.<API key>();"><i class="fa fa-refresh" />
</div>
</td>
</tr>
</table>
<br>
Set the interval for notices and the required messages before triggering one. Use 0 for required messages if you only want a timer.<br><br>
<form role="form">
<div class="form-group" onkeypress="return event.keyCode != 13">
<label for="noticeInterval">Timer Interval</label>
<button type="button" class="btn btn-primary inline pull-right"
onclick="$.<API key>('#noticeIntervalInput', 'interval')">Submit</button>
<input type="number" min="5" class="form-control" id="noticeIntervalInput" placeholder="Minutes"
data-toggle="tooltip" title="Set the interval (in minutes) of when a notice gets triggered. Minimum is 5 minutes" />
</div>
</form>
<form role="form">
<div class="form-group" onkeypress="return event.keyCode != 13">
<label for="noticeMsgReq">Required Messages</label>
<button type="button" class="btn btn-primary inline pull-right"
onclick="$.updateNoticeReq('#noticeReqInput', 'reqmessages')">Submit</button>
<input type="number" min="1" class="form-control" id="noticeReqInput" placeholder="Number of Messages"
data-toggle="tooltip" title="Set the amount of messages required before a notice gets triggered." />
</div>
</form>
<br>
Notices are timed chat announcements that are said randomly with the interval you have set. It is a great feature to promote your social media.<br><br>
<div id="<API key>" />
<div id="_noticesPanel">
<form role="form">
<div class="form-group" onkeypress="return event.keyCode != 13">
<label for="addNotice">Add New Notice</label>
<button type="button" class="btn btn-primary inline pull-right"
onclick="$.addNotice()">Submit</button>
<input type="text" class="form-control" id="addNoticeInput" placeholder="New Notice"
data-toggle="tooltip" title="Enter a message, or you can use a command. command:Command_Name" />
</div>
</form>
Current Notices
<div id="noticeList" style="height: 200px; overflow: auto;" />
</div>
</div>
</div>
</div>
<!-- Run the Acordion -->
<script>$("#noticesAccordion").accordion( { clearStyle: true, heightStyle: "panel", icons: null } );</script>
<script>$('[data-toggle="tooltip"]').tooltip({ trigger: 'hover' });</script>
<script>handleInputFocus();</script> |
package co.fxl.data.format.gwt;
import java.util.Date;
import co.fxl.data.format.api.IFormat;
public abstract class DateFormatImpl implements IFormat<Date> {
int yearIncrement = 1900;
int monthIncrement = 1;
int dayIncrement = 1;
public DateFormatImpl() {
}
public DateFormatImpl(int yearIncrement, int monthIncrement, int dayIncrement) {
this.yearIncrement = yearIncrement;
this.monthIncrement = monthIncrement;
this.dayIncrement = dayIncrement;
}
@SuppressWarnings("deprecation")
@Override
public Date parse(String string) {
try {
if (string == null || string.equals(""))
return null;
String[] s = string.split("\\.");
Integer year = Integer.valueOf(s[2]);
if (year < 0)
return null;
Integer month = Integer.valueOf(s[1]);
if (month < 1 || month > 12)
return null;
Integer day = Integer.valueOf(s[0]);
if (day < 1 || day > 31)
return null;
return new Date(year - yearIncrement, month - monthIncrement, day - dayIncrement);
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
@Override
public String format(Date date) {
if (date == null)
return "";
int day = date.getDate() + dayIncrement;
int month = date.getMonth() + monthIncrement;
int year = date.getYear() + yearIncrement;
String string = l(day, 2) + "." + l(month, 2) + "." + l(year, 4);
return string;
}
static String l(int date, int i) {
String s = String.valueOf(date);
while (s.length() < i)
s = "0" + s;
return s;
}
} |
// The LLVM Compiler Infrastructure
// <string_view>
// void remove_prefix(size_type _n)
#include <string_view>
#include <cassert>
#include <iostream>
#include "test_macros.h"
template<typename CharT>
void test ( const CharT *s, size_t len ) {
typedef std::basic_string_view<CharT> SV;
{
SV sv1 ( s );
assert ( sv1.size() == len );
assert ( sv1.data() == s );
if ( len > 0 ) {
sv1.remove_prefix ( 1 );
assert ( sv1.size() == (len - 1));
assert ( sv1.data() == (s + 1));
sv1.remove_prefix ( len - 1 );
}
assert ( sv1.size() == 0 );
sv1.remove_prefix ( 0 );
assert ( sv1.size() == 0 );
}
}
#if _LIBCPP_STD_VER > 11
constexpr size_t test_ce ( size_t n, size_t k ) {
typedef std::basic_string_view<char> SV;
SV sv1{ "ABCDEFGHIJKL", n };
sv1.remove_prefix ( k );
return sv1.size();
}
#endif
int main () {
test ( "ABCDE", 5 );
test ( "a", 1 );
test ( "", 0 );
test ( L"ABCDE", 5 );
test ( L"a", 1 );
test ( L"", 0 );
#if TEST_STD_VER >= 11
test ( u"ABCDE", 5 );
test ( u"a", 1 );
test ( u"", 0 );
test ( U"ABCDE", 5 );
test ( U"a", 1 );
test ( U"", 0 );
#endif
#if _LIBCPP_STD_VER > 11
{
static_assert ( test_ce ( 5, 0 ) == 5, "" );
static_assert ( test_ce ( 5, 1 ) == 4, "" );
static_assert ( test_ce ( 5, 5 ) == 0, "" );
static_assert ( test_ce ( 9, 3 ) == 6, "" );
}
#endif
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.