answer stringlengths 15 1.25M |
|---|
# -*- coding: utf-8; -*-
# This file is part of Superdesk.
from superdesk.io.feed_parsers.newsml_2_0 import NewsMLTwoFeedParser
from superdesk.io.registry import <API key>
from superdesk.errors import ParserError
from superdesk.metadata.item import CONTENT_TYPE
from superdesk import etree as sd_etree
from superdesk import text_utils
import logging
logger = logging.getLogger(__name__)
IPTC_NS = 'http://iptc.org/std/nar/2006-10-01/'
class STTNewsMLFeedParser(NewsMLTwoFeedParser):
"""
Feed Parser which can parse STT variant of NewsML
"""
NAME = 'sttnewsml'
label = "STT NewsML"
SUBJ_QCODE_PREFIXES = ('stt-subj',)
def can_parse(self, xml):
return xml.tag.endswith('newsItem')
def parse(self, xml, provider=None):
self.root = xml
try:
item = self.parse_item(xml)
if not item.get('headline'):
item['headline'] = text_utils.get_text(item.get('body_html', ''), 'html')[:100]
try:
abstract = xml.xpath("//iptc:description[@role='drol:summary']", namespaces={'iptc': IPTC_NS})[0].text
except IndexError:
pass
else:
if abstract:
item['abstract'] = abstract
return [item]
except Exception as ex:
raise ParserError.<API key>(ex, provider)
def <API key>(self, tree, item):
html_elt = tree.find(self.qname('html'))
body_elt = html_elt.find(self.qname('body'))
body_elt = sd_etree.clean_html(body_elt)
content = dict()
content['contenttype'] = tree.attrib['contenttype']
if len(body_elt) > 0:
contents = [sd_etree.to_string(e, encoding='unicode', method="html") for e in body_elt]
content['content'] = '\n'.join(contents)
elif body_elt.text:
content['content'] = '<pre>' + body_elt.text + '</pre>'
content['format'] = CONTENT_TYPE.PREFORMATTED
return content
<API key>(STTNewsMLFeedParser.NAME, STTNewsMLFeedParser()) |
<?php
/**
* Isis value iterator. Iterates over all values for
* each result row.
*/
class IsisValueIterator implements Iterator
{
private $valueset;
private $row = 0;
private $rows = 0;
/**
* Constructor.
*
* @param $class
* Instance of IsisConnector or child class.
*
* @param $field
* Field to iterate over.
*/
public function __construct($class, $field) {
$this->rows = $class->getRows($field);
$this->valueset = $class->getValues($field);
}
/**
* Rewind the Iterator to the first element.
*/
function rewind() {
$this->row = 0;
$this->value = 0;
}
/**
* Return the key of the current element.
*/
function key() {
return $this->row;
}
/**
* Return the current element.
*/
function current() {
return $this->valueset[$this->row];
}
/**
* Move forward to next element.
*/
function next() {
++$this->row;
}
/**
* Check if there is a current element after calls to rewind() or next().
*/
function valid() {
return $this->row < $this->rows;
}
} |
package org.diqube.connection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransportException;
/**
* A thrift-usable socket customized for the use in diqube.
*
* @author Bastian Gloeckle
*/
public class DiqubeClientSocket extends TSocket {
private SocketListener listener;
private boolean listenerInformed = false;
/**
* @param timeout
* milliseconds
*/
/* package */ DiqubeClientSocket(String host, int port, int timeout, SocketListener listener) {
super(host, port, timeout);
this.listener = listener;
}
@Override
public void open() throws TTransportException {
super.open();
inputStream_ = new InputStreamFacade(inputStream_);
outputStream_ = new OutputStreamFacade(outputStream_);
}
private synchronized void connectionDied(String cause) {
if (!listenerInformed) {
listenerInformed = true;
listener.connectionDied(cause);
close();
}
}
private class InputStreamFacade extends InputStream {
private InputStream delegate;
public InputStreamFacade(InputStream delegate) {
this.delegate = delegate;
}
@Override
public int read() throws IOException {
try {
return delegate.read();
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public int read(byte[] b) throws IOException {
try {
return delegate.read(b);
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
try {
return delegate.read(b, off, len);
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public long skip(long n) throws IOException {
try {
return delegate.skip(n);
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public String toString() {
return delegate.toString();
}
@Override
public int available() throws IOException {
try {
return delegate.available();
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public void close() throws IOException {
try {
delegate.close();
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public void mark(int readlimit) {
delegate.mark(readlimit);
}
@Override
public void reset() throws IOException {
delegate.reset();
}
@Override
public boolean markSupported() {
return delegate.markSupported();
}
}
private class OutputStreamFacade extends OutputStream {
private OutputStream delegate;
public OutputStreamFacade(OutputStream delegate) {
this.delegate = delegate;
}
@Override
public void write(int b) throws IOException {
try {
delegate.write(b);
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public void write(byte[] b) throws IOException {
try {
delegate.write(b);
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
try {
delegate.write(b, off, len);
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public void flush() throws IOException {
try {
delegate.flush();
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public void close() throws IOException {
try {
delegate.close();
} catch (IOException e) {
connectionDied(e.getMessage());
throw new IOException(e);
}
}
@Override
public String toString() {
return delegate.toString();
}
}
} |
package elki.index.preprocessed.knn;
import java.util.EventObject;
import elki.database.ids.DBIDs;
/**
* Encapsulates information describing changes of the k nearest neighbors (kNNs)
* of some objects due to insertion or removal of objects. Used to notify all
* subscribed {@link KNNListener} of the change.
*
* @author Elke Achtert
* @since 0.4.0
*
* @has - - - DBIDs
*
* @see KNNListener
*/
public class KNNChangeEvent extends EventObject {
/**
* Serialization ID since Java EventObjects are expected to be serializable.
*/
private static final long serialVersionUID = 513913140334355886L;
/**
* Available event types.
*/
public enum Type {
/**
* Identifies the insertion of new objects.
*/
INSERT,
/**
* Identifies the removal of objects.
*/
DELETE
}
/**
* Holds the type of this change event.
*
* @see Type
*/
private final Type type;
/**
* The ids of the kNNs that were inserted or deleted due to the insertion or
* removals of objects.
*/
private final DBIDs objects;
/**
* The ids of the kNNs that were updated due to the insertion or removals of
* objects.
*/
private final DBIDs updates;
/**
* Used to create an event when kNNs of some objects have been changed.
*
* @param source the object responsible for generating the event
* @param type the type of change
* @param objects the ids of the removed or inserted kNNs (according to the
* type of this event)
* @param updates the ids of kNNs which have been changed due to the removals
* or insertions
* @see Type#INSERT
* @see Type#DELETE
*/
public KNNChangeEvent(Object source, Type type, DBIDs objects, DBIDs updates) {
super(source);
this.type = type;
this.objects = objects;
this.updates = updates;
}
/**
* Returns the type of this change event.
*
* @return {@link Type#INSERT} or {@link Type#DELETE}
*/
public Type getType() {
return type;
}
/**
* Returns the ids of the removed or inserted kNNs (according to the type of
* this event).
*
* @return the ids of the removed or inserted kNNs
*/
public DBIDs getObjects() {
return objects;
}
/**
* Returns the ids of kNNs which have been changed due to the removals or
* insertions.
*
* @return the ids of kNNs which have been changed
*/
public DBIDs getUpdates() {
return updates;
}
} |
// API: api.pixels.js
// database schemas
var Project = require('../models/project');
var Clientel = require('../models/client'); // weird name cause 'Client' is restricted name
var User = require('../models/user');
var File = require('../models/file');
var Layers = require('../models/layer');
// utils
var _ = require('lodash');
var fs = require('fs-extra');
var gm = require('gm');
var kue = require('kue');
var fss = require("q-io/fs");
var zlib = require('zlib');
var uuid = require('node-uuid');
var util = require('util');
var utf8 = require("utf8");
var mime = require("mime");
var exec = require('child_process').exec;
var dive = require('dive');
var async = require('async');
var carto = require('carto');
var crypto = require('crypto');
var fspath = require('path');
var request = require('request');
var nodepath = require('path');
var formidable = require('formidable');
var nodemailer = require('nodemailer');
var uploadProgress = require('<API key>');
var mapnikOmnivore = require('mapnik-omnivore');
var httpStatus = require('http-status');
// api
var api = module.parent.exports;
// function exports
module.exports = api.pixels = {
//
//
//
snap : function (req, res, next) {
var ops = [];
var view = req.body || {};
var user = req.user;
var script_path = api.config.path.tools + 'phantomJS-snapshot.js';
var filename = 'snap-' + api.utils.getRandom(10) + '.png';
var outPath = api.config.path.image + filename;
var options = {
url : api.config.portalServer.uri,
outPath : outPath,
view : view
};
var snapCommand = [
"--ssl-protocol=tlsv1",
script_path,
JSON.stringify(options)
];
var errorMessage = {};
// phantomJS: create snapshot
ops.push(function (callback) {
var util = require('util');
var spawn = require('child_process').spawn;
var ls = spawn('phantomjs', snapCommand);
ls.stdout.on('data', function (data) {
var dataTextObj = api.utils.parse(data) || {};
if (dataTextObj.error) {
errorMessage = dataTextObj.error;
}
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('exit', function (code) {
callback(code, code);
});
});
// create File
ops.push(function (callback) {
var f = new File();
f.uuid = 'file-' + uuid.v4();
f.createdBy = user.uuid;
f.createdByName = user.firstName + ' ' + user.lastName;
f.files = filename;
f.access.users = [user.uuid];
f.name = filename;
f.description = 'Snapshot';
f.type = 'image';
f.format = 'png';
f.data.image.file = filename;
f.save(function (err, doc) {
callback(err, doc);
});
});
async.series(ops, function (err, result) {
// get file
var created_snap = result[1];
if (result[0] == 1) {
next(errorMessage);
}
console.log(result);
// return to client
res.send({
image : created_snap && created_snap.uuid || null,
error : err || null
});
});
},
handleImage : function (path, callback) {
var entry = {};
var file = path;
var ops = {};
ops.dimensions = function (cb) {
// get image size
api.pixels.getImageSize(file, cb);
};
ops.identity = function (cb) {
// get exif size
api.pixels.getIdentify(file, cb);
};
ops.dataSize = function (cb) {
// get file size in bytes
api.pixels.getFileSize(file, cb);
};
// move raw file into /images/ folder
ops.rawFile = function (cb) {
// copy raw file
api.pixels.copyRawFile(file, cb);
};
// run all ops async in series
async.series(ops, function (err, results) {
if (err || !results) return callback(err || 'No results.');
var exif = results.identity,
dimensions = results.dimensions,
dataSize = results.dataSize,
file = results.rawFile;
entry.data = entry.data || {};
entry.data.image = entry.data.image || {};
entry.data.image.dimensions = dimensions;
entry.dataSize = dataSize;
entry.data.image.file = file;
entry.type = 'image';
if (exif) {
entry.data.image.created = api.pixels.getExif.created(exif);
entry.data.image.gps = api.pixels.getExif.gps(exif);
entry.data.image.cameraType = api.pixels.getExif.cameraType(exif);
entry.data.image.orientation = api.pixels.getExif.orientation(exif);
}
// return results to whatever callback
callback(null, entry);
});
},
// process images straight after upload
_processImage : function (entry, callback) {
var file = entry.permanentPath,
ops = {};
ops.dimensions = function (cb) {
// get image size
api.pixels.getImageSize(file, cb);
};
ops.identity = function (cb) {
// get exif size
api.pixels.getIdentify(file, cb);
};
ops.dataSize = function (cb) {
// get file size in bytes
api.pixels.getFileSize(file, cb);
};
// move raw file into /images/ folder
ops.rawFile = function (cb) {
// move raw file
api.pixels.moveRawFile(file, cb);
};
// run all ops async in series
async.series(ops, function (err, results) {
if (err || !results) return callback(err || 'No results.');
var exif = results.identity,
dimensions = results.dimensions,
dataSize = results.dataSize,
file = results.rawFile;
entry.data.image = entry.data.image || {};
entry.data.image.dimensions = dimensions;
entry.dataSize = dataSize;
entry.data.image.created = api.pixels.getExif.created(exif);
entry.data.image.gps = api.pixels.getExif.gps(exif);
entry.data.image.cameraType = api.pixels.getExif.cameraType(exif);
entry.data.image.orientation = api.pixels.getExif.orientation(exif);
entry.data.image.file = file;
// return results to whatever callback
callback(null, entry);
});
},
// helper fn to parse exif
getExif : {
created : function (exif) {
if (!exif) return;
var time = '';
var profile = exif['Profile-EXIF'];
if (profile) time = profile['Date Time']; // todo: other date formats
if (!time) return;
var s = time.split(/[-: ]/);
var date = new Date(s[0], s[1]-1, s[2], s[3], s[4], s[5]);
time = date.toJSON();
return time;
},
gps : function (exif) {
var profile = exif['Profile-EXIF'];
if (!profile) return;
// get numbers
var altitude = api.pixels.getExif.getAltitude(profile);
var direction = api.pixels.getExif.getDirection(profile);
var coords = api.pixels.getExif.getCoords(profile);
if (!coords) return;
var gps = {
lat : coords.lat,
lng : coords.lng,
alt : altitude,
dir : direction
};
return gps;
},
cameraType : function (exif) {
var cameraType = '';
var profile = exif['Profile-EXIF'];
if (profile) cameraType = profile['Model'];
return cameraType;
},
orientation : function (exif) {
var orientation = -1;
var orientations = {
'topleft' : 1,
'bottomright' : 3, // todo: BottomImageRight
'righttop' : 6,
'leftbottom' : 8
};
// from exif in int format
var profile = exif['Profile-EXIF'];
if (profile) {
orientation = profile.orientation;
if (orientation) return orientation;
}
// try from root orientation
var o = exif['Orientation'];
if (o) {
var text = o.toLowerCase();
orientation = orientations[text];
if (orientation) return orientation;
}
return -1;
},
getAltitude : function (profile) {
var gpsalt = profile['GPS Altitude'];
if (!gpsalt) return -1;
var alt = gpsalt.split('/');
if (!alt) return -1;
var x = alt[0];
var y = alt[1];
var altitude = parseInt(x) / parseInt(y);
return altitude;
},
getDirection : function (profile) {
var gpsdir = profile['GPS Img Direction'];
if (!gpsdir) return -1;
var dir = gpsdir.split('/');
if (!dir) return -1;
var x = dir[0];
var y = dir[1];
var direction = parseInt(x) / parseInt(y);
return direction;
},
getCoords : function(exif) {
var lat = exif.GPSLatitude || exif['GPS Latitude'];
var lon = exif.GPSLongitude || exif['GPS Longitude'];
var latRef = exif.GPSLatitudeRef || exif['GPS Latitude Ref'] || "N";
var lonRef = exif.GPSLongitudeRef || exif['GPS Longitude Ref'] || "W";
if (!lat || !lon) return false;
var ref = {'N': 1, 'E': 1, 'S': -1, 'W': -1};
var i;
if (typeof lat === 'string') {
lat = lat.split(',');
}
if (typeof lon === 'string') {
lon = lon.split(',');
}
for (i = 0; i < lat.length; i++) {
if (typeof lat[i] === 'string') {
lat[i] = lat[i].replace(/^\s+|\s+$/g,'').split('/');
lat[i] = parseInt(lat[i][0], 10) / parseInt(lat[i][1], 10);
}
}
for (i = 0; i < lon.length; i++) {
if (typeof lon[i] === 'string') {
lon[i] = lon[i].replace(/^\s+|\s+$/g,'').split('/');
lon[i] = parseInt(lon[i][0], 10) / parseInt(lon[i][1], 10);
}
}
lat = (lat[0] + (lat[1] / 60) + (lat[2] / 3600)) * ref[latRef];
lon = (lon[0] + (lon[1] / 60) + (lon[2] / 3600)) * ref[lonRef];
return {lat : lat, lng : lon}
}
},
getImageSize : function (path, callback) {
gm(path)
.size(function (err, size) {
callback(err, size);
});
},
getFileSize : function (path, callback) {
fs.stat(path, function (err, stats) {
callback(err, stats.size);
});
},
// move raw file to /images/ folder
moveRawFile : function (oldPath, callback) {
var newFile = 'image-raw-' + uuid.v4();
var newPath = api.config.path.image + newFile;
// move file
fs.rename(oldPath, newPath, function (err) {
callback(err, newFile);
});
},
// copy raw file to /images/ folder
copyRawFile : function (oldPath, callback) {
var newFile = 'image-raw-' + uuid.v4();
var newPath = api.config.path.image + newFile;
// copy file
fs.copy(oldPath, newPath, function (err) {
callback(err, newFile);
});
},
// add file to project
addFileToProject : function (file, projectUuid) {
Project
.findOne({uuid : projectUuid})
.exec(function (err, project) {
if (err || !project) return;
project.files.push(file._id);
project.markModified('files');
project.save(function (err, doc) {
if (err) console.log('File save error: ', err);
console.log('File saved to project.');
});
});
},
// resize single image
resizeImage : function (option, callback) {
if (!option) return callback('No options provided.');
// basic options
var width = parseInt(option.width) || null;
var height = parseInt(option.height) || null;
var quality = parseInt(option.quality) || 90; // default quality 60
// crop options
option.crop = option.crop || {};
var cropX = option.crop.x || 0; // default crop is no crop, same dimensions and topleft
var cropY = option.crop.y || 0;
var cropW = option.crop.w || width;
var cropH = option.crop.h || height;
// file options
var path = option.file; // original file
var newFile = 'image-' + uuid.v4(); // unique filename
var newPath = api.config.path.image + newFile; // modified file
var format = option.format || 'jpeg';
// wtf
gm.prototype.checkSize = function (action) {
action();
return this;
};
try {
// do crunch magic
gm(path)
.resize(width) // todo: if h/w is false, calc ratio
.autoOrient()
.crop(cropW, cropH, cropX, cropY) // x, y is offset from top left corner
.noProfile() // todo: strip of all exif?
.setFormat(format.toUpperCase()) // todo: watermark systemapic? or client?
.quality(quality)
.write(newPath, function (err) {
if (err) return callback(err);
var result = {
file : newFile,
height : height,
width : width,
path : newPath
};
// return error and file
callback(null, result);
});
} catch (e) {
callback(e);
}
},
getIdentify : function (path, callback) {
gm(path)
.identify(function (err, exif){
callback(err, exif);
});
},
// cxxxxx
<API key> : function (req, res) {
if (!req.query) return api.error.missingInformation(req, res);
// set vars
var quality = req.query.quality;
var imageId = req.params[0]; // '<API key>'
var fitW = req.query.fitW;
var fitH = req.query.fitH;
var newFile = 'image-' + uuid.v4(); // unique filename
var newPath = api.config.path.image + newFile; // modified file
var imagePath = '/data/images/' + imageId;
api.pixels.getImageSize(imagePath, function (err, size) {
if (err || !size) return api.error.general(req, res, err || 'No size.');
var imgWidth = size.width;
var imgHeight = size.height;
var imgLandscape;
var fitLandscape;
if (imgWidth >= imgHeight) imgLandscape = true;
if (fitW >= fitH) fitLandscape = true;
if ( !fitLandscape && imgLandscape ) {
cropW = fitW * fitH/fitW;
// Offset the X axis
cropX = (cropW - fitW) / 2;
cropY = 0;
} else {
cropW = fitW;
// Find the image proportion
var prop = imgWidth / cropW;
// Find the image size with overflow
cropH = imgHeight / prop;
cropX = 0;
// Offset the Y axis
cropY = (cropH - fitH) / 2;
}
quality = 100;
// do crunch magic
gm(imagePath)
.resize(cropW) // the width of the image BEFORE cropping!
.autoOrient()
.crop(
fitW, // The actual width of the image
fitH, // The actual height of the image
cropX, // x, y is offset from top left corner
cropY
)
.noProfile() // todo: strip of all exif?
.setFormat('JPEG') // todo: watermark systemapic? or client?
.quality(quality)
.write(newPath, function (err) {
if (err) return api.error.general(req, res, err);
res.sendfile(newPath, {maxAge : 10000000});
});
});
},
<API key> : function (req, res) {
if (!req.query) return api.error.missingInformation(req, res);
// set vars
var width = req.query.width;
var height = req.query.height;
var quality = req.query.quality;
var imageId = req.params[0]; // '<API key>'
var cropX = req.query.cropx;
var cropY = req.query.cropy;
var cropW = req.query.cropw;
var cropH = req.query.croph;
var format = req.query.format;
var imagePath = '/data/images/' + imageId;
if (imageId == 'images') return res.send();
var options = {
height: height,
width : width,
file : imagePath,
format : format,
crop : {
x : cropX,
y : cropY,
h : cropH,
w : cropW
},
quality : quality
};
// create image with dimensions
api.pixels.resizeImage(options, function (err, result) {
if (err || !result) return api.error.general(req, res, err || 'No result.');
var path = result.path;
res.sendfile(path, {maxAge : 10000000});
});
},
serveScreenshot : function (req, res) {
if (!req.query) return api.error.missingInformation(req, res);
// set vars
var image_id = req.params[0]; // '<API key>'
var path = '/data/images/' + image_id;
// only allow screenshot to go thru
if (path.indexOf('resized_screenshot.jpg') == -1) return res.send();
// return screenshot
res.sendfile(path, {maxAge : 10000000});
},
_resizeScreenshot : function (options, callback) {
var image = options.image; // /data/images/<API key>.png
var outPath = image + '.resized_screenshot.jpg';
var width = 1200;
// do crunch magic
gm(image)
.resize(width) // todo: if h/w is false, calc ratio
.autoOrient()
.noProfile() // todo: strip of all exif?
.quality(90)
.write(outPath, function (err) {
if (err) return callback(err);
var base = outPath.split('/').reverse()[0];
// return error and file
callback(null, base);
});
},
// serve images without wasting a pixel
<API key> : function (req, res) {
if (!req.query) return api.error.missingInformation(req, res);
// set vars
var width = req.query.width;
var height = req.query.height;
var quality = req.query.quality;
var raw = req.query.raw;
var fileUuid = req.params[0]; // '<API key>'
var cropX = req.query.cropx;
var cropY = req.query.cropy;
var cropW = req.query.cropw;
var cropH = req.query.croph;
// if raw quality requested, return full image
if (raw) return api.pixels.returnRawfile(req, res);
// async waterfall (each fn passes results into next fn)
var ops = [];
// find file
ops.push(function (callback) {
File
.findOne({uuid : fileUuid})
.exec(function (err, file) {
if (err || !file) return callback(err || 'No file.');
// find image with right dimensions (exactly) // todo: % margins
var image = _.find(file.data.image.crunched, function (i) {
if (!i) return false;
if (_.isObject(i.crop)) i.crop = {}; // prevent errors
// check if crunched is same dimensions
return parseInt(i.width) == parseInt(width) && // width
parseInt(i.height) == parseInt(height) && // height
parseInt(i.quality) == parseInt(quality) && // quality
parseInt(i.crop.x) == parseInt(cropX) && // crop
parseInt(i.crop.y) == parseInt(cropY) && // crop
parseInt(i.crop.h) == parseInt(cropH) && // crop
parseInt(i.crop.w) == parseInt(cropW); // crop
});
// return found image (if any)
var rawfile = file.data.image.file;
var vars = {
rawfile : file.data.image.file,
image : image
};
callback(null, vars);
});
});
// create image if not found
ops.push(function (vars, callback) {
if (!vars) return callback('Missing vars.');
var image = vars.image;
var rawfile = vars.rawfile;
// return image if found
if (image) {
image.existing = true;
return callback(null, image);
}
// if not found, create image
var template = {
file : api.config.path.image + rawfile,
width : width,
height : height,
quality : quality,
crop : {
x : cropX,
y : cropY,
h : cropH,
w : cropW
}
};
// create image with dimensions
api.pixels.resizeImage(template, callback);
});
// image found or created
ops.push(function (result, callback) {
// add image to File object if it was created
if (!result.existing) api.pixels.addImageToFile(result, fileUuid);
// return result
callback(null, result);
});
// run all async ops
async.waterfall(ops, function (err, result) {
if (err || !result) return api.error.general(req, res, err || 'No result.');
api.pixels.returnImage(req, res, result);
});
},
// add crunched image to File object
addImageToFile : function (result, fileUuid, callback) {
File
.findOne({uuid : fileUuid})
.exec(function (err, file) {
if (err || !file) {
callback && callback(err || 'No file.');
return;
}
file.data.image.crunched.addToSet(result);
file.markModified('data');
file.save(function (err) {
if (callback) callback(err, result);
});
});
},
// send image to client
returnImage : function (req, res, imageFile) {
// send file back to client, just need file path
var path = api.config.path.image + imageFile.file;
res.sendfile(path, {maxAge : 10000000}); // cache age, 115 days.. cache not working?
},
returnRawfile : function (req, res) {
var fileUuid = req.params[0];
// get raw file
File
.findOne({uuid : fileUuid})
.exec(function (err, file) {
if (err || !file) return api.error.general(req, res, err || 'No file.');
// return raw file
var imageFile = file.data.image;
return api.pixels.returnImage(req, res, imageFile);
});
}
}; |
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML-3.2//EN">
<HTML> <HEAD>
<TITLE></TITLE>
<LINK REV="made" HREF="mailto:dougo AT ccs.neu.edu">
</HEAD>
<BODY>
<H1><HR></H1>
<pre>
From: chris losinger <chrisdl AT pagesz.net>
Date: Mon, 15 Dec 1997 16:15:08 -0500
oh boy oh boy !
since i consider my musical taste to be highly developed as to
quality, if somewhat limited in scope, i will trust that
most of what i bought in 1997 that was released in 1997 is also
the best of 1997.
so,
Blonde Redhead - Fake Can Be Just As Good
Yo La Tengo - Autumn Sweater
Pavement - Brighten the Corners
Polvo - Shapes
Sea and Cake - The Fawn
Alison Krauss & co. - So Long So Wrong ( i _do_ live in NC)
aside from a possible negative vote for Bjork's Homogenic,
that's it.
-c
c h r i s l o s i n g e r
chrisdl AT pagesz.net http:
tupelos! tupelos! tupelos!
</pre>
<HR>
<ADDRESS><A HREF="http:
<A HREF="mailto:dougo AT ccs.neu.edu"><dougo AT ccs.neu.edu></A>
</ADDRESS>
<!-- hhmts start -->
Last modified: Sun Dec 27 23:17:07 EST 1998
<!-- hhmts end -->
</BODY> </HTML> |
<?php
class <API key>
{
/**
*
* @var Version $Version
* @access public
*/
public $Version = null;
/**
*
* @var ShipmentNumberType $ShipmentNumber
* @access public
*/
public $ShipmentNumber = null;
/**
*
* @var ShipmentOrderDDType $ShipmentOrder
* @access public
*/
public $ShipmentOrder = null;
/**
*
* @param Version $Version
* @param ShipmentNumberType $ShipmentNumber
* @param ShipmentOrderDDType $ShipmentOrder
* @access public
*/
public function __construct($Version, $ShipmentNumber, $ShipmentOrder)
{
$this->Version = $Version;
$this->ShipmentNumber = $ShipmentNumber;
$this->ShipmentOrder = $ShipmentOrder;
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rgaa 4.0 Test.1.1.7 Passed 01</title>
</head>
<body class="Passed">
<div>
<h1>Rgaa 4.0 Test.1.1.7 Passed 01</h1>
<!-- START [test-detail] -->
<div class="test-detail" lang="fr">
<p>Chaque image embarquée (balise <code><embed></code> avec l’attribut <code>type="image/…"</code>) <a href="https://www.numerique.gouv.fr/publications/rgaa-accessibilite/methode/glossaire/
<ul>
<li>La balise <code><embed></code> possède une alternative textuelle</li>
<li>L’élément <code><embed></code> est immédiatement suivi d’un <a href="https://www.numerique.gouv.fr/publications/rgaa-accessibilite/methode/glossaire/
<li>Un mécanisme permet à l’utilisateur de remplacer l’élément <code><embed></code> par un <a href="https://www.numerique.gouv.fr/publications/rgaa-accessibilite/methode/glossaire/#contenu-alternatif">contenu alternatif</a>.</li>
</ul>
</div>
<!-- END [test-detail] -->
<!-- #testcase -->
<!-- START [test-explanation] -->
<div class="test-explanation">
Passed.
</div>
<!-- END [test-explanation] -->
</div>
</body>
</html> |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Rgaa32016 Test.8.7.1 Failed 01</title>
</head>
<body class="Failed">
<div>
<h1>Rgaa32016 Test.8.7.1 Failed 01</h1>
<!-- START [test-detail] -->
<div class="test-detail" lang="fr">
Dans chaque page Web, chaque texte &
</div>
<!-- END [test-detail] -->
<div class="testcase">
</div>
<div class="test-explanation">
Failed.
</div>
</div>
</body>
</html> |
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# at the root of the source code of this program. If not,
import itertools
from typing import List, Union
from ddd.logic.<API key>.commands import <API key>
from ddd.logic.<API key>.domain.model.<API key> import \
<API key>
from ddd.logic.<API key>.domain.model.<API key> import \
<API key>
from ddd.logic.<API key>.domain.service.<API key> import \
<API key>
from ddd.logic.<API key>.domain.service.<API key> import \
<API key>
from ddd.logic.<API key>.dtos import <API key>, \
<API key>, <API key>, <API key>, \
<API key>, <API key>
from ddd.logic.<API key>.repository.<API key> import \
<API key>
from education_group.ddd.domain.group import GroupIdentity
from osis_common.ddd import interface
class <API key>(interface.DomainService):
@classmethod
def <API key>(
cls,
cmd: '<API key>',
<API key>: '<API key>',
<API key>: '<API key>',
<API key>: '<API key>'
):
formation = <API key>.get_formation(
code_programme=cmd.code_programme,
annee=cmd.annee,
)
groupements_ajustes = <API key>.search(
groupement_id=GroupIdentity(
year=cmd.annee,
code=cmd.code_programme,
)
)
<API key> = cls.<API key>(
groupements_ajustes,
<API key>
)
return <API key>(
uuid='uuid-1234',
code=formation.racine.<API key>.code,
annee=cmd.annee,
sigle=formation.sigle,
version=formation.version,
transition_name=formation.transition_name,
<API key>=formation.intitule_formation,
racine=cls.__build_contenu(
[formation.racine],
groupements_ajustes,
<API key>
)[0],
)
@classmethod
def <API key>(
cls,
groupements_ajustes: List['<API key>'],
<API key>: '<API key>'
) -> List['<API key>']:
<API key> = itertools.chain.from_iterable(
[
groupement.<API key>
for groupement in groupements_ajustes
]
)
<API key> = [
unite_enseignement.<API key>
for unite_enseignement in <API key>
]
return <API key>.search(
entity_ids=<API key>
)
@classmethod
def __build_contenu(
cls,
<API key>: List[Union['<API key>', '<API key>']],
groupements_ajustes: List['<API key>'],
<API key>: List['<API key>']
) -> List[Union['<API key>', '<API key>']]:
contenu = []
for element in <API key>:
if isinstance(element, <API key>):
contenu.append(
<API key>(
code=element.code,
intitule=element.intitule_complet,
obligatoire=element.obligatoire,
bloc=element.bloc,
)
)
elif isinstance(element, <API key>):
contenu.append(
<API key>(
intitule_complet=element.<API key>.intitule_complet,
obligatoire=element.<API key>.obligatoire,
code=element.<API key>.code,
<API key>=cls.<API key>(
element,
groupements_ajustes,
<API key>
),
contenu=cls.__build_contenu(
element.<API key>,
groupements_ajustes,
<API key>
)
)
)
return contenu
@classmethod
def <API key>(
cls,
groupement: '<API key>',
groupements_ajustes: List['<API key>'],
<API key>: List['<API key>']
) -> List['<API key>']:
<API key> = next(
(
groupement_ajuste
for groupement_ajuste in groupements_ajustes
if groupement_ajuste.groupement_id.code == groupement.<API key>.code
),
None
)
<API key> = <API key>.<API key> if \
<API key> else []
return [
cls.<API key>(unite_enseignement, <API key>)
for unite_enseignement in <API key>
]
@classmethod
def <API key>(
cls,
<API key>: '<API key>',
<API key>: List['<API key>']
) -> '<API key>':
<API key> = next(
dto for dto in <API key> if dto.code == <API key>.code
)
return <API key>(
code=<API key>.code,
intitule=<API key>.intitule_complet,
obligatoire=<API key>.obligatoire,
bloc=1,
a_la_suite_de="",
) |
extern crate diesel;
use self::diesel::result::Error as DatabaseError;
use std::error;
use std::fmt;
use std::convert::From;
#[derive(Debug)]
pub enum QuizError {
DatabaseError(DatabaseError),
JokerUnavailable,
GameAlreadyFinished,
NoGameInProgress,
GameStillInProgress,
StateError,
OutOfResources,
}
impl fmt::Display for QuizError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
QuizError::DatabaseError(ref err) => write!(f, "Database error: {}", err),
QuizError::JokerUnavailable => write!(f, "Joker error: Tried to use unavailable Joker"),
QuizError::GameAlreadyFinished => {
write!(f,
"Game already finished error: Tried to interact with a game that has already been finished")
}
QuizError::NoGameInProgress => {
write!(f,
"No game in progress error: Tried to play without starting a game first")
}
QuizError::GameStillInProgress => {
write!(f,
"Game still in progress error: Tried to start game while old one was not finished yet")
}
QuizError::StateError => {
write!(f,
"State error: Found game in a corrupt state, e.g. no available categories")
}
QuizError::OutOfResources => {
write!(f, "Out of resources error: Answered all possible questions")
}
}
}
}
impl error::Error for QuizError {
fn description(&self) -> &str {
match *self {
QuizError::DatabaseError(ref err) => err.description(),
QuizError::JokerUnavailable => "Joker unavailable error",
QuizError::GameAlreadyFinished => "Game already finished error",
QuizError::GameStillInProgress => "Game still in progress error",
QuizError::NoGameInProgress => "No game in progress error",
QuizError::StateError => "State error",
QuizError::OutOfResources => "Out of resources error",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
QuizError::DatabaseError(ref err) => Some(err),
_ => None,
}
}
}
impl From<DatabaseError> for QuizError {
fn from(err: DatabaseError) -> Self {
QuizError::DatabaseError(err)
}
} |
<?php
$ret = $GLOBALS['db']->Execute("UPDATE `".DB_PREFIX."_mods` SET `icon` = 'l4d.png' WHERE `modfolder` = 'left4dead' AND `icon` = '';");
return true;
?> |
package com.rapidminer.operator;
import com.rapidminer.operator.ports.PortOwner;
import com.rapidminer.operator.ports.quickfix.QuickFix;
import java.util.List;
/**
* An error in the process setup that can be registered with the operator in which it appears using
* {@link Operator#addError(ProcessSetupError)}. Beyond specifying its message, an error may also
* provide a collections of quick fixes that solve this problem.
*
* @author Simon Fischer
*
*/
public interface ProcessSetupError {
/** Severity levels of ProcessSetupErrors. */
public enum Severity {
/**
* This indicates that the corresponding message is just for information
*/
INFORMATION,
/**
* This is an indicator of wrong experiment setup, but the process may run nevertheless.
*/
WARNING,
/** Process will definitely (well, say, most certainly) not run. */
ERROR
}
/** Returns the human readable, formatted message. */
public String getMessage();
/**
* Returns the owner of the port that should be displayed by the GUI to fix the error.
*/
public PortOwner getOwner();
/** If possible, return a list of fixes for the error. */
public List<? extends QuickFix> getQuickFixes();
/** Returns the severity of the error. */
public Severity getSeverity();
} |
package org.kuali.kfs.module.ld.document.validation.impl;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.kns.service.<API key>;
import org.kuali.kfs.krad.service.<API key>;
import org.kuali.kfs.krad.util.GlobalVariables;
import org.kuali.kfs.module.ld.LaborConstants;
import org.kuali.kfs.module.ld.businessobject.<API key>;
import org.kuali.kfs.module.ld.businessobject.PositionData;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.<API key>;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.validation.GenericValidation;
import org.kuali.kfs.sys.document.validation.event.<API key>;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Validates that a labor journal voucher document's accounting lines have valid Position Code
*/
public class <API key> extends GenericValidation {
private AccountingLine <API key>;
/**
* Validates that the accounting line in the labor journal voucher document for valid position code
*
* @see org.kuali.kfs.validation.Validation#validate(java.lang.Object[])
*/
public boolean validate(<API key> event) {
boolean result = true;
<API key> <API key> = (<API key>) <API key>();
String positionNumber = <API key>.getPositionNumber();
if (StringUtils.isBlank(positionNumber) || LaborConstants.<API key>().equals(positionNumber)) {
return true;
}
if (!<API key>(positionNumber)) {
result = false;
}
return result;
}
/**
* Checks whether employee id exists
*
* @param positionNumber positionNumber is checked against the collection of position number matches
* @return True if the given position number exists, false otherwise.
*/
protected boolean <API key>(String positionNumber) {
boolean <API key> = true;
Map<String, Object> criteria = new HashMap<String, Object>();
criteria.put(<API key>.POSITION_NUMBER, positionNumber);
Collection<PositionData> <API key> = SpringContext.getBean(<API key>.class).findMatching(PositionData.class, criteria);
if (<API key> == null || <API key>.isEmpty()) {
String label = SpringContext.getBean(<API key>.class).getDataDictionary().<API key>(PositionData.class.getName()).<API key>(<API key>.POSITION_NUMBER).getLabel();
GlobalVariables.getMessageMap().putError(<API key>.POSITION_NUMBER, KFSKeyConstants.ERROR_EXISTENCE, label);
<API key> = false;
}
return <API key>;
}
/**
* Gets the <API key> attribute.
*
* @return Returns the <API key>.
*/
public AccountingLine <API key>() {
return <API key>;
}
/**
* Sets the <API key> attribute value.
*
* @param <API key> The <API key> to set.
*/
public void <API key>(AccountingLine <API key>) {
this.<API key> = <API key>;
}
} |
{% extends "base.html" %}
{% set active_page = "projects" %}
{% block content %}
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var project_task_runs = {{task_runs_json | tojson}};
var project_schema = {{<API key> | tojson}};
</script>
<script type="text/javascript" src="{{url_for('static', filename='geotagx-js/<API key>.js')}}">
</script>
<h1> {{ _('Task Run Summary') }} </h1>
<div class="row">
<div class="col-xs-6" id="<API key>">
</div>
<div class="col-xs-6">
<div class="row" id="<API key>"></div>
<div class="row">
<center>
<img id="<API key>" src="{{task_info.image_url}}" style="width:100%;padding:30px"></img>
</center>
</div>
</div>
</div>
{% endblock %} |
package org.brewingagile.backoffice.types;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.Objects;
@EqualsAndHashCode
@ToString(includeFieldNames = false)
public final class ParticipantEmail {
public final String value;
private ParticipantEmail(String x) {
this.value = Objects.requireNonNull(x);
}
public static ParticipantEmail participantEmail(String x) {
return new ParticipantEmail(x);
}
public static fj.Ord<ParticipantEmail> Ord = fj.Ord.ord(l -> r -> fj.Ord.stringOrd.compare(l.value, r.value));
} |
DELETE FROM `weenie` WHERE `class_Id` = 27317;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (27317, '<API key>', 10, '2019-02-10 00:00:00') /* Creature */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (27317, 1, 16) /* ItemType - Creature */
, (27317, 2, 31) /* CreatureType - Human */
, (27317, 6, -1) /* ItemsCapacity */
, (27317, 7, -1) /* ContainersCapacity */
, (27317, 16, 32) /* ItemUseable - Remote */
, (27317, 25, 91) /* Level */
, (27317, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, <API key>, EdgeSlide */
, (27317, 95, 8) /* RadarBlipColor - Yellow */
, (27317, 113, 1) /* Gender - Male */
, (27317, 133, 4) /* ShowableOnRadar - ShowAlways */
, (27317, 134, 16) /* PlayerKillerStatus - RubberGlue */
, (27317, 188, 1) /* HeritageGroup - Aluvian */
, (27317, 307, 5) /* DamageRating */
, (27317, 8007, 0) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (27317, 1, True ) /* Stuck */
, (27317, 19, False) /* Attackable */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (27317, 54, 3) /* UseRadius */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (27317, 1, 'Jonas') /* Name */
, (27317, 5, 'Tusker Captive') /* Template */
, (27317, 8006, 'AAA9AAAAAAA=') /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (27317, 1, 33554433) /* Setup */
, (27317, 2, 150994945) /* MotionTable */
, (27317, 3, 536870913) /* SoundTable */
, (27317, 6, 67108990) /* PaletteBase */
, (27317, 8, 100667446) /* Icon */
, (27317, 9, 83890506) /* EyesTexture */
, (27317, 10, 83890521) /* NoseTexture */
, (27317, 11, 83890632) /* MouthTexture */
, (27317, 15, 67117028) /* HairPalette */
, (27317, 16, 67110064) /* EyesPalette */
, (27317, 17, 67109559) /* SkinPalette */
, (27317, 8001, 9437238) /* <API key> - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */
, (27317, 8003, 4) /* <API key> - Stuck */
, (27317, 8005, 100419) /* <API key> - CSetup, MTable, Children, STable, Position, Movement */;
INSERT INTO `<API key>` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (27317, 8040, 1481179414, 111.432, -344.005, -95.995, -0.9999992, 0, 0, -0.001285) /* <API key> */
/* @teleloc 0x58490116 [111.432000 -344.005000 -95.995000] -0.999999 0.000000 0.000000 -0.001285 */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (27317, 8000, 3355943135) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`)
VALUES (27317, 1, 100, 0, 0) /* Strength */
, (27317, 2, 120, 0, 0) /* Endurance */
, (27317, 3, 250, 0, 0) /* Quickness */
, (27317, 4, 120, 0, 0) /* Coordination */
, (27317, 5, 190, 0, 0) /* Focus */
, (27317, 6, 190, 0, 0) /* Self */;
INSERT INTO `<API key>` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`)
VALUES (27317, 1, 140, 0, 0, 200) /* MaxHealth */
, (27317, 3, 130, 0, 0, 250) /* MaxStamina */
, (27317, 5, 110, 0, 0, 300) /* MaxMana */;
INSERT INTO `<API key>` (`object_Id`, `destination_Type`, `weenie_Class_Id`, `stack_Size`, `palette`, `shade`, `try_To_Bond`)
VALUES (27317, 2, 22546, 1, 0, 0, False) /* Create Coconut (22546) for Wield */;
INSERT INTO `<API key>` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (27317, 67109559, 0, 24)
, (27317, 67110064, 32, 8)
, (27317, 67113213, 80, 12)
, (27317, 67113213, 72, 8)
, (27317, 67117028, 24, 8);
INSERT INTO `<API key>` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (27317, 0, 83889072, 83893326)
, (27317, 0, 83889342, 83893326)
, (27317, 1, 83892352, 83893327)
, (27317, 5, 83892352, 83893327)
, (27317, 16, 83886232, 83890685)
, (27317, 16, 83886668, 83890506)
, (27317, 16, 83886837, 83890521)
, (27317, 16, 83886684, 83890632);
INSERT INTO `<API key>` (`object_Id`, `index`, `animation_Id`)
VALUES (27317, 0, 16777294)
, (27317, 1, 16783912)
, (27317, 2, 16777293)
, (27317, 3, 16777292)
, (27317, 4, 16777291)
, (27317, 5, 16783916)
, (27317, 6, 16777297)
, (27317, 7, 16777296)
, (27317, 8, 16777298)
, (27317, 9, 16777300)
, (27317, 10, 16777301)
, (27317, 11, 16777302)
, (27317, 12, 16777304)
, (27317, 13, 16777303)
, (27317, 14, 16777305)
, (27317, 15, 16777307)
, (27317, 16, 16795654); |
#include "memcached/tcp_conn.hpp"
#include "errors.hpp"
#include <boost/bind.hpp>
#include "arch/io/network.hpp"
#include "concurrency/cross_thread_signal.hpp"
#include "db_thread_info.hpp"
#include "logger.hpp"
#include "memcached/parser.hpp"
#include "perfmon/perfmon.hpp"
struct <API key> : public <API key>, public <API key> {
explicit <API key>(tcp_conn_t *c) : conn(c) { }
tcp_conn_t *conn;
void write(const char *buffer, size_t bytes, signal_t *interruptor) {
try {
assert_thread();
conn->write_buffered(buffer, bytes, interruptor);
} catch (<API key>) {
/* Ignore */
}
}
void write_unbuffered(const char *buffer, size_t bytes, signal_t *interruptor) {
try {
conn->write(buffer, bytes, interruptor);
} catch (<API key>) {
/* Ignore */
}
}
void flush_buffer(signal_t *interruptor) {
try {
conn->flush_buffer(interruptor);
} catch (<API key>) {
/* Ignore errors; it's OK for the write end of the connection to be closed. */
}
}
bool is_write_open() {
return conn->is_write_open();
}
void read(void *buf, size_t nbytes, signal_t *interruptor) {
try {
conn->read(buf, nbytes, interruptor);
} catch (<API key>) {
throw no_more_data_exc_t();
}
}
void read_line(std::vector<char> *dest, signal_t *interruptor) {
try {
for (;;) {
const_charslice sl = conn->peek();
void *crlf_loc = memmem(sl.beg, sl.end - sl.beg, "\r\n", 2);
ssize_t threshold = MEGABYTE;
if (crlf_loc) {
// We have a valid line.
size_t line_size = reinterpret_cast<char *>(crlf_loc) - sl.beg;
dest->resize(line_size + 2); // +2 for CRLF
memcpy(dest->data(), sl.beg, line_size + 2);
conn->pop(line_size + 2, interruptor);
return;
} else if (sl.end - sl.beg > threshold) {
// If a malfunctioning client sends a lot of data without a
// CRLF, we cut them off. (This doesn't apply to large values
// because they are read from the socket via a different
// mechanism.) There are better ways to handle this
// situation.
logERR("Aborting connection %p because we got more than %zd bytes without a CRLF",
coro_t::self(), threshold);
conn->shutdown_read();
throw <API key>();
}
// Keep trying until we get a complete line.
conn->read_more_buffered(interruptor);
}
} catch (<API key>) {
throw no_more_data_exc_t();
}
}
};
void serve_memcache(tcp_conn_t *conn, <API key><<API key>> *nsi, memcached_stats_t *stats, signal_t *interruptor) {
<API key> interface(conn);
handle_memcache(&interface, nsi, <API key>, stats, interruptor);
}
memcache_listener_t::memcache_listener_t(const std::set<ip_address_t> &local_addresses,
int _port,
namespace_repo_t<<API key>> *_ns_repo,
const namespace_id_t &_ns_id,
<API key> *_parent)
: port(_port),
ns_id(_ns_id),
ns_repo(_ns_repo),
next_thread(0),
parent(_parent),
stats(parent),
tcp_listener(new <API key>(local_addresses, port,
boost::bind(&memcache_listener_t::handle, this, auto_drainer_t::lock_t(&drainer), _1)))
{
tcp_listener-><API key>();
}
signal_t *memcache_listener_t::get_bound_signal() {
return tcp_listener->get_bound_signal();
}
memcache_listener_t::~memcache_listener_t() { }
void memcache_listener_t::handle(auto_drainer_t::lock_t keepalive, const scoped_ptr_t<<API key>> &nconn) {
assert_thread();
block_pm_duration conn_timer(&stats.pm_conns);
/* We will switch to another thread so there isn't too much load on the thread
where the `memcache_listener_t` lives */
int chosen_thread = (next_thread++) % get_num_db_threads();
/* Construct a cross-thread watcher so we will get notified on `chosen_thread`
when a shutdown command is delivered on the main thread. */
<API key> signal_transfer(keepalive.get_drain_signal(), chosen_thread);
on_thread_t thread_switcher(chosen_thread);
scoped_ptr_t<tcp_conn_t> conn;
nconn-><API key>(&conn);
/* `serve_memcache()` will continuously serve memcache queries on the given conn
until the connection is closed. */
try {
namespace_repo_t<<API key>>::access_t ns_access(ns_repo, ns_id, &signal_transfer);
serve_memcache(conn.get(), ns_access.get_namespace_if(), &stats, &signal_transfer);
} catch (const interrupted_exc_t &ex) {
// Interrupted, nothing to do but return
}
} |
<!DOCTYPE html>
<html lang="en"
>
<head>
<title>2016Fall - 2016Fall CPA (MDE)</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
/*some stuff for output/input prompts*/
div.cell{border:1px solid transparent;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch}div.cell.selected{border-radius:4px;border:thin #ababab solid}
div.cell.edit_mode{border-radius:4px;border:thin #008000 solid}
div.cell{width:100%;padding:5px 5px 5px 0;margin:0;outline:none}
div.prompt{min-width:11ex;padding:.4em;margin:0;font-family:monospace;text-align:right;line-height:1.21429em}
@media (max-width:480px){div.prompt{text-align:left}}div.inner_cell{display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch;-webkit-box-flex:1;-moz-box-flex:1;box-flex:1;flex:1}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;line-height:1.21429em}
div.prompt:empty{padding-top:0;padding-bottom:0}
div.input{page-break-inside:avoid;display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:horizontal;-moz-box-align:stretch;display:box;box-orient:horizontal;box-align:stretch;}
div.inner_cell{width:90%;}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;}
div.input_prompt{color:navy;border-top:1px solid transparent;}
div.output_wrapper{margin-top:5px;position:relative;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.output_scroll{height:24em;width:100%;overflow:auto;border-radius:4px;-webkit-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);-moz-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);}
div.output_collapsed{margin:0px;padding:0px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.out_prompt_overlay{height:100%;padding:0px 0.4em;position:absolute;border-radius:4px;}
div.out_prompt_overlay:hover{-webkit-box-shadow:inset 0 0 1px #000000;-moz-box-shadow:inset 0 0 1px #000000;box-shadow:inset 0 0 1px #000000;background:rgba(240, 240, 240, 0.5);}
div.output_prompt{color:darkred;}
a.anchor-link:link{text-decoration:none;padding:0px 20px;visibility:hidden;}
h1:hover .anchor-link,h2:hover .anchor-link,h3:hover .anchor-link,h4:hover .anchor-link,h5:hover .anchor-link,h6:hover .anchor-link{visibility:visible;}
/* end stuff for output/input prompts*/
.highlight-ipynb .hll { background-color: #ffffcc }
.highlight-ipynb { background: #f8f8f8; }
.highlight-ipynb .c { color: #408080; font-style: italic } /* Comment */
.highlight-ipynb .err { border: 1px solid #FF0000 } /* Error */
.highlight-ipynb .k { color: #008000; font-weight: bold } /* Keyword */
.highlight-ipynb .o { color: #666666 } /* Operator */
.highlight-ipynb .cm { color: #408080; font-style: italic } /* Comment.Multiline */
.highlight-ipynb .cp { color: #BC7A00 } /* Comment.Preproc */
.highlight-ipynb .c1 { color: #408080; font-style: italic } /* Comment.Single */
.highlight-ipynb .cs { color: #408080; font-style: italic } /* Comment.Special */
.highlight-ipynb .gd { color: #A00000 } /* Generic.Deleted */
.highlight-ipynb .ge { font-style: italic } /* Generic.Emph */
.highlight-ipynb .gr { color: #FF0000 } /* Generic.Error */
.highlight-ipynb .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight-ipynb .gi { color: #00A000 } /* Generic.Inserted */
.highlight-ipynb .go { color: #888888 } /* Generic.Output */
.highlight-ipynb .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.highlight-ipynb .gs { font-weight: bold } /* Generic.Strong */
.highlight-ipynb .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight-ipynb .gt { color: #0044DD } /* Generic.Traceback */
.highlight-ipynb .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.highlight-ipynb .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.highlight-ipynb .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.highlight-ipynb .kp { color: #008000 } /* Keyword.Pseudo */
.highlight-ipynb .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.highlight-ipynb .kt { color: #B00040 } /* Keyword.Type */
.highlight-ipynb .m { color: #666666 } /* Literal.Number */
.highlight-ipynb .s { color: #BA2121 } /* Literal.String */
.highlight-ipynb .na { color: #7D9029 } /* Name.Attribute */
.highlight-ipynb .nb { color: #008000 } /* Name.Builtin */
.highlight-ipynb .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.highlight-ipynb .no { color: #880000 } /* Name.Constant */
.highlight-ipynb .nd { color: #AA22FF } /* Name.Decorator */
.highlight-ipynb .ni { color: #999999; font-weight: bold } /* Name.Entity */
.highlight-ipynb .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.highlight-ipynb .nf { color: #0000FF } /* Name.Function */
.highlight-ipynb .nl { color: #A0A000 } /* Name.Label */
.highlight-ipynb .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.highlight-ipynb .nt { color: #008000; font-weight: bold } /* Name.Tag */
.highlight-ipynb .nv { color: #19177C } /* Name.Variable */
.highlight-ipynb .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.highlight-ipynb .w { color: #bbbbbb } /* Text.Whitespace */
.highlight-ipynb .mf { color: #666666 } /* Literal.Number.Float */
.highlight-ipynb .mh { color: #666666 } /* Literal.Number.Hex */
.highlight-ipynb .mi { color: #666666 } /* Literal.Number.Integer */
.highlight-ipynb .mo { color: #666666 } /* Literal.Number.Oct */
.highlight-ipynb .sb { color: #BA2121 } /* Literal.String.Backtick */
.highlight-ipynb .sc { color: #BA2121 } /* Literal.String.Char */
.highlight-ipynb .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.highlight-ipynb .s2 { color: #BA2121 } /* Literal.String.Double */
.highlight-ipynb .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.highlight-ipynb .sh { color: #BA2121 } /* Literal.String.Heredoc */
.highlight-ipynb .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.highlight-ipynb .sx { color: #008000 } /* Literal.String.Other */
.highlight-ipynb .sr { color: #BB6688 } /* Literal.String.Regex */
.highlight-ipynb .s1 { color: #BA2121 } /* Literal.String.Single */
.highlight-ipynb .ss { color: #19177C } /* Literal.String.Symbol */
.highlight-ipynb .bp { color: #008000 } /* Name.Builtin.Pseudo */
.highlight-ipynb .vc { color: #19177C } /* Name.Variable.Class */
.highlight-ipynb .vg { color: #19177C } /* Name.Variable.Global */
.highlight-ipynb .vi { color: #19177C } /* Name.Variable.Instance */
.highlight-ipynb .il { color: #666666 } /* Literal.Number.Integer.Long */
</style>
<style type="text/css">
/* Overrides of notebook CSS for static HTML export */
div.entry-content {
overflow: visible;
padding: 8px;
}
.input_area {
padding: 0.2em;
}
a.heading-anchor {
white-space: normal;
}
.rendered_html
code {
font-size: .8em;
}
pre.ipynb {
color: black;
background: #f7f7f7;
border: none;
box-shadow: none;
margin-bottom: 0;
padding: 0;
margin: 0px;
font-size: 13px;
}
/* remove the prompt div from text cells */
div.text_cell .prompt {
display: none;
}
/* remove horizontal padding from text cells, */
/* so it aligns with outer body text */
div.text_cell_render {
padding: 0.5em 0em;
}
img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none}
</style>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script>
<script type="text/javascript">
init_mathjax = function() {
if (window.MathJax) {
// MathJax loaded
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
},
displayAlign: 'left', // Change this to 'center' to center equations.
"HTML-CSS": {
styles: {'.MathJax_Display': {"margin": 0}}
}
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
}
init_mathjax();
</script>
<link rel="canonical" href="./<API key>.html">
<meta name="author" content="s40523241" />
<meta name="keywords" content=",,," />
<meta name="description" content=", , , ." />
<meta property="og:site_name" content="2016Fall CPA (MDE)" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="2016Fall "/>
<meta property="og:url" content="./<API key>.html"/>
<meta property="og:description" content=", , , ."/>
<meta property="article:published_time" content="2016-09-02" />
<meta property="article:section" content="Misc" />
<meta property="article:tag" content="" />
<meta property="article:tag" content="" />
<meta property="article:tag" content="" />
<meta property="article:tag" content="" />
<meta property="article:author" content="s40523241" />
<!-- Bootstrap -->
<link rel="stylesheet" href="./theme/css/bootstrap.united.min.css" type="text/css"/>
<link href="./theme/css/font-awesome.min.css" rel="stylesheet">
<link href="./theme/css/pygments/monokai.css" rel="stylesheet">
<link href="./theme/tipuesearch/tipuesearch.css" rel="stylesheet">
<link rel="stylesheet" href="./theme/css/style.css" type="text/css"/>
<link href="./feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
title="2016Fall CPA (MDE) ATOM Feed"/>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushJScript.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushJava.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushPython.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushPhp.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCpp.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCss.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCSharp.js"></script>
<script type="text/javascript" src="http://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushBash.js"></script>
<script type='text/javascript'>
(function(){
var corecss = document.createElement('link');
var themecss = document.createElement('link');
var corecssurl = "http://chiamingyen.github.io/kmolab_data/files/syntaxhighlighter/css/shCore.css";
if ( corecss.setAttribute ) {
corecss.setAttribute( "rel", "stylesheet" );
corecss.setAttribute( "type", "text/css" );
corecss.setAttribute( "href", corecssurl );
} else {
corecss.rel = "stylesheet";
corecss.href = corecssurl;
}
document.<API key>("head")[0].insertBefore( corecss, document.getElementById("<API key>") );
var themecssurl = "http://chiamingyen.github.io/kmolab_data/files/syntaxhighlighter/css/shThemeDefault.css?ver=3.0.9b";
if ( themecss.setAttribute ) {
themecss.setAttribute( "rel", "stylesheet" );
themecss.setAttribute( "type", "text/css" );
themecss.setAttribute( "href", themecssurl );
} else {
themecss.rel = "stylesheet";
themecss.href = themecssurl;
}
//document.getElementById("<API key>").appendChild(themecss);
document.<API key>("head")[0].insertBefore( themecss, document.getElementById("<API key>") );
})();
SyntaxHighlighter.config.strings.expandSource = '+ expand source';
SyntaxHighlighter.config.strings.help = '?';
SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n';
SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: ';
SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: ';
SyntaxHighlighter.defaults['pad-line-numbers'] = false;
SyntaxHighlighter.defaults['toolbar'] = false;
SyntaxHighlighter.all();
</script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="./" class="navbar-brand">
2016Fall CPA (MDE) </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="./pages/about/">
About
</a></li>
<li >
<a href="./category/course.html">Course</a>
</li>
<li class="active">
<a href="./category/misc.html">Misc</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span>
<form class="navbar-search" action="./search.html">
<input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input" required>
</form></span>
</li>
<li><a href="./archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<section id="content">
<article>
<header class="page-header">
<h1>
<a href="./<API key>.html"
rel="bookmark"
title="Permalink to 2016Fall ">
2016Fall
</a>
</h1>
</header>
<div class="entry-content">
<div class="panel">
<div class="panel-body">
<footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i class="fa fa-calendar"></i><time datetime="2016-09-02T12:00:00+08:00"> 02 2016</time>
</span>
<span class="label label-default">By</span>
<a href="./author/s40523241.html"><i class="fa fa-user"></i> s40523241</a>
<span class="label label-default">Tags</span>
<a href="./tag/shi-yong-dao-yin.html"></a>
/
<a href="./tag/chuang-zao-li.html"></a>
/
<a href="./tag/biao-da-neng-li.html"></a>
/
<a href="./tag/xie-tong-she-ji.html"></a>
</footer><!-- /.post-info --> </div>
</div>
<p>, , , .</p>
<h1></h1>
<p>, , .</p>
<ol>
<li> -
(Creative Competencies)</li>
<li> - 2D3D
(Six Presentation Methods)</li>
<li> -
(Collaborative Designs)</li>
</ol>
<h1></h1>
<p> Python3 print(), input(), , :</p>
<p> Python3 :</p>
<ol>
<li> Windows 10 </li>
<li> X-Windows, </li>
<li>
<p></p>
</li>
<li>
<p>:</p>
</li>
</ol>
<p> start.bat , git Python3 , Python3 , SciTE , go </p>
<p>:</p>
<p>? Python3 ? Python3 ?</p>
<p> SciTE Python3 , ?</p>
<p> Leo Editor Python3 , ?</p>
<ol>
<li>:</li>
</ol>
<p> Remote Desktop, Python3 , .</p>
<p> putty Xming, X-Windows , , .</p>
<ol>
<li>:</li>
</ol>
<p>, SolidWorks, OnShape , Brython , Python3 .</p>
<p>:</p>
<p>? <a href="https:
<p>?</p>
<p> Brython Python3 :</p>
<!-- Brython -->
<script type="text/javascript"
src="https://cdn.rawgit.com/brython-dev/brython/master/www/src/brython_dist.js">
</script>
<!-- Brython -->
<script>
window.onload=function(){
brython(1);
}
</script>
<!-- Brython -->
<canvas id="plotarea" width="600" height="400"></canvas>
<script type="text/python3">
# browser document, doc
from browser import document as doc
import math
import random
# browser ,
import browser.timer
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
width = canvas.width
height = canvas.height
n = 20
# , None
x = [None]*n
y = [None]*n
vy = [None]*n
vx = [None]*n
g = 0.05
cor = 0.7
fr = 0.95
r = 5
for i in range(n):
x[i] = 300
y[i] = 100
# random.random() 0 1
vx[i] = 2*(random.random()-.5)
vy[i] = 2*(random.random()-.5)
# i Y
def updateY(i):
if ((y[i]+r) < height):
#y = height
vy[i] += g
else:
vy[i] = -vy[i]*cor
vx[i] *= fr
y[i] += vy[i]
if ((y[i]+r) > height):
y[i] = height-r
# i X
def updateX(i):
if ((x[i]+r) >= width or (x[i]-r) <= 0):
vx[i] = -vx[i]*cor
x[i] += vx[i]
if ((x[i]+r) > width):
x[i] = width-r
elif ((x[i]-r) < 0):
x[i] = r
def circle(x,y,r):
ctx.beginPath()
ctx.arc(x, y, r, 0, math.pi*2, True)
ctx.fill()
ctx.closePath()
def text(s):
ctx.fillStyle = "#ff0000"
ctx.font = "30px sans-serif"
ctx.textBaseline = "bottom"
ctx.fillText(s,0,height)
def animate():
ctx.clearRect(0, 0, width, height)
ctx.fillStyle = "#000000"
for i in range(n):
updateY(i)
updateX(i)
circle(x[i],y[i],r)
text("Click me!")
def on_canvas_click(ev):
browser.timer.set_interval(animate,0)
# , on_canvas_click
canvas.bind('click', on_canvas_click, False)
</script>
<p>:</p>
<pre class="brush: python">
<canvas id="plotarea" width="600" height="400"></canvas>
<script type="text/python3">
# browser document, doc
from browser import document as doc
import math
import random
# browser ,
import browser.timer
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
width = canvas.width
height = canvas.height
n = 20
# , None
x = [None]*n
y = [None]*n
vy = [None]*n
vx = [None]*n
g = 0.05
cor = 0.7
fr = 0.95
r = 5
for i in range(n):
x[i] = 300
y[i] = 100
# random.random() 0 1
vx[i] = 2*(random.random()-.5)
vy[i] = 2*(random.random()-.5)
# i Y
def updateY(i):
if ((y[i]+r) < height):
#y = height
vy[i] += g
else:
vy[i] = -vy[i]*cor
vx[i] *= fr
y[i] += vy[i]
if ((y[i]+r) > height):
y[i] = height-r
# i X
def updateX(i):
if ((x[i]+r) >= width or (x[i]-r) <= 0):
vx[i] = -vx[i]*cor
x[i] += vx[i]
if ((x[i]+r) > width):
x[i] = width-r
elif ((x[i]-r) < 0):
x[i] = r
def circle(x,y,r):
ctx.beginPath()
ctx.arc(x, y, r, 0, math.pi*2, True)
ctx.fill()
ctx.closePath()
def text(s):
ctx.fillStyle = "#ff0000"
ctx.font = "30px sans-serif"
ctx.textBaseline = "bottom"
ctx.fillText(s,0,height)
def animate():
ctx.clearRect(0, 0, width, height)
ctx.fillStyle = "#000000"
for i in range(n):
updateY(i)
updateX(i)
circle(x[i],y[i],r)
text("Click me!")
def on_canvas_click(ev):
browser.timer.set_interval(animate,0)
# , on_canvas_click
canvas.bind('click', on_canvas_click, False)
</script>
</pre>
<p>:</p>
<p>1, :</p>
<pre class="brush: python">
<canvas id="japanflag1" width="600" height="250"></canvas>
<script type="text/python3">
from browser import document as doc
import math
canvas = doc["japanflag1"]
ctx = canvas.getContext("2d")
# ctx
ctx.beginPath()
ctx.lineWidth = 1
# (100, 100)
ctx.moveTo(100, 100)
# (150, 200)
ctx.lineTo(150, 200)
# , "rgb(0, 0, 255)"
ctx.strokeStyle = "blue"
ctx.stroke()
ctx.closePath()
</script>
</pre>
<!-- Brython -->
<canvas id="japanflag1" width="600" height="250"></canvas>
<script type="text/python3">
from browser import document as doc
import math
canvas = doc["japanflag1"]
ctx = canvas.getContext("2d")
# ctx
ctx.beginPath()
ctx.lineWidth = 1
# (100, 100)
ctx.moveTo(100, 100)
# (150, 200)
ctx.lineTo(150, 200)
# , "rgb(0, 0, 255)"
ctx.strokeStyle = "blue"
ctx.stroke()
ctx.closePath()
</script>
<p>:</p>
<pre class="brush: python">
<canvas id="japanflag2" width="600" height="400"></canvas>
<script type="text/python">
# doc
from browser import document as doc
import math
canvas = doc["japanflag2"]
ctx = canvas.getContext("2d")
# ctx
# , (x1, y1) , (x2, y2)
def draw_line(x1, y1, x2, y2):
global ctx
ctx.beginPath()
ctx.lineWidth = 1
# (x1, y1)
ctx.moveTo(x1, y1)
# (x2, y2)
ctx.lineTo(x2, y2)
# , "rgb(0, 0, 255)"
ctx.strokeStyle = "blue"
ctx.stroke()
ctx.closePath()
# draw_line()
# (10, 10) (410, 310)
draw_line(10, 10, 410, 10)
draw_line(10, 310, 410, 310)
draw_line(10, 10, 10, 310)
draw_line(410, 10, 410, 310)
</script>
</pre>
<canvas id="japanflag2" width="600" height="350"></canvas>
<script type="text/python">
# doc
from browser import document as doc
import math
canvas = doc["japanflag2"]
ctx = canvas.getContext("2d")
# ctx
# , (x1, y1) , (x2, y2)
def draw_line(x1, y1, x2, y2):
global ctx
ctx.beginPath()
ctx.lineWidth = 1
# (x1, y1)
ctx.moveTo(x1, y1)
# (x2, y2)
ctx.lineTo(x2, y2)
# , "rgb(0, 0, 255)"
ctx.strokeStyle = "blue"
ctx.stroke()
ctx.closePath()
# draw_line()
# (10, 10) (410, 310)
draw_line(10, 10, 410, 10)
draw_line(10, 310, 410, 310)
draw_line(10, 10, 10, 310)
draw_line(410, 10, 410, 310)
</script>
<p>:</p>
<pre class="brush: python">
<canvas id="japanflag3" width="650" height="450"></canvas>
<script type="text/python">
from browser import document
import math
canvas = document["japanflag3"]
ctx = canvas.getContext("2d")
# ctx
# , (x1, y1) , (x2, y2)
def draw_line(x1, y1, x2, y2):
global ctx
ctx.beginPath()
ctx.lineWidth = 1
# (x1, y1)
ctx.moveTo(x1, y1)
# (x2, y2)
ctx.lineTo(x2, y2)
# , "rgb(0, 0, 255)"
ctx.strokeStyle = "blue"
ctx.stroke()
ctx.closePath()
# draw_line()
# (10, 10) (410, 310)
draw_line(10, 10, 410, 10)
draw_line(10, 310, 410, 310)
draw_line(10, 10, 10, 310)
draw_line(410, 10, 410, 310)
# context.arc(x,y,r,sAngle,eAngle,counterclockwise)
# arc( x, y, , , )
circle_x = 10 + 400/2
circle_y = 10 + 300/2
ctx.beginPath()
ctx.arc(circle_x, circle_y, 80, 0, math.pi*2, True)
ctx.strokeStyle = 'rgb(255, 0, 0)'
ctx.stroke()
ctx.fillStyle = 'rgb(255, 0, 0)'
ctx.fill()
ctx.closePath()
</script>
</pre>
<canvas id="japanflag3" width="650" height="450"></canvas>
<script type="text/python">
from browser import document
import math
canvas = document["japanflag3"]
ctx = canvas.getContext("2d")
# ctx
# , (x1, y1) , (x2, y2)
def draw_line(x1, y1, x2, y2):
global ctx
ctx.beginPath()
ctx.lineWidth = 1
# (x1, y1)
ctx.moveTo(x1, y1)
# (x2, y2)
ctx.lineTo(x2, y2)
# , "rgb(0, 0, 255)"
ctx.strokeStyle = "blue"
ctx.stroke()
ctx.closePath()
# draw_line()
# (10, 10) (410, 310)
draw_line(10, 10, 410, 10)
draw_line(10, 310, 410, 310)
draw_line(10, 10, 10, 310)
draw_line(410, 10, 410, 310)
# context.arc(x,y,r,sAngle,eAngle,counterclockwise)
# arc( x, y, , , )
circle_x = 10 + 400/2
circle_y = 10 + 300/2
ctx.beginPath()
ctx.arc(circle_x, circle_y, 80, 0, math.pi*2, True)
ctx.strokeStyle = 'rgb(255, 0, 0)'
ctx.stroke()
ctx.fillStyle = 'rgb(255, 0, 0)'
ctx.fill()
ctx.closePath()
</script>
<p>:</p>
<pre class="brush: python">
<canvas id="japanflag4" width="650" height="450"></canvas>
<script type="text/python">
# doc
from browser import document as doc
import math
canvas = doc["japanflag4"]
ctx = canvas.getContext("2d")
# ctx
# , (x1, y1) , (x2, y2)
def draw_line(ctx, x1, y1, x2, y2):
ctx.beginPath()
ctx.lineWidth = 1
# (x1, y1)
ctx.moveTo(x1, y1)
# (x2, y2)
ctx.lineTo(x2, y2)
# , "rgb(0, 0, 255)"
ctx.strokeStyle = "blue"
ctx.stroke()
ctx.closePath()
# draw_frame draw_line()
def draw_frame(ctx, x, y, w):
# draw_line()
# (x, y) (410, 310)
draw_line(ctx, x, y, w*3/2+x, y)
draw_line(ctx, x, w+y, w*3/2+x, w+y)
draw_line(ctx, x, y, x, w+y)
draw_line(ctx, w*3/2+x, y, w*3/2+x, w+y)
def draw_circle(x, y, r, fill=None):
global ctx
ctx.beginPath()
ctx.arc(x, y, r, 0, math.pi*2, True)
if fill == None:
ctx.fillStyle = 'rgb(255, 0, 0)'
ctx.fill()
else:
ctx.strokeStyle = "rgb(255, 0, 0)"
ctx.stroke()
ctx.closePath()
# draw_frame()
width = 400
draw_frame(ctx, 10, 10, width)
x_center = 10 + width*3/2/2
y_center = 10 + width/2
radius = width*3/5/2
draw_circle(x_center, y_center, radius)
</script>
</pre>
<canvas id="japanflag4" width="650" height="450"></canvas>
<script type="text/python">
# doc
from browser import document as doc
import math
canvas = doc["japanflag4"]
ctx = canvas.getContext("2d")
# ctx
# , (x1, y1) , (x2, y2)
def draw_line(ctx, x1, y1, x2, y2):
ctx.beginPath()
ctx.lineWidth = 1
# (x1, y1)
ctx.moveTo(x1, y1)
# (x2, y2)
ctx.lineTo(x2, y2)
# , "rgb(0, 0, 255)"
ctx.strokeStyle = "blue"
ctx.stroke()
ctx.closePath()
# draw_frame draw_line()
def draw_frame(ctx, x, y, w):
# draw_line()
# (x, y) (410, 310)
draw_line(ctx, x, y, w*3/2+x, y)
draw_line(ctx, x, w+y, w*3/2+x, w+y)
draw_line(ctx, x, y, x, w+y)
draw_line(ctx, w*3/2+x, y, w*3/2+x, w+y)
def draw_circle(x, y, r, fill=None):
global ctx
ctx.beginPath()
ctx.arc(x, y, r, 0, math.pi*2, True)
if fill == None:
ctx.fillStyle = 'rgb(255, 0, 0)'
ctx.fill()
else:
ctx.strokeStyle = "rgb(255, 0, 0)"
ctx.stroke()
ctx.closePath()
# draw_frame()
width = 400
draw_frame(ctx, 10, 10, width)
x_center = 10 + width*3/2/2
y_center = 10 + width/2
radius = width*3/5/2
draw_circle(x_center, y_center, radius)
</script>
<p>:</p>
<canvas id="rocflag" width="650" height="450"></canvas>
<script type="text/python3">
# doc
from browser import document as doc
import math
canvas = doc["rocflag"]
ctx = canvas.getContext("2d")
# , x , y canvas.height
# ctx.setTransform(1, 0, 0, -1, 0, canvas.height)
# canvas
flag_w = canvas.width
flag_h = canvas.height
circle_x = flag_w/4
circle_y = flag_h/4
ctx.fillStyle='rgb(255, 0, 0)'
ctx.fillRect(0,0,flag_w,flag_h)
ctx.fillStyle='rgb(0, 0, 150)'
ctx.fillRect(0,0,flag_w/2,flag_h/2)
ctx.beginPath()
star_radius = flag_w/8
angle = 0
for i in range(24):
angle += 5*math.pi*2/12
toX = circle_x + math.cos(angle)*star_radius
toY = circle_y + math.sin(angle)*star_radius
# i 0 toX, toY, lineTo
if (i):
ctx.lineTo(toX, toY)
else:
ctx.moveTo(toX, toY)
ctx.closePath()
ctx.fillStyle = '#fff'
ctx.fill()
ctx.beginPath()
ctx.arc(circle_x, circle_y, flag_w*17/240, 0, math.pi*2, True)
ctx.closePath()
ctx.fillStyle = 'rgb(0, 0, 149)'
ctx.fill()
ctx.beginPath()
ctx.arc(circle_x, circle_y, flag_w/16, 0, math.pi*2, True)
ctx.closePath()
ctx.fillStyle = '#fff'
ctx.fill()
</script>
<pre class="brush: python">
<canvas id="rocflag" width="650" height="450"></canvas>
<script type="text/python3">
# doc
from browser import document as doc
import math
canvas = doc["rocflag"]
ctx = canvas.getContext("2d")
# , x , y canvas.height
# ctx.setTransform(1, 0, 0, -1, 0, canvas.height)
# canvas
flag_w = canvas.width
flag_h = canvas.height
circle_x = flag_w/4
circle_y = flag_h/4
ctx.fillStyle='rgb(255, 0, 0)'
ctx.fillRect(0,0,flag_w,flag_h)
ctx.fillStyle='rgb(0, 0, 150)'
ctx.fillRect(0,0,flag_w/2,flag_h/2)
ctx.beginPath()
star_radius = flag_w/8
angle = 0
for i in range(24):
angle += 5*math.pi*2/12
toX = circle_x + math.cos(angle)*star_radius
toY = circle_y + math.sin(angle)*star_radius
# i 0 toX, toY, lineTo
if (i):
ctx.lineTo(toX, toY)
else:
ctx.moveTo(toX, toY)
ctx.closePath()
ctx.fillStyle = '#fff'
ctx.fill()
ctx.beginPath()
ctx.arc(circle_x, circle_y, flag_w*17/240, 0, math.pi*2, True)
ctx.closePath()
ctx.fillStyle = 'rgb(0, 0, 149)'
ctx.fill()
ctx.beginPath()
ctx.arc(circle_x, circle_y, flag_w/16, 0, math.pi*2, True)
ctx.closePath()
ctx.fillStyle = '#fff'
ctx.fill()
</script>
</pre>
</div>
<!-- /.entry-content -->
</article>
</section>
</div>
<div class="col-sm-3" id="sidebar">
<aside>
<section class="well well-sm">
<ul class="list-group list-group-flush">
<li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4>
<ul class="list-group" id="recentposts">
<li class="list-group-item">
<a href="./<API key>.html">
2016fallcp
</a>
</li>
<li class="list-group-item">
<a href="./w16.html">
W16
</a>
</li>
<li class="list-group-item">
<a href="./w15.html">
w15
</a>
</li>
<li class="list-group-item">
<a href="./w13.html">
W13
</a>
</li>
<li class="list-group-item">
<a href="./w12.html">
w12
</a>
</li>
</ul>
</li>
<li class="list-group-item"><a href="./categories.html"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Categories</span></h4></a>
<ul class="list-group" id="categories">
<li class="list-group-item">
<a href="./category/course.html">
<i class="fa fa-folder-open fa-lg"></i> Course
</a>
</li>
<li class="list-group-item">
<a href="./category/misc.html">
<i class="fa fa-folder-open fa-lg"></i> Misc
</a>
</li>
</ul>
</li>
<li class="list-group-item"><a href="./tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a>
<ul class="list-group list-inline tagcloud" id="tags">
</ul>
</li>
<li class="list-group-item"><h4><i class="fa <API key> fa-lg"></i><span class="icon-label">Links</span></h4>
<ul class="list-group" id="links">
<li class="list-group-item">
<a href="http://getpelican.com/" target="_blank">
Pelican
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/DandyDev/pelican-bootstrap3/" target="_blank">
pelican-bootstrap3
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/getpelican/pelican-plugins" target="_blank">
pelican-plugins
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/Tipue/Tipue-Search" target="_blank">
Tipue search
</a>
</li>
</ul>
</li>
</ul>
</section>
</aside>
</div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2016 KMOL
· Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>,
<a href="http://docs.getpelican.com/" target="_blank">Pelican</a>,
<a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="./theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="./theme/js/bootstrap.min.js"></script>
<script src="./theme/js/respond.min.js"></script>
</body>
</html> |
package info.nightscout.androidaps.plugins.pump.omnipod;
import android.os.Looper;
import org.joda.time.DateTimeZone;
import org.joda.time.tz.UTCProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import dagger.android.AndroidInjector;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.interfaces.<API key>;
import info.nightscout.androidaps.interfaces.<API key>;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.AAPSLoggerTest;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.omnipod.manager.AapsOmnipodManager;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
public class <API key> {
@Mock HasAndroidInjector injector;
AAPSLogger aapsLogger = new AAPSLoggerTest();
RxBusWrapper rxBusWrapper = new RxBusWrapper();
@Mock ResourceHelper resourceHelper;
@Mock(answer = Answers.RETURNS_DEEP_STUBS) <API key> <API key>;
@Mock AapsOmnipodManager aapsOmnipodManager;
@Mock <API key> <API key>;
@Mock RileyLinkUtil rileyLinkUtil;
@Test
@PrepareForTest(Looper.class)
public <T> void <API key>() {
DateTimeZone.setProvider(new UTCProvider());
// mock all the things
PowerMockito.mockStatic(Looper.class);
OmnipodPumpPlugin plugin = new OmnipodPumpPlugin(injector, aapsLogger, rxBusWrapper, null,
resourceHelper, <API key>, null, null, aapsOmnipodManager, <API key>,
null, null, null, null, null,
rileyLinkUtil, null, null
);
when(<API key>.getActiveTreatments().<API key>(anyLong())).thenReturn(null);
when(rileyLinkUtil.getRileyLinkHistory()).thenReturn(new ArrayList<>());
when(injector.androidInjector()).thenReturn(new AndroidInjector<Object>() {
@Override public void inject(Object instance) {
}
});
Profile profile = mock(Profile.class);
// always return a PumpEnactResult containing same rate and duration as input
when(aapsOmnipodManager.setTemporaryBasal(any(TempBasalPair.class))).thenAnswer(
invocation -> {
TempBasalPair pair = invocation.getArgument(0);
PumpEnactResult result = new PumpEnactResult(injector);
result.absolute(pair.getInsulinRate());
result.duration(pair.getDurationMinutes());
return result;
});
// Given standard basal
when(profile.getBasal()).thenReturn(0.5d);
// When
PumpEnactResult result1 = plugin.setTempBasalPercent(80, 30, profile, false);
PumpEnactResult result2 = plugin.setTempBasalPercent(5000, 30000, profile, false);
PumpEnactResult result3 = plugin.setTempBasalPercent(0, 30, profile, false);
PumpEnactResult result4 = plugin.setTempBasalPercent(0, 0, profile, false);
PumpEnactResult result5 = plugin.setTempBasalPercent(-50, 60, profile, false);
// Then return correct values
assertEquals(result1.absolute, 0.4d, 0.01d);
assertEquals(result1.duration, 30);
assertEquals(result2.absolute, 25d, 0.01d);
assertEquals(result2.duration, 30000);
assertEquals(result3.absolute, 0d, 0.01d);
assertEquals(result3.duration, 30);
assertEquals(result4.absolute, -1d, 0.01d);
assertEquals(result4.duration, -1);
// this is validated downstream, see <API key>
assertEquals(result5.absolute, -0.25d, 0.01d);
assertEquals(result5.duration, 60);
// Given zero basal
when(profile.getBasal()).thenReturn(0d);
// When
result1 = plugin.setTempBasalPercent(8000, 90, profile, false);
result2 = plugin.setTempBasalPercent(0, 0, profile, false);
// Then return zero values
assertEquals(result1.absolute, 0d, 0.01d);
assertEquals(result1.duration, 90);
assertEquals(result2.absolute, -1d, 0.01d);
assertEquals(result2.duration, -1);
// Given unhealthy basal
when(profile.getBasal()).thenReturn(500d);
// When treatment
result1 = plugin.setTempBasalPercent(80, 30, profile, false);
// Then return sane values
assertEquals(result1.absolute, PumpType.Insulet_Omnipod.<API key>(500d * 0.8), 0.01d);
assertEquals(result1.duration, 30);
// Given weird basal
when(profile.getBasal()).thenReturn(1.234567d);
// When treatment
result1 = plugin.setTempBasalPercent(280, 600, profile, false);
// Then return sane values
assertEquals(result1.absolute, 3.4567876, 0.01d);
assertEquals(result1.duration, 600);
// Given negative basal
when(profile.getBasal()).thenReturn(-1.234567d);
// When treatment
result1 = plugin.setTempBasalPercent(280, 510, profile, false);
// Then return negative value (this is validated further downstream, see <API key>)
assertEquals(result1.absolute, -3.4567876, 0.01d);
assertEquals(result1.duration, 510);
}
} |
#include "UI.h"
#include <vpvl2/vpvl2.h>
#include <vpvl2/extensions/Archive.h>
#include <vpvl2/extensions/AudioSource.h>
#include <vpvl2/extensions/World.h>
#include <vpvl2/extensions/gl/SimpleShadowMap.h>
#include <vpvl2/qt/ApplicationContext.h>
#include <vpvl2/qt/CustomGLContext.h>
#include <vpvl2/qt/DebugDrawer.h>
#include <vpvl2/qt/TextureDrawHelper.h>
#include <vpvl2/qt/Util.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-<API key>"
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include <QApplication>
#include <QDesktopWidget>
#pragma clang diagnostic pop
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QtConcurrent/QtConcurrent>
#endif
#if defined(VPVL2_LINK_ASSIMP3) || defined(VPVL2_LINK_ASSIMP)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#if defined(VPVL2_LINK_ASSIMP3)
#include <assimp/Importer.hpp>
#elif defined(VPVL2_LINK_ASSIMP)
#include <assimp/assimp.hpp>
#include <assimp/DefaultLogger.h>
#include <assimp/aiPostProcess.h>
#include <assimp/aiScene.h>
#endif
#pragma clang diagnostic pop
#endif
#include <BulletCollision/CollisionShapes/btStaticPlaneShape.h>
#include <BulletDynamics/Dynamics/<API key>.h>
#include <BulletDynamics/Dynamics/btRigidBody.h>
#include <glm/gtc/matrix_transform.hpp>
/* internal headers */
#include "vpvl2/pmx/Bone.h"
#include "vpvl2/pmx/Joint.h"
#include "vpvl2/pmx/Label.h"
#include "vpvl2/pmx/Material.h"
#include "vpvl2/pmx/Model.h"
#include "vpvl2/pmx/Morph.h"
#include "vpvl2/pmx/RigidBody.h"
#include "vpvl2/pmx/Vertex.h"
#include "vpvl2/asset/Model.h"
#include "vpvl2/pmd2/Model.h"
#include "vpvl2/vmd/Motion.h"
#ifdef <API key>
/* to cast IEffect#internalPointer and IEffect#internalContext */
#include <Cg/cg.h>
#include <Cg/cgGL.h>
#endif
using namespace vpvl2;
using namespace vpvl2::qt;
QDebug operator<<(QDebug debug, const Vector3 &v)
{
debug.nospace() << "(x=" << v.x() << ", y=" << v.y() << ", z=" << v.z() << ")";
return debug;
}
QDebug operator<<(QDebug debug, const Color &v)
{
debug.nospace() << "(r=" << v.x() << ", g=" << v.y() << ", b=" << v.z() << ", a=" << v.w() << ")";
return debug;
}
QDebug operator<<(QDebug debug, const IString *str)
{
if (str) {
debug.nospace() << Util::toQString(static_cast<const String *>(str)->value());
}
else {
debug.nospace() << "(null)";
}
return debug;
}
QDebug operator<<(QDebug debug, const pmx::Bone *bone)
{
if (!bone) {
debug.nospace() << "Bone is null";
return debug.space();
}
debug.nospace();
debug << "Bone id = " << bone->index();
debug << "\n";
debug << " name = " << bone->name(IEncoding::kJapanese);
debug << "\n";
debug << " english = " << bone->name(IEncoding::kEnglish);
debug << "\n";
debug << " origin = " << bone->origin();
debug << "\n";
if (bone->parentBoneRef()) {
debug << " parent = " << bone->parentBoneRef()->name(IEncoding::kJapanese);
debug << "\n";
}
debug << " index = " << bone->layerIndex();
debug << "\n";
debug << " offset = " << bone->origin();
debug << "\n";
if (bone-><API key>()) {
debug << " targetBone = " << bone->effectorBoneRef()->name(IEncoding::kJapanese);
debug << "\n";
debug << " constraintAngle = " << bone->constraintAngle();
debug << "\n";
}
if (bone-><API key>() || bone->hasInherentRotation()) {
debug << " <API key> = " << bone-><API key>()->name(IEncoding::kJapanese);
debug << "\n";
debug << " weight = " << bone->weight();
debug << "\n";
}
if (bone->hasFixedAxes()) {
debug << " axis = " << bone->axis();
debug << "\n";
}
if (bone->hasLocalAxes()) {
debug << " axisX = " << bone->axisX();
debug << "\n";
debug << " axisZ = " << bone->axisZ();
debug << "\n";
}
return debug.space();
}
QDebug operator<<(QDebug debug, const pmx::Material *material)
{
if (!material) {
debug.nospace() << "Material is null";
return debug.space();
}
debug.nospace();
debug << "Material id = " << material->index();
debug << "\n";
debug << " name = " << material->name(IEncoding::kJapanese);
debug << "\n";
debug << " english = " << material->name(IEncoding::kEnglish);
debug << "\n";
debug << " mainTexture = " << material->mainTexture();
debug << "\n";
debug << " sphereTexture = " << material->sphereTexture();
debug << "\n";
debug << " toonTexture = " << material->toonTexture();
debug << "\n";
debug << " ambient = " << material->ambient();
debug << "\n";
debug << " diffuse = " << material->diffuse();
debug << "\n";
debug << " specular = " << material->specular();
debug << "\n";
debug << " edgeColor = " << material->edgeColor();
debug << "\n";
debug << " shininess = " << material->shininess();
debug << "\n";
debug << " edgeSize = " << material->edgeSize();
debug << "\n";
debug << " indices = " << material->indexRange().count;
debug << "\n";
debug << " <API key> = " << material-><API key>();
debug << "\n";
debug << " isCullingDisabled = " << material->isCullingDisabled();
debug << "\n";
debug << " hasShadow = " << material->hasShadow();
debug << "\n";
debug << " isSelfShadowEnabled = " << material->isSelfShadowEnabled();
debug << "\n";
debug << " isEdgeEnabled = " << material->isEdgeEnabled();
debug << "\n";
switch (material-><API key>()) {
case pmx::Material::kAddTexture:
debug << " sphere = add";
break;
case pmx::Material::kMultTexture:
debug << " sphere = modulate";
break;
case pmx::Material::kNone:
debug << " sphere = none";
break;
case pmx::Material::kSubTexture:
debug << " sphere = subtexture";
break;
case pmx::Material::<API key>:
break;
}
debug << "\n";
return debug.space();
}
QDebug operator<<(QDebug debug, const pmx::Morph *morph)
{
if (!morph) {
debug.nospace() << "Morph is null";
return debug.space();
}
debug.nospace();
debug << "Morph id = " << morph->index();
debug << "\n";
debug << " name = " << morph->name(IEncoding::kJapanese);
debug << "\n";
debug << " english = " << morph->name(IEncoding::kEnglish);
debug << "\n";
debug << " weight = " << morph->weight();
debug << "\n";
debug << " category = ";
switch (morph->category()) {
case IMorph::kBase:
debug << "kBase";
break;
case IMorph::kEyeblow:
debug << "kEyeblow";
break;
case IMorph::kEye:
debug << "kEye";
break;
case IMorph::kLip:
debug << "kLip";
break;
case IMorph::kOther:
debug << "kOther";
break;
default:
debug << "(unknown)";
break;
}
debug << "\n";
debug << " type = ";
switch (morph->type()) {
case IMorph::kGroupMorph:
debug << "kGroup";
break;
case IMorph::kVertexMorph:
debug << "kVertex";
break;
case IMorph::kBoneMorph:
debug << "kBone";
break;
case IMorph::kTexCoordMorph:
debug << "kTexCoord";
break;
case IMorph::kUVA1Morph:
debug << "kUVA1";
break;
case IMorph::kUVA2Morph:
debug << "kUVA2";
break;
case IMorph::kUVA3Morph:
debug << "kUVA3";
break;
case IMorph::kUVA4Morph:
debug << "kUVA4";
break;
case IMorph::kMaterialMorph:
debug << "kMaterial";
break;
case IMorph::kFlipMorph:
debug << "kFlip";
break;
case IMorph::kImpulseMorph:
debug << "kImpulse";
break;
default:
debug << "(unknown)";
break;
}
debug << "\n";
return debug.space();
}
QDebug operator<<(QDebug debug, const pmx::Label *label)
{
if (!label) {
debug.nospace() << "Label is null";
return debug.space();
}
debug.nospace();
debug << "Label id = " << label->index();
debug << "\n";
debug << " name = " << label->name(IEncoding::kJapanese);
debug << "\n";
debug << " english = " << label->name(IEncoding::kEnglish);
debug << "\n";
debug << " isSpecial = " << label->isSpecial();
debug << "\n";
debug << " count = " << label->count();
debug << "\n";
for (int i = 0; i < label->count(); i++) {
if (IBone *bone = label->boneRef(i)) {
debug << " bone = " << bone->name(IEncoding::kJapanese);
}
else if (IMorph *morph = label->morphRef(i)) {
debug << " morph = " << morph->name(IEncoding::kJapanese);
}
debug << "\n";
}
return debug.space();
}
QDebug operator<<(QDebug debug, const pmx::RigidBody *body)
{
if (!body) {
debug.nospace() << "RigidBody is null";
return debug.space();
}
debug.nospace();
debug << "RigidBody id = " << body->index();
debug << "\n";
debug << " name = " << body->name(IEncoding::kJapanese);
debug << "\n";
debug << " english = " << body->name(IEncoding::kEnglish);
debug << "\n";
debug << " size = " << body->size();
debug << "\n";
debug << " position = " << body->position();
debug << "\n";
debug << " rotation = " << body->rotation();
debug << "\n";
debug << " mass = " << body->mass();
debug << "\n";
debug << " linearDamping = " << body->linearDamping();
debug << "\n";
debug << " angularDamping = " << body->angularDamping();
debug << "\n";
debug << " restitution = " << body->restitution();
debug << "\n";
debug << " friction = " << body->friction();
debug << "\n";
debug << " groupID = " << body->groupID();
debug << "\n";
debug << " collisionGroupMask = " << body->collisionGroupMask();
debug << "\n";
debug << " collisionGroupID = " << body->collisionGroupID();
debug << "\n";
return debug.space();
}
QDebug operator<<(QDebug debug, const pmx::Joint *joint)
{
if (!joint) {
debug.nospace() << "Joint is null";
return debug.space();
}
debug.nospace();
debug << "Joint id = " << joint->index();
debug << "\n";
debug << " name = " << joint->name(IEncoding::kJapanese);
debug << "\n";
debug << " english = " << joint->name(IEncoding::kEnglish);
debug << "\n";
debug << " position = " << joint->position();
debug << "\n";
debug << " rotation = " << joint->rotation();
debug << "\n";
debug << " positionLowerLimit = " << joint->positionLowerLimit();
debug << "\n";
debug << " positionUpperLimit = " << joint->positionUpperLimit();
debug << "\n";
debug << " rotationLowerLimit = " << joint->rotationLowerLimit();
debug << "\n";
debug << " rotationUpperLimit = " << joint->rotationUpperLimit();
debug << "\n";
debug << " positionStiffness = " << joint->positionStiffness();
debug << "\n";
debug << " rotationStiffness = " << joint->rotationStiffness();
debug << "\n";
if (IRigidBody *rigidBodyRef = joint->rigidBody1Ref()) {
debug << " rigidBody1 = " << rigidBodyRef->name(IEncoding::kJapanese);
debug << "\n";
}
if (IRigidBody *rigidBodyRef = joint->rigidBody2Ref()) {
debug << " rigidBody2 = " << rigidBodyRef->name(IEncoding::kJapanese);
debug << "\n";
}
return debug.space();
}
namespace vpvl2
{
namespace render
{
namespace qt
{
const QString kWindowTitle = "MMDAI2 rendering test program with Qt (FPS:%1)";
static void UIToggleFlags(int target, int &flags)
{
if ((flags & target) != target) {
flags -= target;
}
else {
flags += target;
}
}
template<typename T>
static void UIWaitFor(const QFuture<T> &future)
{
while (!future.isResultReadyAt(0)) {
qApp->processEvents(QEventLoop::<API key>);
}
}
UI::UI(const QGLFormat &format)
: QGLWidget(new CustomGLContext(format), 0),
m_world(new World()),
m_scene(new Scene(false)),
m_audioSource(new AudioSource()),
m_manualTimeIndex(0),
m_debugFlags(0),
m_automaticMotion(false)
{
setMouseTracking(true);
setWindowTitle(kWindowTitle.arg("N/A"));
}
UI::~UI()
{
#ifdef VPVL2_LINK_ASSIMP
Assimp::DefaultLogger::kill();
#endif
m_audioSource.reset();
m_world.take();
m_dictionary.releaseAll();
}
void UI::load(const QString &filename)
{
Util::loadDictionary(&m_dictionary);
m_encoding.reset(new Encoding(&m_dictionary));
m_settings.reset(new QSettings(filename, QSettings::IniFormat, this));
m_settings->setIniCodec("UTF-8");
m_factory.reset(new Factory(m_encoding.data()));
QHash<QString, QString> settings;
foreach (const QString &key, m_settings->allKeys()) {
const QString &value = m_settings->value(key).toString();
settings.insert(key, value);
m_stringMapRef.insert(std::make_pair(Util::fromQString(key), Util::fromQString(value)));
}
}
void UI::rotate(float x, float y)
{
ICamera *camera = m_scene->cameraRef();
Vector3 angle = camera->angle();
angle.setX(angle.x() + x);
angle.setY(angle.y() + y);
camera->setAngle(angle);
}
void UI::translate(float x, float y)
{
ICamera *camera = m_scene->cameraRef();
const Vector3 &diff = camera->modelViewTransform() * Vector3(x, y, 0);
const Vector3 &position = camera->lookAt() + diff;
camera->setLookAt(position + diff);
}
void UI::closeEvent(QCloseEvent *event)
{
QThreadPool *pool = QThreadPool::globalInstance();
if (pool->activeThreadCount() > 0)
pool->waitForDone();
event->accept();
}
void UI::initializeGL()
{
GLenum err = 0;
if (!Scene::initialize(&err)) {
qFatal("Cannot initialize GLEW: %s", glewGetErrorString(err));
}
QGLFormat f = format(); Q_UNUSED(f);
qDebug("GL_VERSION: %s", glGetString(GL_VERSION));
qDebug("GL_VENDOR: %s", glGetString(GL_VENDOR));
qDebug("GL_RENDERER: %s", glGetString(GL_RENDERER));
qDebug("<API key>: %s", glGetString(<API key>));
const QSize s(m_settings->value("window.width", 960).toInt(), m_settings->value("window.height", 640).toInt());
const QSize &margin = qApp->desktop()->screenGeometry().size() - s;
move((margin / 2).width(), (margin / 2).height());
resize(s);
setMinimumSize(640, 480);
<API key>.reset(new ApplicationContext(m_scene.data(), m_encoding.data(), &m_stringMapRef));
<API key>->initialize(m_settings->value("enable.debug", false).toBool());
<API key>-><API key>(glm::vec2(width(), height()));
#ifdef VPVL2_LINK_ATB
ui::AntTweakBar::initialize();
m_controller.create(<API key>.data());
#endif
m_scene->setPreferredFPS(qMax(m_settings->value("scene.fps", 30).toFloat(), Scene::defaultFPS()));
if (m_settings->value("enable.opencl", false).toBool()) {
m_scene->setAccelerationType(Scene::<API key>);
}
else if (m_settings->value("enable.vss", false).toBool()) {
m_scene->setAccelerationType(Scene::<API key>);
}
ICamera *camera = m_scene->cameraRef();
camera->setZNear(qMax(m_settings->value("scene.znear", 0.1f).toFloat(), 0.1f));
camera->setZFar(qMax(m_settings->value("scene.zfar", 10000.0).toFloat(), 100.0f));
ILight *light = m_scene->lightRef();
light->setToonEnable(m_settings->value("enable.toon", true).toBool());
m_helper.reset(new TextureDrawHelper(size()));
m_helper->load(QRectF(0, 0, 1, 1));
m_helper->resize(size());
m_drawer.reset(new DebugDrawer(<API key>.data(), &m_stringMapRef));
m_drawer->load();
if (m_settings->value("enable.sm", false).toBool() && Scene::<API key>()) {
<API key>->createShadowMap(Vector3(2048, 2048, 0));
}
if (loadScene()) {
const QString &path = m_settings->value("audio.file").toString();
if (!m_audioSource->load(path.toUtf8().constData())) {
qDebug("Cannot load audio file: %s", m_audioSource->errorString());
}
else if (!m_audioSource->play()) {
qDebug("Cannot play audio source: %s", m_audioSource->errorString());
}
unsigned int interval = m_settings->value("window.fps", 30).toUInt();
m_timeHolder.setUpdateInterval(btSelect(interval, interval / 1.0f, 60.0f));
m_updateTimer.start(int(btSelect(interval, 1000.0f / interval, 0.0f)), this);
m_timeHolder.start();
}
else {
qFatal("Unable to load scene");
}
}
void UI::timerEvent(QTimerEvent * /* event */)
{
if (m_automaticMotion) {
double offset, latency;
m_audioSource->getOffsetLatency(offset, latency);
if (offset != 0 || latency != 0) {
qDebug("offset: %.2f", offset + latency);
}
m_timeHolder.saveElapsed(qRound64(offset + latency));
seekScene(m_timeHolder.timeIndex(), m_timeHolder.delta());
}
<API key>-><API key>(glm::vec2(width(), height()));
m_scene->update(Scene::kUpdateAll);
setWindowTitle(kWindowTitle.arg(m_counter.value()));
updateGL();
}
void UI::seekScene(const IKeyframe::TimeIndex &timeIndex, const IKeyframe::TimeIndex &delta)
{
m_scene->seek(timeIndex, Scene::kUpdateAll);
if (m_scene->isReachedTo(m_scene->duration())) {
m_scene->seek(0, Scene::kUpdateAll);
m_scene->update(Scene::kResetMotionState);
m_timeHolder.reset();
}
m_world->stepSimulation(delta);
}
void UI::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_A:
UIToggleFlags(btIDebugDraw::DBG_DrawAabb, m_debugFlags);
break;
case Qt::Key_C:
UIToggleFlags(btIDebugDraw::DBG_DrawConstraints, m_debugFlags);
break;
case Qt::Key_L:
UIToggleFlags(btIDebugDraw::<API key>, m_debugFlags);
break;
case Qt::Key_N:
seekScene(++m_manualTimeIndex, 1);
break;
case Qt::Key_P:
seekScene(qMax(--m_manualTimeIndex, IKeyframe::TimeIndex(0)), 1);
break;
case Qt::Key_W:
UIToggleFlags(btIDebugDraw::DBG_DrawWireframe, m_debugFlags);
break;
}
}
void UI::mousePressEvent(QMouseEvent *event)
{
m_prevPos = event->pos();
#ifdef VPVL2_LINK_ATB
Qt::MouseButtons buttons = event->buttons();
if (buttons & Qt::LeftButton) {
m_controller.handleAction(IApplicationContext::<API key>, true);
}
if (buttons & Qt::MiddleButton) {
m_controller.handleAction(IApplicationContext::<API key>, true);
}
if (buttons & Qt::RightButton) {
m_controller.handleAction(IApplicationContext::<API key>, true);
}
#endif
setMousePositions(event);
}
void UI::mouseMoveEvent(QMouseEvent *event)
{
Qt::MouseButtons buttons = event->buttons();
bool handled = false;
#ifdef VPVL2_LINK_ATB
handled = m_controller.handleMotion(event->x(), event->y());
#endif
if (!handled && (buttons & Qt::LeftButton)) {
const QPoint &diff = event->pos() - m_prevPos;
Qt::KeyboardModifiers modifiers = event->modifiers();
if (modifiers & Qt::ShiftModifier) {
translate(diff.x() * -0.1f, diff.y() * 0.1f);
}
else {
rotate(diff.y() * 0.5f, diff.x() * 0.5f);
}
m_prevPos = event->pos();
}
setMousePositions(event);
}
void UI::mouseReleaseEvent(QMouseEvent *event)
{
#ifdef VPVL2_LINK_ATB
m_controller.handleAction(IApplicationContext::<API key>, false);
m_controller.handleAction(IApplicationContext::<API key>, false);
m_controller.handleAction(IApplicationContext::<API key>, false);
#endif
setMousePositions(event);
}
void UI::wheelEvent(QWheelEvent *event)
{
Qt::KeyboardModifiers modifiers = event->modifiers();
ICamera *camera = m_scene->cameraRef();
int delta = 0;
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
delta = event->pixelDelta().y();
#else
delta = event->delta();
#endif
bool handled = false;
#ifdef VPVL2_LINK_ATB
handled = m_controller.handleWheel(delta);
#endif
if (!handled) {
if (modifiers & Qt::ControlModifier && modifiers & Qt::ShiftModifier) {
const qreal step = 1.0;
camera->setFov(qMax(delta > 0 ? camera->fov() - step : camera->fov() + step, 0.0));
}
else {
qreal step = 4.0;
if (modifiers & Qt::ControlModifier) {
step *= 5.0f;
}
else if (modifiers & Qt::ShiftModifier) {
step *= 0.2f;
}
if (step != 0.0f) {
camera->setDistance(delta > 0 ? camera->distance() - step : camera->distance() + step);
}
}
}
}
void UI::resizeGL(int w, int h)
{
glViewport(0, 0, w, h);
if (m_helper) {
m_helper->resize(QSize(w, h));
}
#ifdef VPVL2_LINK_ASSIMP
m_controller.resize(w, h);
#endif
}
void UI::paintGL()
{
if (<API key>) {
<API key>->renderShadowMap();
<API key>->renderOffscreen();
<API key>-><API key>(glm::vec2(width(), height()));
renderWindow();
if (IShadowMap *shadowMap = m_scene->shadowMapRef()) {
if (const GLuint *bufferRef = static_cast<GLuint *>(shadowMap->textureRef())) {
m_helper->draw(QRectF(0, 0, 256, 256), *bufferRef);
}
}
m_drawer->drawWorld(m_world.data(), m_debugFlags);
if (m_audioSource->isRunning()) {
m_audioSource->update();
double offset, latency;
m_audioSource->getOffsetLatency(offset, latency);
qDebug("elapsed:%.1f timeIndex:%.2f offset:%.2f latency:%2f",
m_timeHolder.elapsed(),
m_timeHolder.timeIndex(),
offset,
latency);
}
#ifdef VPVL2_LINK_ATB
m_controller.render();
#endif
}
else {
glViewport(0, 0, width(), height());
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | <API key>);
}
bool flushed; /* unused */
m_counter.update(m_timeHolder.elapsed(), flushed);
}
void UI::renderWindow()
{
Array<IRenderEngine *> <API key>, enginesForStandard, <API key>;
Hash<HashPtr, IEffect *> nextPostEffects;
m_scene-><API key>(<API key>,
enginesForStandard,
<API key>,
nextPostEffects);
for (int i = <API key>.count() - 1; i >= 0; i
IRenderEngine *engine = <API key>[i];
engine->update();
engine->preparePostProcess();
}
glViewport(0, 0, width(), height());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | <API key>);
for (int i = 0, nengines = <API key>.count(); i < nengines; i++) {
IRenderEngine *engine = <API key>[i];
engine->performPreProcess();
}
for (int i = 0, nengines = enginesForStandard.count(); i < nengines; i++) {
IRenderEngine *engine = enginesForStandard[i];
engine->renderModel();
engine->renderEdge();
if (!m_scene->shadowMapRef()) {
engine->renderShadow();
}
}
for (int i = 0, nengines = <API key>.count(); i < nengines; i++) {
IRenderEngine *engine = <API key>[i];
IEffect *const *nextPostEffect = nextPostEffects[engine];
engine->performPostProcess(*nextPostEffect);
}
}
void UI::setMousePositions(QMouseEvent *event)
{
#ifdef <API key>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
const QPointF &pos = event->localPos();
#else
const QPointF &pos = event->posF();
#endif
const QSizeF &size = geometry().size() / 2;
const qreal w = size.width(), h = size.height();
const glm::vec2 value((pos.x() - w) / w, (pos.y() - h) / -h);
Qt::MouseButtons buttons = event->buttons();
<API key>->setMousePosition(value, buttons & Qt::LeftButton, IApplicationContext::<API key>);
<API key>->setMousePosition(value, buttons & Qt::MiddleButton, IApplicationContext::<API key>);
<API key>->setMousePosition(value, buttons & Qt::RightButton, IApplicationContext::<API key>);
<API key>->setMousePosition(value, false, IApplicationContext::<API key>);
#else
Q_UNUSED(event);
#endif
}
bool UI::loadScene()
{
#ifdef VPVL2_LINK_ASSIMP
Assimp::Logger::LogSeverity severity = Assimp::Logger::VERBOSE;
Assimp::DefaultLogger::create("", severity, <API key>);
#endif
QScopedPointer<btStaticPlaneShape> ground(new btStaticPlaneShape(Vector3(0, 1, 0), 0));
btRigidBody::<API key> info(0, 0, ground.take(), kZeroV3);
QScopedPointer<btRigidBody> body(new btRigidBody(info));
m_world->dynamicWorldRef()->addRigidBody(body.take(), 0x10, 0);
m_scene->setWorldRef(m_world->dynamicWorldRef());
const QString &modelMotionPath = QDir(m_settings->value("dir.motion").toString())
.absoluteFilePath(m_settings->value("file.motion").toString());
const QString &cameraMotionPath = QDir(m_settings->value("dir.camera").toString())
.absoluteFilePath(m_settings->value("file.camera").toString());
QProgressDialog dialog(this);
dialog.setWindowModality(Qt::ApplicationModal);
dialog.setLabelText("Loading scene...");
dialog.setMaximum(-1);
dialog.show();
int nmodels = m_settings->beginReadArray("models");
for (int i = 0; i < nmodels; i++) {
m_settings->setArrayIndex(i);
const QString &path = m_settings->value("path").toString();
const bool enableEffect = m_settings->value("enable.effects", true).toBool();
if (!path.isNull()) {
if (IModelSharedPtr model = addModel(path, dialog, i, enableEffect)) {
addMotion(modelMotionPath, model.data());
<API key>->setCurrentModelRef(model.data());
}
qApp->processEvents(QEventLoop::<API key>);
}
}
m_settings->endArray();
IMotionSmartPtr cameraMotion(loadMotion(cameraMotionPath, 0));
if (IMotion *motion = cameraMotion.release()) {
m_scene->cameraRef()->setMotion(motion);
}
qApp->processEvents(QEventLoop::<API key>);
dialog.setValue(dialog.value() + 1);
m_scene->seek(0, Scene::kUpdateAll);
m_scene->update(Scene::kUpdateAll | Scene::kResetMotionState);
m_automaticMotion = m_settings->value("enable.playing", true).toBool();
#ifdef VPVL2_LINK_ATB
m_controller.setCurrentModelRef(<API key>->currentModelRef());
#endif
return true;
}
UI::ModelSet UI::createModelAsync(const QString &path)
{
IModelSharedPtr model;
QFile file(path);
bool ok = true;
if (path.endsWith(".zip")) {
ArchiveSharedPtr archive(new Archive(m_encoding.data()));
Archive::EntryNames entries;
String archivePath(Util::fromQString(path));
if (archive->open(&archivePath, entries)) {
const UnicodeString targetExtension(".pmx");
for (Archive::EntryNames::const_iterator it = entries.begin(); it != entries.end(); it++) {
const UnicodeString &filename = *it;
if (filename.endsWith(targetExtension)) {
archive->uncompressEntry(filename);
const std::string *bytes = archive->dataRef(filename);
const uint8 *data = reinterpret_cast<const uint8 *>(bytes->data());
const QFileInfo finfo(Util::toQString(filename));
archive->setBasePath(Util::fromQString(finfo.path()));
model = IModelSharedPtr(m_factory->createModel(data, bytes->size(), ok), &Scene::<API key>);
break;
}
}
return ModelSet(model, archive);
}
}
else if (file.open(QFile::ReadOnly)) {
const uint8 *data = static_cast<const uint8 *>(file.map(0, file.size()));
model = IModelSharedPtr(m_factory->createModel(data, file.size(), ok), &Scene::<API key>);
return ModelSet(model, ArchiveSharedPtr());
}
else {
qWarning("Failed loading the model");
}
return ModelSet();
}
IMotion *UI::createMotionAsync(const QString &path, IModel *model)
{
IMotionSmartPtr motion;
QFile file(path);
if (file.open(QFile::ReadOnly)) {
bool ok = true;
const uint8 *data = static_cast<const uint8 *>(file.map(0, file.size()));
motion.reset(m_factory->createMotion(data, file.size(), model, ok));
}
else {
qWarning("Failed parsing the model motion, skipped...");
}
return motion.release();
}
static IEffect *CreateEffectAsync(ApplicationContext *context, IModel *model, const IString *dir)
{
return context->createEffectRef(model, dir);
}
IModelSharedPtr UI::addModel(const QString &path, QProgressDialog &dialog, int index, bool enableEffect)
{
const QFileInfo info(path);
QFuture<ModelSet> future = QtConcurrent::run(this, &UI::createModelAsync, path);
dialog.setLabelText(QString("Loading %1...").arg(info.fileName()));
dialog.setRange(0, 0);
UIWaitFor(future);
const ModelSet &set = future.result();
IModelSharedPtr modelPtr = set.first;
if (future.isCanceled() || !modelPtr) {
return IModelSharedPtr();
}
if (modelPtr->error() != IModel::kNoError) {
qWarning("Failed parsing the model: %d", modelPtr->error());
return IModelSharedPtr();
}
String s1(Util::fromQString(info.absoluteDir().absolutePath()));
ApplicationContext::ModelContext modelContext(<API key>.data(), set.second.data(), &s1);
<API key>->addModelPath(modelPtr.data(), Util::fromQString(info.absoluteFilePath()));
QFuture<IEffect *> future2 = QtConcurrent::run(&CreateEffectAsync,
<API key>.data(),
modelPtr.data(), &s1);
dialog.setLabelText(QString("Loading an effect of %1...").arg(info.fileName()));
UIWaitFor(future2);
IEffect *effectRef = future2.result();
int flags = enableEffect ? Scene::kEffectCapable : 0;
#ifdef <API key>
if (!effectRef) {
qWarning() << "Effect" << <API key>->effectFilePath(modelPtr.data(), &s1) << "does not exists";
}
else if (!effectRef->internalPointer()) {
CGcontext c = static_cast<CGcontext>(effectRef->internalContext());
qWarning() << cgGetLastListing(c);
}
else {
effectRef-><API key>();
}
#else
Q_UNUSED(effectRef)
#endif
QScopedPointer<IRenderEngine> enginePtr(m_scene->createRenderEngine(<API key>.data(),
modelPtr.data(), flags));
enginePtr->setEffect(effectRef, IEffect::kAutoDetection, &modelContext);
if (enginePtr->upload(&modelContext)) {
<API key>-><API key>(effectRef, &s1);
modelPtr->setEdgeWidth(m_settings->value("edge.width", 1.0).toFloat());
modelPtr->setPhysicsEnable(m_settings->value("enable.physics", true).toBool());
if (!modelPtr->name(IEncoding::kDefaultLanguage)) {
String s(Util::fromQString(info.fileName()));
modelPtr->setName(&s, IEncoding::kDefaultLanguage);
}
bool parallel = m_settings->value("enable.parallel", true).toBool();
enginePtr->setUpdateOptions(parallel ? IRenderEngine::kParallelUpdate : IRenderEngine::kNone);
m_scene->addModel(modelPtr.data(), enginePtr.take(), index);
}
else {
return IModelSharedPtr();
}
#if 0
if (pmx::Model *pmx = dynamic_cast<pmx::Model*>(model)) {
const Array<pmx::Material *> &materials = pmx->materials();
const int nmaterials = materials.count();
for (int i = 0; i < nmaterials; i++)
qDebug() << materials[i];
const Array<pmx::Bone *> &bones = pmx->bones();
const int nbones = bones.count();
for (int i = 0; i < nbones; i++)
qDebug() << bones[i];
const Array<pmx::Morph *> &morphs = pmx->morphs();
const int nmorphs = morphs.count();
for (int i = 0; i < nmorphs; i++)
qDebug() << morphs.at(i);
const Array<pmx::Label *> &labels = pmx->labels();
const int nlabels = labels.count();
for (int i = 0; i < nlabels; i++)
qDebug() << labels.at(i);
const Array<pmx::RigidBody *> &bodies = pmx->rigidBodies();
const int nbodies = bodies.count();
for (int i = 0; i < nbodies; i++)
qDebug() << bodies.at(i);
const Array<pmx::Joint *> &joints = pmx->joints();
const int njoints = joints.count();
for (int i = 0; i < njoints; i++)
qDebug() << joints.at(i);
}
#endif
return modelPtr;
}
IMotion *UI::addMotion(const QString &path, IModel *model)
{
IMotionSmartPtr motion(loadMotion(path, model));
if (IMotion *m = motion.get()) {
m_scene->addMotion(m);
}
return motion.release();
}
IMotion *UI::loadMotion(const QString &path, IModel *model)
{
QFuture<IMotion *> future = QtConcurrent::run(this, &UI::createMotionAsync, path, model);
UIWaitFor(future);
IMotionSmartPtr motionPtr(future.result());
return future.isCanceled() ? 0 : motionPtr.release();
}
} /* namespace qt */
} /* namespace render */
} /* namespace vpvl2 */ |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=emulateIE7" />
<title>Coverage for skf/api/kb/endpoints/kb_item_new.py: 100%</title>
<link rel="icon" sizes="32x32" href="favicon_32.png">
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.hotkeys.js"></script>
<script type="text/javascript" src="jquery.isonscreen.js"></script>
<script type="text/javascript" src="coverage_html.js"></script>
<script type="text/javascript">
jQuery(document).ready(coverage.pyfile_ready);
</script>
</head>
<body class="pyfile">
<div id="header">
<div class="content">
<h1>Coverage for <b>skf/api/kb/endpoints/kb_item_new.py</b> :
<span class="pc_cov">100%</span>
</h1>
<img id="keyboard_icon" src="keybd_closed.png" alt="Show keyboard shortcuts" />
<h2 class="stats">
20 statements
<button type="button" class="run shortkey_r button_toggle_run" title="Toggle lines run">20 run</button>
<button type="button" class="mis show_mis shortkey_m button_toggle_mis" title="Toggle lines missing">0 missing</button>
<button type="button" class="exc show_exc shortkey_x button_toggle_exc" title="Toggle lines excluded">0 excluded</button>
</h2>
</div>
</div>
<div class="help_panel">
<img id="panel_icon" src="keybd_open.png" alt="Hide keyboard shortcuts" />
<p class="legend">Hot-keys on this page</p>
<div>
<p class="keyhelp">
<span class="key">r</span>
<span class="key">m</span>
<span class="key">x</span>
<span class="key">p</span> toggle line displays
</p>
<p class="keyhelp">
<span class="key">j</span>
<span class="key">k</span> next/prev highlighted chunk
</p>
<p class="keyhelp">
<span class="key">0</span> (zero) top of page
</p>
<p class="keyhelp">
<span class="key">1</span> (one) first highlighted chunk
</p>
</div>
</div>
<div id="source">
<p id="t1" class="pln"><span class="n"><a href="#t1">1</a></span><span class="t"> </span><span class="r"></span></p>
<p id="t2" class="run"><span class="n"><a href="#t2">2</a></span><span class="t"><span class="key">from</span> <span class="nam">flask</span> <span class="key">import</span> <span class="nam">request</span> </span><span class="r"></span></p>
<p id="t3" class="run"><span class="n"><a href="#t3">3</a></span><span class="t"><span class="key">from</span> <span class="nam">flask_restplus</span> <span class="key">import</span> <span class="nam">Resource</span> </span><span class="r"></span></p>
<p id="t4" class="run"><span class="n"><a href="#t4">4</a></span><span class="t"><span class="key">from</span> <span class="nam">skf</span><span class="op">.</span><span class="nam">api</span><span class="op">.</span><span class="nam">security</span> <span class="key">import</span> <span class="nam">security_headers</span><span class="op">,</span> <span class="nam">validate_privilege</span> </span><span class="r"></span></p>
<p id="t5" class="run"><span class="n"><a href="#t5">5</a></span><span class="t"><span class="key">from</span> <span class="nam">skf</span><span class="op">.</span><span class="nam">api</span><span class="op">.</span><span class="nam">kb</span><span class="op">.</span><span class="nam">business</span> <span class="key">import</span> <span class="nam">create_kb_item</span> </span><span class="r"></span></p>
<p id="t6" class="run"><span class="n"><a href="#t6">6</a></span><span class="t"><span class="key">from</span> <span class="nam">skf</span><span class="op">.</span><span class="nam">api</span><span class="op">.</span><span class="nam">kb</span><span class="op">.</span><span class="nam">serializers</span> <span class="key">import</span> <span class="nam">kb_update</span><span class="op">,</span> <span class="nam">message</span> </span><span class="r"></span></p>
<p id="t7" class="run"><span class="n"><a href="#t7">7</a></span><span class="t"><span class="key">from</span> <span class="nam">skf</span><span class="op">.</span><span class="nam">api</span><span class="op">.</span><span class="nam">kb</span><span class="op">.</span><span class="nam">parsers</span> <span class="key">import</span> <span class="nam">authorization</span> </span><span class="r"></span></p>
<p id="t8" class="run"><span class="n"><a href="#t8">8</a></span><span class="t"><span class="key">from</span> <span class="nam">skf</span><span class="op">.</span><span class="nam">api</span><span class="op">.</span><span class="nam">restplus</span> <span class="key">import</span> <span class="nam">api</span> </span><span class="r"></span></p>
<p id="t9" class="run"><span class="n"><a href="#t9">9</a></span><span class="t"><span class="key">from</span> <span class="nam">skf</span><span class="op">.</span><span class="nam">api</span><span class="op">.</span><span class="nam">security</span> <span class="key">import</span> <span class="nam">log</span><span class="op">,</span> <span class="nam">val_num</span><span class="op">,</span> <span class="nam">val_alpha</span><span class="op">,</span> <span class="nam">val_alpha_num</span><span class="op">,</span> <span class="nam"><API key></span> </span><span class="r"></span></p>
<p id="t10" class="pln"><span class="n"><a href="#t10">10</a></span><span class="t"> </span><span class="r"></span></p>
<p id="t11" class="run"><span class="n"><a href="#t11">11</a></span><span class="t"><span class="nam">ns</span> <span class="op">=</span> <span class="nam">api</span><span class="op">.</span><span class="nam">namespace</span><span class="op">(</span><span class="str">'kb'</span><span class="op">,</span> <span class="nam">description</span><span class="op">=</span><span class="str">'Operations related to kb items'</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t12" class="pln"><span class="n"><a href="#t12">12</a></span><span class="t"> </span><span class="r"></span></p>
<p id="t13" class="run"><span class="n"><a href="#t13">13</a></span><span class="t"><span class="op">@</span><span class="nam">ns</span><span class="op">.</span><span class="nam">route</span><span class="op">(</span><span class="str">'/new/<int:category_id>'</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t14" class="run"><span class="n"><a href="#t14">14</a></span><span class="t"><span class="op">@</span><span class="nam">api</span><span class="op">.</span><span class="nam">response</span><span class="op">(</span><span class="num">404</span><span class="op">,</span> <span class="str">'Validation error'</span><span class="op">,</span> <span class="nam">message</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t15" class="run"><span class="n"><a href="#t15">15</a></span><span class="t"><span class="key">class</span> <span class="nam">KBItemCreate</span><span class="op">(</span><span class="nam">Resource</span><span class="op">)</span><span class="op">:</span> </span><span class="r"></span></p>
<p id="t16" class="pln"><span class="n"><a href="#t16">16</a></span><span class="t"> </span><span class="r"></span></p>
<p id="t17" class="run"><span class="n"><a href="#t17">17</a></span><span class="t"> <span class="op">@</span><span class="nam">api</span><span class="op">.</span><span class="nam">expect</span><span class="op">(</span><span class="nam">authorization</span><span class="op">,</span> <span class="nam">kb_update</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t18" class="run"><span class="n"><a href="#t18">18</a></span><span class="t"> <span class="op">@</span><span class="nam">api</span><span class="op">.</span><span class="nam">marshal_with</span><span class="op">(</span><span class="nam">message</span><span class="op">,</span> <span class="str">'Success'</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t19" class="run"><span class="n"><a href="#t19">19</a></span><span class="t"> <span class="op">@</span><span class="nam">api</span><span class="op">.</span><span class="nam">response</span><span class="op">(</span><span class="num">400</span><span class="op">,</span> <span class="str">'No results found'</span><span class="op">,</span> <span class="nam">message</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t20" class="pln"><span class="n"><a href="#t20">20</a></span><span class="t"> <span class="key">def</span> <span class="nam">put</span><span class="op">(</span><span class="nam">self</span><span class="op">,</span> <span class="nam">category_id</span><span class="op">)</span><span class="op">:</span> </span><span class="r"></span></p>
<p id="t21" class="pln"><span class="n"><a href="#t21">21</a></span><span class="t"> <span class="str">"""</span> </span><span class="r"></span></p>
<p id="t22" class="pln"><span class="n"><a href="#t22">22</a></span><span class="t"><span class="str"> Create new kb item.</span> </span><span class="r"></span></p>
<p id="t23" class="pln"><span class="n"><a href="#t23">23</a></span><span class="t"><span class="str"> * Privileges required: **edit**</span> </span><span class="r"></span></p>
<p id="t24" class="pln"><span class="n"><a href="#t24">24</a></span><span class="t"><span class="str"> """</span> </span><span class="r"></span></p>
<p id="t25" class="run"><span class="n"><a href="#t25">25</a></span><span class="t"> <span class="nam">validate_privilege</span><span class="op">(</span><span class="nam">self</span><span class="op">,</span> <span class="str">'edit'</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t26" class="run"><span class="n"><a href="#t26">26</a></span><span class="t"> <span class="nam">data</span> <span class="op">=</span> <span class="nam">request</span><span class="op">.</span><span class="nam">json</span> </span><span class="r"></span></p>
<p id="t27" class="run"><span class="n"><a href="#t27">27</a></span><span class="t"> <span class="nam"><API key></span><span class="op">(</span><span class="nam">data</span><span class="op">.</span><span class="nam">get</span><span class="op">(</span><span class="str">'title'</span><span class="op">)</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t28" class="run"><span class="n"><a href="#t28">28</a></span><span class="t"> <span class="nam">result</span> <span class="op">=</span> <span class="nam">create_kb_item</span><span class="op">(</span><span class="nam">data</span><span class="op">,</span> <span class="nam">category_id</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t29" class="run"><span class="n"><a href="#t29">29</a></span><span class="t"> <span class="key">return</span> <span class="nam">result</span><span class="op">,</span> <span class="num">200</span><span class="op">,</span> <span class="nam">security_headers</span><span class="op">(</span><span class="op">)</span> </span><span class="r"></span></p>
<p id="t30" class="pln"><span class="n"><a href="#t30">30</a></span><span class="t"> </span><span class="r"></span></p>
</div>
<div id="footer">
<div class="content">
<p>
<a class="nav" href="index.html">&
created at 2021-03-26 13:45 +0100
</p>
</div>
</div>
</body>
</html> |
package org.sejda.impl.sambox.component;
import static java.util.Objects.nonNull;
import static org.sejda.commons.util.RequireUtils.requireArg;
import static org.sejda.commons.util.RequireUtils.requireNotBlank;
import static org.sejda.commons.util.RequireUtils.requireNotNullArg;
import static org.sejda.impl.sambox.component.OutlineUtils.pageDestinationFor;
import java.awt.Color;
import java.awt.Point;
import java.io.IOException;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import org.sejda.impl.sambox.util.FontUtils;
import org.sejda.model.exception.TaskException;
import org.sejda.model.exception.TaskIOException;
import org.sejda.model.parameter.MergeParameters;
import org.sejda.model.toc.ToCPolicy;
import org.sejda.sambox.cos.COSArray;
import org.sejda.sambox.cos.COSInteger;
import org.sejda.sambox.pdmodel.PDDocument;
import org.sejda.sambox.pdmodel.PDPage;
import org.sejda.sambox.pdmodel.PDPageContentStream;
import org.sejda.sambox.pdmodel.PDPageTree;
import org.sejda.sambox.pdmodel.common.PDRectangle;
import org.sejda.sambox.pdmodel.font.PDFont;
import org.sejda.sambox.pdmodel.font.PDType1Font;
import org.sejda.sambox.pdmodel.interactive.annotation.PDAnnotation;
import org.sejda.sambox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.sejda.sambox.pdmodel.interactive.documentnavigation.destination.<API key>;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Component creating a table of content
*
* @author Andrea Vacondio
*/
public class <API key> {
private static final Logger LOG = LoggerFactory.getLogger(<API key>.class);
private static final int DEFAULT_FONT_SIZE = 14;
private static final int DEFAULT_MARGIN = 72;
private static final String SEPARATOR = " ";
private final Deque<ToCItem> items = new LinkedList<>();
private PDDocument document;
private PDRectangle pageSize = null;
private float fontSize = DEFAULT_FONT_SIZE;
private float margin = DEFAULT_MARGIN;
private PDFont font = PDType1Font.HELVETICA;
private float lineHeight;
private MergeParameters params;
private PageTextWriter writer;
public <API key>(MergeParameters params, PDDocument document) {
requireNotNullArg(document, "Containing document cannot be null");
requireNotNullArg(params, "Parameters cannot be null");
this.document = document;
this.params = params;
this.writer = new PageTextWriter(document);
}
/**
* Adds to the ToC the given text with the given annotation associated
*
* @param text
* @param pageNumber
* @param page
*/
public void appendItem(String text, long pageNumber, PDPage page) {
requireNotBlank(text, "ToC item cannot be blank");
requireArg(pageNumber > 0, "ToC item cannot point to a negative page");
requireNotNullArg(page, "ToC page cannot be null");
<API key>();
if (shouldGenerateToC()) {
items.add(new ToCItem(text, pageNumber, linkAnnotationFor(page)));
}
}
private PDAnnotationLink linkAnnotationFor(PDPage importedPage) {
<API key> pageDest = pageDestinationFor(importedPage);
PDAnnotationLink link = new PDAnnotationLink();
link.setDestination(pageDest);
link.setBorder(new COSArray(COSInteger.ZERO, COSInteger.ZERO, COSInteger.ZERO));
return link;
}
/**
* Generates a ToC and prepend it to the given document
*
* @throws TaskException
* if there is an error generating the ToC
*/
public int addToC() throws TaskException {
return addToC(0);
}
/**
* Generates a ToC and inserts it in the doc at before the given page number
*
* @throws TaskException
* if there is an error generating the ToC
*/
public int addToC(int beforePageNumber) throws TaskException {
PDPageTree pagesTree = document.getPages();
LinkedList<PDPage> toc = generateToC();
toc.descendingIterator().forEachRemaining(p -> {
if (pagesTree.getCount() > 0) {
pagesTree.insertBefore(p, pagesTree.get(beforePageNumber));
} else {
pagesTree.add(p);
}
});
return toc.size();
}
private LinkedList<PDPage> generatedToC;
private LinkedList<PDPage> generateToC() throws TaskIOException {
if(generatedToC == null) {
generatedToC = _generateToC();
}
return generatedToC;
}
private LinkedList<PDPage> _generateToC() throws TaskIOException {
// we need to know how many pages the ToC itself has
// so we can write the page numbers of the ToC items correctly
// but can only know how many pages the ToC has after we generate it
// therefore, 1) generate ToC using a dummy estimate for the tocNumberOfPages
int tocNumberOfPages = _generateToC(0).size();
// 2) generate ToC again with correct tocNumberOfPages
return _generateToC(tocNumberOfPages);
}
private LinkedList<PDPage> _generateToC(int tocNumberOfPages) throws TaskIOException {
LinkedList<PDPage> pages = new LinkedList<>();
<API key>();
int maxRowsPerPage = (int) ((pageSize().getHeight() - (margin * 2) + lineHeight) / lineHeight);
Deque<ToCItem> items = new LinkedList<>(this.items);
if (shouldGenerateToC()) {
while (!items.isEmpty()) {
int row = 0;
float separatorWidth = stringLength(SEPARATOR);
float <API key> = <API key>(separatorWidth);
PDPage page = createPage(pages);
try (PDPageContentStream stream = new PDPageContentStream(document, page)) {
while (!items.isEmpty() && row < maxRowsPerPage) {
// peek, don't poll. we don't know yet if the item will fit on this page
// eg: long item that wraps on multiple lines, but there's no room for all of them
// (1 row available on page, but item wraps on 2 rows).
ToCItem i = items.peek();
if (nonNull(i)) {
float y = pageSize().getHeight() - margin - (row * lineHeight);
float x = margin;
List<String> lines = <API key>(i.text, <API key>, separatorWidth);
if (row + lines.size() > maxRowsPerPage) {
// does not fit on multiple lines, write on next page
row = maxRowsPerPage;
continue;
}
// fits even if on multiple lines, take out of the items thing
items.poll();
// write item on multiple lines if it's too long to fit on just one
// regular scenario is a single line
for (int j = 0; j < lines.size(); j++) {
String line = lines.get(j);
writeText(page, line, x, y);
if (j < lines.size() - 1) {
// if we've written the item last line, don't increment the row and y coordinate
row++;
y = pageSize().getHeight() - margin - (row * lineHeight);
}
}
long pageNumber = i.page + tocNumberOfPages;
String pageString = SEPARATOR + Long.toString(pageNumber);
float x2 = getPageNumberX(separatorWidth);
writeText(page, pageString, x2, y);
// make the item clickable and link to the page number
// we want a little spacing between link annotations, so they are not adjacent, to prevent mis-clicking
// the spacing will be applied top and bottom and is the difference between line height and font height
float spacing = (lineHeight - fontSize) / 2;
float height = lineHeight * lines.size() - 2 * spacing;
i.annotation.setRectangle(
new PDRectangle(margin, y - spacing, pageSize().getWidth() - (2 * margin), height));
page.getAnnotations().add(i.annotation);
// draw line between item text and page number
// chapter 1 <API key> 12
// chapter 2 <API key> 15
// TODO: dots .............. instead of line <API key>
String lastLine = lines.get(lines.size() - 1);
stream.moveTo(margin + separatorWidth + stringLength(lastLine), y);
stream.lineTo(<API key>, y);
stream.setLineWidth(0.5f);
stream.stroke();
}
row++;
}
} catch (IOException e) {
throw new TaskIOException("An error occurred while create the ToC", e);
}
}
if (params.isBlankPageIfOdd() && pages.size() % 2 == 1) {
PDPage lastTocPage = pages.getLast();
PDPage blankPage = new PDPage(lastTocPage.getMediaBox());
pages.add(blankPage);
}
}
return pages;
}
private void <API key>() {
if(generatedToC != null) {
throw new <API key>("ToC has already been generated");
}
}
private void writeText(PDPage page, String s, float x, float y) throws TaskIOException {
writer.write(page, new Point.Float(x, y), s, font, (double) fontSize, Color.BLACK);
}
private List<String> <API key>(String text, float <API key>, float separatorWidth)
throws TaskIOException {
float maxWidth = pageSize().getWidth() - margin - (pageSize().getWidth() - <API key>)
- separatorWidth;
return FontUtils.wrapLines(text, font, fontSize, maxWidth, document);
}
private PDPage createPage(LinkedList<PDPage> pages) {
LOG.debug("Creating new ToC page");
PDPage page = new PDPage(pageSize());
pages.add(page);
return page;
}
private float <API key>(float separatorWidth) throws TaskIOException {
return getPageNumberX(separatorWidth);
}
private float getPageNumberX(float separatorWidth) throws TaskIOException {
return pageSize().getWidth() - margin - separatorWidth
/* leave enough space for a 4 digit page number, assumes 9 to be a wide enough digit */
- stringLength(Long.toString(9999));
}
private float stringLength(String text) throws TaskIOException {
return writer.getStringWidth(text, font, fontSize);
}
public boolean hasToc() {
return !items.isEmpty();
}
public boolean shouldGenerateToC() {
return params.<API key>() != ToCPolicy.NONE;
}
public void pageSizeIfNotSet(PDRectangle pageSize) {
<API key>();
if (this.pageSize == null) {
this.pageSize = pageSize;
}
}
private void <API key>() {
float scalingFactor = pageSize().getHeight() / PDRectangle.A4.getHeight();
this.fontSize = scalingFactor * DEFAULT_FONT_SIZE;
this.margin = scalingFactor * DEFAULT_MARGIN;
this.lineHeight = (float) (fontSize + (fontSize * 0.7));
}
private PDRectangle pageSize() {
return Optional.ofNullable(pageSize).orElse(PDRectangle.A4);
}
public float getFontSize() {
return fontSize;
}
PDDocument getDoc() {
return document;
}
private static class ToCItem {
public final String text;
public final long page;
public final PDAnnotation annotation;
public ToCItem(String text, long page, PDAnnotation annotation) {
this.text = text;
this.page = page;
this.annotation = annotation;
}
}
} |
'use strict';
/* Controllers */
angular.module('quizsApp')
.controller('<API key>', ['$scope', '$state', '$rootScope', '$stateParams', '$timeout', 'APP_PATH', 'MAX_FILE_SIZE', 'PATTERN_FILE', 'Notifications', 'Upload', 'Modal', 'Line', 'State', 'Questions', 'QuestionsApi', function($scope, $state, $rootScope, $stateParams, $timeout, APP_PATH, MAX_FILE_SIZE, PATTERN_FILE, Notifications, Upload, Modal, Line, State, Questions, QuestionsApi) {
$scope.maxFileSize = MAX_FILE_SIZE;
$scope.patternFile = PATTERN_FILE;
$scope.errorFileQCM = [];
$scope.errorFileASS = {'left':[], 'right': []};
$scope.errorFileTAT = [];
// type de question
$scope.types = {qcm: true, tat: false, ass: false};
// titre de l'action mis en majuscule par angular
$scope.actionTitle = 'ajouter une question';
// placeholder pour les input file media
$scope.placeholderMedia = "Joindre un fichier (image ou son)";
$scope.placeholderLink = "Intégrer une video web";
var defaultQuestions = {qcm: "Cochez la ou les bonnes réponses.", tat: "Remplissez les trous avec propositions qui vous semblent justes.", ass: "Associez les propositions entre elles."};
$scope.lastDeleteLeurre = {};
//promise d'un time out permettant de l'annuler
var promiseTimeOut = "";
$scope.connect1 = {id: null, x1: null, y1: null}
$scope.connect2 = {id: null, x2: null, y2: null}
//Variable pour les leurres
//id temporairea
$rootScope.idLeurreTmp = "tmp_0";
$scope.indexOfleurre =0;
$rootScope.medias = {
answers: {
qcm: [],
ass: [],
tat: []
}
};
$scope.openFileWindow = function () {
angular.element( document.querySelector( '#fileUpload' ) ).trigger('click');
};
// Fonction qui change le type de la question
$rootScope.changeType = function(type){
_.each($scope.types, function(button, key){
if (key == type) {
$scope.types[key] = true;
$rootScope.question.type = key;
<API key>(key);
} else {
$scope.types[key] = false;
};
});
}
var <API key> = function(type){
if (isDefaultLibelle($rootScope.question.libelle)) {
$rootScope.question.libelle = defaultQuestions[type];
};
}
var isDefaultLibelle = function(string){
var response = false;
_.each(defaultQuestions, function(libelle){
if (libelle === string || string === "") {
response = true;
};
});
return response;
}
// fonction permettant de couper un nom trop long...
var sizeNameMedia = function(name, lengthMax, lengthLeft, lengthRight){
if (name.length > lengthMax) {
return name.substring(0,lengthLeft) + " ... " + name.substring(name.length-lengthRight,name.length);
};
return name;
}
var checkErrorsFile = function(file){
if (file.$error == 'maxSize'){
return "La taille maximum autorisée est de "+file.$errorParam+" !";
}
if (file.$error == 'pattern'){
return "Seuls les images et audios sont autorisés !";
}
return null;
}
$scope.openFileUpload = function(id){
angular.element($('#'+id)).click();
};
$rootScope.uploadQuestionMedia = function(file, link){
if ( file ) $scope.errorFileQuestion = checkErrorsFile(file);
if (file && !file.$error) {
var params = {
name: sizeNameMedia(file.name, 25, 11, 11),
url: window.URL.createObjectURL(file),
mime: file.type,
type: file.type.split("/")[0]
};
$rootScope.question.media = setMedia(params);
$rootScope.medias["file"] = file;
}
if (link) {
var params = {
name: sizeNameMedia(link.name, 25, 11, 11),
fullname: link.name,
url: link.url,
type: "video"
};
$rootScope.question.media = setMedia(params);
};
}
$rootScope.<API key> = function(file, index, link){
if ( file ) $scope.errorFileQCM[index] = checkErrorsFile(file);
if (file && !file.$error) {
var params = {
name: sizeNameMedia(file.name, 30, 22, 8),
url: window.URL.createObjectURL(file),
mime: file.type,
type: file.type.split("/")[0]
};
$rootScope.suggestions.qcm[index].joindre = setMedia(params);
$rootScope.medias.answers.qcm[index] = file;
}
if (link) {
var params = {
name: sizeNameMedia(link.name, 30, 22, 8),
fullname: link.name,
url: link.url,
type: "video"
};
$rootScope.suggestions.qcm[index].joindre = setMedia(params);
};
}
$rootScope.<API key> = function(file, index, direction, link){
if ( file ) $scope.errorFileASS[direction][index] = checkErrorsFile(file);
if (file && !file.$error) {
var params = {
name: sizeNameMedia(file.name, 8, 0, 8),
url: window.URL.createObjectURL(file),
mime: file.type,
type: file.type.split("/")[0]
};
if (direction === 'left') {
$rootScope.suggestions.ass[index].leftProposition.joindre = setMedia(params);
$rootScope.medias.answers.ass[index] = {leftProposition: file};
} else {
$rootScope.suggestions.ass[index].rightProposition.joindre = setMedia(params);
$rootScope.medias.answers.ass[index] = {rightProposition: file};
};
};
if (link) {
var params = {
name: sizeNameMedia(link.name, 8, 0, 8),
url: link.url,
fullname: link.name,
type: "video"
};
if (direction === 'left') {
$rootScope.suggestions.ass[index].leftProposition.joindre = setMedia(params);
} else {
$rootScope.suggestions.ass[index].rightProposition.joindre = setMedia(params);
};
};
}
$rootScope.<API key> = function(file, index, link){
if ( file ) $scope.errorFileTAT[index] = checkErrorsFile(file);
if (file && !file.$error) {
var params = {
name: sizeNameMedia(file.name, 15, 5, 8),
url: window.URL.createObjectURL(file),
mime: file.type,
type: file.type.split("/")[0]
};
$rootScope.suggestions.tat[index].joindre = setMedia(params);
$rootScope.medias.answers.tat[index] = file;
};
if (link) {
var params = {
name: sizeNameMedia(link.name, 15, 5, 8),
url: link.url,
fullname: link.name,
type: "video"
};
$rootScope.suggestions.tat[index].joindre = setMedia(params);
};
}
var setMedia = function(params){
var object = {file: {}};
object.file.name = params.name;
object.file.url = params.url;
object.type = params.type;
if (params.type != "video"){
object.mime = params.mime;
} else {
object.fullname = params.fullname;
}
return object;
}
var uploadMedia = function(question){
uploadRequest($rootScope.medias.file, question.id, "question");
switch(question.type){
case "qcm":
_.each($rootScope.medias.answers.qcm, function(medium, index){
uploadRequest(medium, question.answers[index].id, "suggestions");
});
break;
case "tat":
_.each($rootScope.medias.answers.tat, function(medium, index){
uploadRequest(medium, question.answers[index].id, "suggestions");
});
break;
case "ass":
_.each($rootScope.medias.answers.ass, function(medium, index){
if (medium.leftProposition)
uploadRequest(medium.leftProposition, question.answers[index].leftProposition.id, "suggestions");
if (medium.rightProposition)
uploadRequest(medium.rightProposition, question.answers[index].rightProposition.id, "suggestions");
});
break;
}
};
// importe le medium
var uploadRequest = function (file, id, type) {
Upload.upload({
url: APP_PATH + '/api/medias/upload',
fields: {'type': type, id: id},
file: file
}).success(function (data, status) {
console.log(data);
}).error(function (data, status) {
console.log('error status: ' + status);
});
};
$scope.openAddLink = function(type, index){
$rootScope.indexSuggestion = index;
$rootScope.typeUpload = type;
Modal.open($scope.modalAddLinkCtrl, APP_PATH + '/app/views/modals/add-link.html', "md");
}
$scope.changeModeAss = function(){
if ($rootScope.validateAss) {
Modal.open($scope.<API key>, APP_PATH + '/app/views/modals/confirm.html', 'md');
} else {
$rootScope.validateAss = !$rootScope.validateAss;
}
}
$scope.checkAss = function(){
return $rootScope.suggestions.ass[0].rightProposition.libelle && $rootScope.suggestions.ass[0].leftProposition.libelle;
}
//efface les proposition de l'association
$scope.cleanAss = function(){
Modal.open($scope.<API key>, APP_PATH + '/app/views/modals/confirm.html', 'md');
}
// Fonction qui enregistre le premier point de connection de la ligne,
$scope.connect = function(idElement, typeProposition){
if ($rootScope.validateAss) {
var element = angular.element($('#'+typeProposition+"connect"+idElement));
var xElement = element.offset().left + element.width() / 2;
var yElement = element.offset().top + element.height() / 2;
// on enregistre les point de connections
if (typeProposition === 'left') {
$scope.connect1 = {id: idElement, x1: xElement, y1: yElement};
} else {
$scope.connect2 = {id: idElement, x2: xElement, y2: yElement};
};
if ($scope.connect1.x1 != null && $scope.connect1.y1 != null && $scope.connect2.x2 != null && $scope.connect2.y2 != null) {
//si on a aucunes solutions et pas les lignes
if(_.indexOf($rootScope.suggestions.ass[$scope.connect1.id].leftProposition.solutions, $scope.connect2.id) == -1 && $('#line'+$scope.connect1.id+"_"+$scope.connect2.id).length == 0){
//dans la proposition de gauche la solution et la proposition de droite
$rootScope.suggestions.ass[$scope.connect1.id].leftProposition.solutions.push($scope.connect2.id);
//et inversement dans la proposition de droite
$rootScope.suggestions.ass[$scope.connect2.id].rightProposition.solutions.push($scope.connect1.id);
Line.create('linesId', $scope.connect1.id+"_"+$scope.connect2.id, $scope.connect1.x1, $scope.connect1.y1, $scope.connect2.x2, $scope.connect2.y2, $scope);
} else if (_.indexOf($rootScope.suggestions.ass[$scope.connect1.id].leftProposition.solutions, $scope.connect2.id) != -1 && $('#line'+$scope.connect1.id+"_"+$scope.connect2.id).length == 0){
Line.create('linesId', $scope.connect1.id+"_"+$scope.connect2.id, $scope.connect1.x1, $scope.connect1.y1, $scope.connect2.x2, $scope.connect2.y2, $scope);
};
$scope.connect1 = {id: null, x1: null, y1: null};
$scope.connect2 = {id: null, x2: null, y2: null};
};
};
}
//supprime une ligne lorsque l'on double click dessus
$scope.clearLine = function(id){
Line.clear(id);
}
// Ajoute une ligne de TAT
$scope.addTAT = function(){
$rootScope.suggestions.tat.push({
text: null,
solution: {id: null, libelle: null},
joindre: {file: null, type: null},
leurre:{id : null, libelle: null},
});
}
// Ajoute une ligne de TAT
$scope.deleteTAT = function(){
var iter = $rootScope.suggestions.tat.length-1;
var tab=$rootScope.suggestions.tat
$rootScope.suggestions.tat=[]
do{
$rootScope.suggestions.tat.push(tab[iter]);
iter
}while(iter>0)
return $rootScope.suggestions.tat;
}
// Ajoute un leurre avec une modal
$scope.addLeurre = function(indexOfleurre){
$scope.indexOfleurre= indexOfleurre;
Modal.openaddleure($scope.modalAddLeurreCtrl, APP_PATH+'/app/views/modals/add-change-object.html', 'md', indexOfleurre);
}
$scope.deleteLeurre = function(id){
$rootScope.suggestions.leurres = _.reject($rootScope.suggestions.leurres, function(leurre){
if (leurre.id === id) {
$scope.lastDeleteLeurre = leurre;
$scope.showBackLeurre = true;
promiseTimeOut = $timeout(function(){
$scope.showBackLeurre = false;
}, 5000);
};
return leurre.id === id;
})
}
//annule la suppresion du dernier leurre
$scope.backLeurre = function(){
$rootScope.suggestions.leurres.push(angular.copy($scope.lastDeleteLeurre));
$scope.showBackLeurre = false;
$timeout.cancel(promiseTimeOut);
$scope.lastDeleteLeurre = {};
}
$scope.atLeastOneAnswer = function(typeQuestion){
var atLeastOne = false;
switch(typeQuestion){
case "qcm":
_.each($rootScope.suggestions.qcm, function(reponse){
if (reponse.proposition != null && reponse.proposition != "") {
atLeastOne = true;
};
});
break;
case "tat":
_.each($rootScope.suggestions.tat, function(reponse){
if (reponse.text != null && reponse.text != "" && reponse.solution != null && reponse.solution) {
atLeastOne = true;
};
});
break;
case "ass":
_.each($rootScope.suggestions.ass, function(reponse){
if (reponse.leftProposition.libelle != null && reponse.leftProposition.libelle != "" && reponse.rightProposition.libelle != null && reponse.rightProposition.libelle) {
atLeastOne = true;
};
});
break;
}
return atLeastOne;
}
// Preview de la question
$scope.preview = function(){
State.saveScope($scope);
State.saveRootScope($rootScope);
//on ajoute les suggestions du type dans la question
$rootScope.question.answers = angular.copy($rootScope.suggestions[$rootScope.question.type]);
$rootScope.question.leurres = angular.copy($rootScope.suggestions.leurres);
//on copi la question dans la preview
$rootScope.previewQuestion = angular.copy($rootScope.question);
if ($scope.modeModif) {
$state.go('quizs.<API key>', {quiz_id: $rootScope.quiz.id, id: $rootScope.previewQuestion.id});
} else {
$state.go('quizs.<API key>', {quiz_id: $rootScope.quiz.id});
};
}
$scope.addQuestion = function(){
if ($rootScope.question.libelle && $scope.atLeastOneAnswer($rootScope.question.type)) {
//on ajoute les suggestions du type dans la question
$rootScope.question.answers = $rootScope.suggestions[$rootScope.question.type];
$rootScope.question.leurres = $rootScope.suggestions.leurres;
$rootScope.quiz.questions[0] = $rootScope.question;
if ($rootScope.modeModif) {
QuestionsApi.update({quiz: $rootScope.quiz}).$promise.then(function(response){
uploadMedia(response.question_updated);
});
} else {
QuestionsApi.create({quiz: $rootScope.quiz}).$promise.then(function(response){
uploadMedia(response.question_created);
});
};
$state.go('quizs.params', {quiz_id: $rootScope.quiz.id});
} else {
Notifications.add("La question doit avoir un titre et au moins une réponse !", "error");
};
}
$scope.backParams = function(){
Modal.open($scope.<API key>, APP_PATH + '/app/views/modals/confirm.html', "md");
}
$scope.<API key> = ["$scope", "$rootScope", "$uibModalInstance", function($scope, $rootScope, $uibModalInstance){
$scope.title = "Effacer les données";
$scope.message = "Êtes vous sûr de vouloir effacer les propositions, solutions liées et médias de l'association ?";
$scope.no = function(){
$uibModalInstance.close();
}
$scope.ok = function(){
for (var i = $rootScope.suggestions.ass.length - 1; i >= 0; i
$rootScope.suggestions.ass[i].leftProposition.libelle = null;
$rootScope.suggestions.ass[i].leftProposition.joindre.file = null;
$rootScope.suggestions.ass[i].leftProposition.solutions = [];
$rootScope.suggestions.ass[i].rightProposition.libelle = null;
$rootScope.suggestions.ass[i].rightProposition.joindre.file = null;
$rootScope.suggestions.ass[i].rightProposition.solutions = [];
};
$(".line").remove();
$uibModalInstance.close();
}
}];
$scope.<API key> = ["$scope", "$rootScope", "$uibModalInstance", function($scope, $rootScope, $uibModalInstance){
$scope.title = "Effacer les données";
$scope.message = "Êtes vous sûr de vouloir effacer toutes les données de la questions ?";
$scope.no = function(){
$uibModalInstance.close();
}
$scope.ok = function(){
$uibModalInstance.close();
}
}];
$scope.<API key> = ["$scope", "$rootScope", "$uibModalInstance", function($scope, $rootScope, $uibModalInstance){
$scope.title = "Modifier le texte";
$scope.message = "Modifier le texte, vous fera perdre tous vos liens ! \n Êtes vous sûr de vouloir le modifier ?";
$scope.no = function(){
$uibModalInstance.close();
}
$scope.ok = function(){
//on supprime les solutions
for (var i = $rootScope.suggestions.ass.length - 1; i >= 0; i
$rootScope.suggestions.ass[i].leftProposition.solutions = [];
$rootScope.suggestions.ass[i].rightProposition.solutions = [];
};
//on supprime les lignes
$(".line").remove();
$rootScope.validateAss = !$rootScope.validateAss;
$uibModalInstance.close();
}
}];
//controller pour ajouter un leurre dans la liste avec une modal
$scope.modalAddLeurreCtrl = ["$scope", "$rootScope", "$uibModalInstance" , "indexOfleurre", function($scope, $rootScope, $uibModalInstance, indexOfleurre ){
$scope.title = "Ajouter un leurre";
$scope.placeholder = "Insérer le leurre";
$scope.maxLength = 100;
$scope.text = "";
$scope.index = indexOfleurre;
$scope.error = "Le leurre ne peut pas être vide !";
$scope.required = false
$scope.no = function(){
$uibModalInstance.close();
}
$scope.ok = function(){
$scope.validate = true;
//si le texte n'est pas vide ou null on l'ajoute au leurres
if ($scope.text != null && $scope.text != "") {
var nb = parseInt($rootScope.idLeurreTmp.split('_')[1]);
$rootScope.idLeurreTmp = $rootScope.idLeurreTmp.split('_')[0] + "_" + ++nb;
$rootScope.suggestions.leurres.push({id: $rootScope.idLeurreTmp, libelle: $scope.text, attribue:$scope.index});
$uibModalInstance.close();
};
}
}];
//controller pour effacer toute la quetsion avec une modal
$scope.<API key> = ["$scope", "$rootScope", "$uibModalInstance", "Questions", function($scope, $rootScope, $uibModalInstance, Questions){
$scope.title = "Annuler la question";
$scope.message = "Êtes vous sûr de vouloir annuler ?";
$scope.no = function(){
$uibModalInstance.close();
}
$scope.ok = function(){
$state.go('quizs.params', {quiz_id: $rootScope.quiz.id});
$uibModalInstance.close();
}
}];
//controller pour ajouter un line video avec une modal
$scope.modalAddLinkCtrl = ["$scope", "$rootScope", "$uibModalInstance", function($scope, $rootScope, $uibModalInstance){
$scope.validate = false;
$scope.title = "Ajout lien vidéo";
$scope.placeholderName = "Insérer le nom de la vidéo";
$scope.placeholderLink = "Insérer le lien de la vidéo";
$scope.name = "";
$scope.text = "";
$scope.error = "Le champs ne peut être vide !";
$scope.no = function(){
$uibModalInstance.close();
}
$scope.ok = function(){
$scope.validate = true;
if ($scope.name != "" && $scope.text != "") {
var link = {url: $scope.text, name: $scope.name};
switch ($rootScope.typeUpload){
case "question":
$rootScope.uploadQuestionMedia(null, link);
break;
case "qcm":
$rootScope.<API key>(null, $rootScope.indexSuggestion, link)
break;
case "tat":
$rootScope.<API key>(null, $rootScope.indexSuggestion, link)
break;
case "assLeft":
$rootScope.<API key>(null, $rootScope.indexSuggestion, "left", link)
break;
case "assRight":
$rootScope.<API key>(null, $rootScope.indexSuggestion, "right", link)
break;
}
$uibModalInstance.close();
};
}
}];
if (!$rootScope.previewQuestion) {
if (!$stateParams.id) {
$rootScope.modeModif = false;
//permet de valider les association pour ensuite les reliers
$rootScope.validateAss = false;
$rootScope.question = Questions.getDefaultQuestion();
$rootScope.suggestions = Questions.<API key>();
//variable des files media
$rootScope.medias = {
answers: {
qcm: [],
tat: [],
ass: []
}
};
// mode update
} else {
QuestionsApi.get({id: $stateParams.id}).$promise.then(function(response){
$rootScope.question = response.question_found;
if ($rootScope.question){
//on remet les suggestions tout en noubliant pas de remettre les suggestions des autre type que celle de la question
$rootScope.suggestions = Questions.<API key>();
$rootScope.suggestions[$rootScope.question.type] = angular.copy($rootScope.question.answers);
$rootScope.suggestions.leurres = angular.copy($rootScope.question.leurres);
$rootScope.modeModif = true;
if ($rootScope.question.type == "ass") {
//permet de valider les association pour ensuite les reliers
$rootScope.validateAss = true;
$timeout(function(){
for (var i = $rootScope.suggestions.ass.length - 1; i >= 0; i
if ($rootScope.suggestions.ass[i].leftProposition.solutions.length > 0) {
_.each($rootScope.suggestions.ass[i].leftProposition.solutions, function(solution){
$scope.connect(i, "left");
$scope.connect(solution, "right");
});
};
};
}, 500);
};
$rootScope.changeType($rootScope.question.type)
} else {
$state.go('erreur', {code: "404", message: "La question n'existe pas !"});
};
});
};
} else {
$rootScope.previewQuestion = null;
$rootScope.modeModif = false;
if ($stateParams.id) $rootScope.modeModif = true;
$scope.types = State.restoreScope().types;
$rootScope.validateAss = false;
$rootScope.question = State.restoreRootScope().question;
$rootScope.suggestions = State.restoreRootScope().suggestions;
$rootScope.idLeurreTmp = State.restoreRootScope().idtemp;
//variable des files media
$rootScope.medias = State.restoreRootScope().medias;
};
}]); |
package org.mazarineblue.functions.events;
import org.mazarineblue.functions.FunctionRegistry;
public class <API key>
extends <API key> {
private static final long serialVersionUID = 1L;
public <API key>(FunctionRegistry registry) {
super(registry);
}
} |
import { WebApplication } from '@/ui_models/application';
import { FeatureStatus, FeatureIdentifier } from '@standardnotes/snjs';
import { FunctionComponent } from 'preact';
import { useCallback } from 'preact/hooks';
import { JSXInternal } from 'preact/src/jsx';
import { Icon } from '../Icon';
import { usePremiumModal } from '../Premium';
import { Switch } from '../Switch';
type Props = {
application: WebApplication;
onToggle: (value: boolean) => void;
onClose: () => void;
isEnabled: boolean;
};
export const FocusModeSwitch: FunctionComponent<Props> = ({
application,
onToggle,
onClose,
isEnabled,
}) => {
const premiumModal = usePremiumModal();
const isEntitled =
application.features.getFeatureStatus(FeatureIdentifier.FocusMode) ===
FeatureStatus.Entitled;
const toggle = useCallback(
(e: JSXInternal.TargetedMouseEvent<HTMLButtonElement>) => {
e.preventDefault();
if (isEntitled) {
onToggle(!isEnabled);
onClose();
} else {
premiumModal.activate('Focused Writing');
}
},
[isEntitled, onToggle, isEnabled, onClose, premiumModal]
);
return (
<>
<button
className="sn-dropdown-item focus:bg-info-backdrop focus:shadow-none justify-between"
onClick={toggle}
>
<div className="flex items-center">
<Icon type="menu-close" className="color-neutral mr-2" />
Focused Writing
</div>
{isEntitled ? (
<Switch className="px-0" checked={isEnabled} />
) : (
<div title="Premium feature">
<Icon type="premium-feature" />
</div>
)}
</button>
</>
);
}; |
<?php
class Constants
{
public static $dbhost = "localhost"; // Replace By Your Database-Host
public static $dbuname = "root"; // Replace By Your Database-Username
<<<< HEAD
public static $dbpass = "password"; // Replace By Your Database-Password
====
public static $dbpass = "1234"; // Replace By Your Database-Password
>>>> <SHA1-like>
public static $dbname = "freeEdu"; // Standard Database Name Donot change It!
public static $branchtab = "MBRANCHT";
public static $regtab = "MREGT";
public static $brnname = "brname";
public static $regname = "regname";
public static $battab = "MBATCHT";
public static $batname = "battab";
public static $batsuffix = "batprefix";
public static $subtab = "MSUBJECTT";
public static $subname = "subtab";
public static $fbappid = '214321525295998';
public static $fb<API key>;
}
class Methods
{
public static function getBatchAddString($batchname)
{
return "create table ".$batchname."(sid text,srno text,sname text,scontact text,sbio text,imgid text)";
}
public static function subAddString($subname)
{
return "create table ".$subname."(subid text,subcode text,subname text,imgid text,year text,inmax text,exmax text,exmin text,cre text,books text)";
}
public static function getBranchId($branchname)
{
return "select brid from MBRANCHT where brname='".$branchname."'";
}
public static function getRegId($regname)
{
return "select regid from MREGT where regname='".$regname."'";
}
}
?> |
# coding: utf-8
import constance
from django.conf import settings
from rest_framework.response import Response
from rest_framework.views import APIView
from kobo.static_lists import COUNTRIES, LANGUAGES, SECTORS
from kobo.apps.hook.constants import <API key>
class EnvironmentView(APIView):
"""
GET-only view for certain server-provided configuration data
"""
CONFIGS_TO_EXPOSE = [
'<API key>',
'PRIVACY_POLICY_URL',
'SOURCE_CODE_URL',
'SUPPORT_EMAIL',
'SUPPORT_URL',
'COMMUNITY_URL',
]
def get(self, request, *args, **kwargs):
"""
Return the lowercased key and value of each setting in
`CONFIGS_TO_EXPOSE`, along with the static lists of sectors, countries,
all known languages, and languages for which the interface has
translations.
"""
data = {
key.lower(): getattr(constance.config, key)
for key in self.CONFIGS_TO_EXPOSE
}
data['available_sectors'] = SECTORS
data['available_countries'] = COUNTRIES
data['all_languages'] = LANGUAGES
data['interface_languages'] = settings.LANGUAGES
data['<API key>'] = <API key>
return Response(data) |
/*
* @author Ludovic Bertin
* @version 1.0
* date 10/08/2001
*/
package com.stratelia.webactiv.beans.admin;
import javax.inject.Inject;
/**
* AdminReference represents the reference to an Admin instance. It manages the access to this
* instance. The Admin objects gathers all the operations that create the organizational resources
* for a Silverpeas server instance. All objects requiring a reference to an Admin instance should
* use an instance of this class.
*/
public class AdminReference {
private final static AdminReference instance = new AdminReference();
@Inject
private Admin admin;
private AdminReference() {
}
static AdminReference getInstance() {
return instance;
}
private synchronized Admin getAdmin() {
if (admin == null) {
// case where the admin reference is used in tests running out of an IoC container context.
// maintained for compatibility reason.
admin = new Admin();
}
return admin;
}
/**
* Gets the administration service refered by this AdminReference.
* @return the admin service instance.
*/
public static Admin getAdminService() {
return getInstance().getAdmin();
}
} |
// ColoredShape.cpp: implementation of the CColoredShape class.
#include "stdafx.h"
#include "ColoredShape.h"
// Construction/Destruction
CColoredShape::CColoredShape()
{
m_colorName = Quantity_NOC_RED;
}
CColoredShape::CColoredShape(const <API key> aColor, const TopoDS_Shape& aShape)
{
m_colorName = aColor;
m_shapeObject = aShape;
}
IMPLEMENT_SERIAL(CColoredShape, CObject,1);
// This schema contains all the Persistent Geometry and Topology
#include <ShapeSchema.hxx>
// Tools to store TopoDS_Shape
#include <MgtBRep.hxx>
#include <PTopoDS_HShape.hxx>
#include <<API key>.hxx>
#include <TopoDS_Shape.hxx>
// Tools to put Persistent Object in an archive
#include <FSD_Archive.hxx>
#include <Storage_Data.hxx>
#include <Storage_HSeqOfRoot.hxx>
#include <Storage_Root.hxx>
#include <<API key>.hxx>
void CColoredShape::Serialize(CArchive & ar)
{
CObject::Serialize(ar);
// an I/O driver
FSD_Archive f( &ar );
// the applicative Schema containing Persistent Topology and Geometry
// Note that it inherits from the class Storage_Schema
Handle(ShapeSchema) s = new ShapeSchema;
if ( ar.IsStoring() )
{
// Store the color in the archive
ar << m_colorName;
//Create the persistent Shape
<API key> aMap;
Handle(PTopoDS_HShape) aPShape =
MgtBRep::Translate(m_shapeObject, aMap, <API key>);
// Store the Persistent shape in the archive
Handle(Storage_Data) d = new Storage_Data;
d->AddRoot("ObjectName", aPShape);
s->Write( f, d);
// Check
if (d->ErrorStatus() != Storage_VSOk)
{
::MessageBox(NULL, " Error while writing... ", " Error ",MB_OK) ;
}
}
else
{
// Read the Color from the archive
Standard_Integer tmp;
ar >> tmp;
m_colorName = (<API key>) tmp;
// Read the Persistent Shape from the archive
Handle(Storage_Data) d = s->Read( f );
Handle(Storage_HSeqOfRoot) roots = d->Roots();
Handle(Standard_Persistent) p;
Handle(Storage_Root) r;
Handle(PTopoDS_HShape) aPShape;
r = roots->Value(1);
p = r->Object();
aPShape = Handle(PTopoDS_HShape)::DownCast(p);
// Create the shape
<API key> aMap;
MgtBRep::Translate(aPShape,aMap,m_shapeObject,<API key>);
}
}
void CColoredShape::Display(Handle(<API key>)& anAIScontext)
{
Handle(AIS_Shape) ais = new AIS_Shape(m_shapeObject);
anAIScontext->SetColor(ais, m_colorName);
anAIScontext->Display(ais, Standard_False);
} |
/* body{font-family:Georgia,"Times New Roman",Times,serif;margin:0;padding:0;background-color:#F3F3F3;} */
body{
font: 16px/1.4 Helvetica,arial,nimbussansl,liberationsans,freesans,clean,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
font-family: Helvetica,arial,nimbussansl,liberationsans,freesans,clean,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 1.4;
font-size-adjust: none;
font-stretch: normal;
x-system-font: none;
<API key>: normal;
<API key>: normal;
font-kerning: auto;
font-synthesis: weight style;
<API key>: normal;
font-variant-caps: normal;
<API key>: normal;
<API key>: normal;
<API key>: normal;
<API key>: normal;
color: #333;
margin:0;padding:0;background-color:#F3F3F3;}
#divbodyholder{padding:5px;background-color:#DDD;max-width:874px;margin:24px auto;}
#divbody{border:solid 1px #ccc;background-color:#fff;padding:0px 48px 24px 48px;top:0;}
.headerholder{background-color:#f9f9f9;border-top:solid 1px #ccc;border-left:solid 1px #ccc;border-right:solid 1px #ccc;}
.header{width:100%;max-width:800px;margin:0px auto;padding-top:24px;padding-bottom:8px;text-align:right}
.content{margin-bottom:5%;}
.nomargin{margin:0;}
.description{margin-top:10px;border-top:solid 1px #666;padding:10px 0;}
h3{font-size:20pt;width:100%;font-weight:bold;margin-top:32px;margin-bottom:0;}
.clear{clear:both;}
#footer{padding-top:10px;border-top:solid 1px #666;color:#333333;text-align:center;font-size:small;font-family:"Courier New","Courier",monospace;}
a{text-decoration:none;color:#003366 !important;}
a:visited{text-decoration:none;color:#336699 !important;}
blockquote{background-color:#f9f9f9;border-left:solid 4px #e9e9e9;margin-left:12px;padding:12px 12px 12px 24px;}
blockquote img{margin:12px 0px;}
blockquote iframe{margin:12px 0px;}
/*
blockquote:before {background-color:#f9f9f9;border-left:solid 4px #e9e9e9;margin-left:12px;padding:12px 12px 12px 24px;content: open-quote;}
blockquote:after {background-color:#f9f9f9;border-left:solid 4px #e9e9e9;margin-left:12px;padding:12px 12px 12px 24px;content: close-quote;}
welcome_landing{
font-family: 'Ubuntu', sans-serif;
font-weigth: 400px;
font-size: 40px;
text-shadow: 4px 4px 4px #aaa;
}
.anchor A {
font-family: 'Ubuntu', sans-serif;
font-size: 20px;
text-shadow: 4px 4px 4px #aaa;
text-decoration:none;
.ubuntu_14 {
font-family: 'Ubuntu', sans-serif;
font-size: 14px;
text-decoration:none;
}
.ubuntu_mono {
font-family: 'Ubuntu Mono';
font-size: 50px;
}
.box-shadow {
-moz-box-shadow: 7px 7px 7px #7C7C7C;
-webkit-box-shadow: 7px 7px 7px #7C7C7C;
box-shadow: 7px 7px 7px #7C7C7C;
}
.img-shadow {
float:left;
background: url(shadowAlpha.png) no-repeat bottom right !important;
background: url(shadow.gif) no-repeat bottom right;
margin: 10px 0 0 10px !important;
margin: 10px 0 0 5px;
}
.img-shadow img {
display: block;
position: relative;
background-color: #fff;
border: 1px solid #a9a9a9;
margin: -6px 6px 6px -6px;
padding: 4px;
} */ |
.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; }
.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; }
.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; }
.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; }
.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; }
.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; }
.ui-tabs .ui-tabs-hide { display: none !important; }
====
* jQuery UI Tabs 1.10.4
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http:
*
* http://api.jqueryui.com/tabs/#theming
*/
.ui-tabs {
position: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
padding: .2em;
}
.ui-tabs .ui-tabs-nav {
margin: 0;
padding: .2em .2em 0;
}
.ui-tabs .ui-tabs-nav li {
list-style: none;
float: left;
position: relative;
top: 0;
margin: 1px .2em 0 0;
border-bottom-width: 0;
padding: 0;
white-space: nowrap;
}
.ui-tabs .ui-tabs-nav .ui-tabs-anchor {
float: left;
padding: .5em 1em;
text-decoration: none;
}
.ui-tabs .ui-tabs-nav li.ui-tabs-active {
margin-bottom: -1px;
padding-bottom: 1px;
}
.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor,
.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor,
.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor {
cursor: text;
}
.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor {
cursor: pointer;
}
.ui-tabs .ui-tabs-panel {
display: block;
border-width: 0;
padding: 1em 1.4em;
background: none;
}
>>>> Weber-Wk-1 |
# REST API Backend for the Radiocontrol Project
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from django.contrib import admin
# Register your models here. |
<!DOCTYPE html>
<html lang="en">
<head>
<title>A markdown powered article</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="./theme/css/main.css" type="text/css" />
<link href="/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="A Pelican Blog Atom Feed" />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<!--[if lte IE 7]>
<link rel="stylesheet" type="text/css" media="all" href="./css/ie.css"/>
<script src="./js/IE8.js" type="text/javascript"></script><![endif]
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" media="all" href="./css/ie6.css"/><![endif]
</head>
<body id="index" class="home">
<header id="banner" class="body">
<h1><a href="./">A Pelican Blog </a></h1>
<nav><ul>
<li><a href="./pages/this-is-a-test-page.html">This is a test page</a></li>
<li ><a href="./category/bar.html">bar</a></li>
<li class="active"><a href="./category/cat1.html">cat1</a></li>
<li ><a href="./category/misc.html">misc</a></li>
<li ><a href="./category/yeah.html">yeah</a></li>
</ul></nav>
</header><!-- /#banner -->
<section id="content" class="body">
<article>
<header>
<h1 class="entry-title">
<a href="./<API key>.html" rel="bookmark"
title="Permalink to A markdown powered article">A markdown powered article</a></h1>
</header>
<div class="entry-content">
<footer class="post-info">
<abbr class="published" title="2011-04-20T00:00:00">
Wed 20 April 2011
</abbr>
<p>In <a href="./category/cat1.html">cat1</a>. </p>
</footer><!-- /.post-info --> <p>You're mutually oblivious.</p>
<p><a href="./unbelievable.html">a root-relative link to unbelievable</a>
<a href="./unbelievable.html">a file-relative link to unbelievable</a></p>
</div><!-- /.entry-content -->
</article>
</section>
<section id="extras" class="body">
</section><!-- /#extras -->
<footer id="contentinfo" class="body">
<address id="about" class="vcard body">
Proudly powered by <a href="http:
</address><!-- /#about -->
<p>The theme is by <a href="http://coding.smashingmagazine.com/2009/08/04/<API key>/">Smashing Magazine</a>, thanks!</p>
</footer><!-- /#contentinfo -->
</body>
</html> |
package ruby.ninja.experiments.zahlenpuzzle.token;
import org.junit.Test;
import rubys.ninja.experiments.zahlenpuzzle.token.NumericalToken;
import static org.junit.Assert.assertSame;
public class NumericalTokenTest {
@Test
public void testValueWorks() {
NumericalToken token = new NumericalToken(1);
assertSame(1, token.getValue());
}
} |
/* global moment */
(function() {
'use strict';
$.widget("custom.<API key>", {
options: {
serverUrl: 'http://localhost:8000'
},
_create: function() {
// TODO: Paging threads
this.element.on('click', '.chat-thread', $.proxy(this._onChatThreadClick, this));
$(document.body).on('connect', $.proxy(this._onConnect, this));
$(document.body).on('pageChange', $.proxy(this._onPageChange, this));
$(document.body).on('message:<API key>', $.proxy(this._onThreadsAdded, this));
$(document.body).on('message:<API key>', $.proxy(this.<API key>, this));
$(document.body).on('message:messages-added', $.proxy(this._onMessagesAdded, this));
},
joinThread: function(threadId, threadTitle, threadDescription, threadLogo, answerType, predefinedTexts, pollAnswer, allowOtherAnswer, expiresAt) {
$(".chat-container").<API key>('joinThread', threadId, threadTitle, threadDescription, threadLogo, 'Keskustelu', answerType, predefinedTexts, pollAnswer, allowOtherAnswer, expiresAt);
},
reloadChatThreads: function () {
this._loadChatThreads();
},
_addThreads: function (threads) {
const sessionId = $(document.body).<API key>('sessionId');
$('.conversations-view').removeClass('loading');
if (!threads.length) {
$('.conversations-view ul').html(<API key>());
} else {
threads.forEach((thread) => {
const threadData = Object.assign(thread, {
imageUrl: thread.imageUrl ? `${thread.imageUrl}?sessionId=${sessionId}` : 'gfx/placeholder.png',
<API key>: thread.latestMessage ? moment(thread.latestMessage).locale('fi').format('LLLL') : null
});
if ($(`.chat-thread[data-id=${thread.id}]`).length) {
if (!threadData.latestMessage) {
let prevLatestMessage = $(`.chat-thread[data-id=${thread.id}]`).attr('data-latest-message');
if (prevLatestMessage) {
threadData.latestMessage = prevLatestMessage;
threadData.<API key> = moment(prevLatestMessage).locale('fi').format('LLLL');
}
}
if(typeof threadData.read === 'undefined') {
threadData.read = $(`.chat-thread[data-id=${thread.id}]`).hasClass('read');
}
$(`.chat-thread[data-id=${thread.id}]`).replaceWith(pugChatThread(threadData));
} else {
$('.conversations-view ul').append(pugChatThread(threadData));
}
});
}
},
_onPageChange: function (event, data) {
if (data.activePage === 'conversations') {
this._loadChatThreads();
$('.menu-item[data-page="conversations"]').removeClass('unread');
$(document.body).<API key>('sendMessage', {
'type': 'mark-item-read',
'id': 'conversations'
});
}
},
_onChatThreadClick: function (event) {
event.preventDefault();
if ('browser' === device.platform) {
$('.item-row').removeClass('active');
$(event.target).closest('.item-row').addClass('active');
}
$("body").addClass("<API key>");
const element = $(event.target).closest('.chat-thread');
element.removeClass('unread').addClass('read');
const threadId = $(element).attr('data-id');
const threadTitle = $(element).attr('data-thread-title');
const threadDescription = $(element).attr('<API key>');
const threadImage = $(element).attr('data-thread-image');
const answerType = $(element).attr('data-answer-type');
const predefinedTexts = JSON.parse($(element).attr('<API key>') || "[]");
const allowOtherAnswer = "true" === $(element).attr('<API key>');
const expiresAt = $(element).attr('data-expires-at');
const pollAnswer = $(element).attr('data-poll-answer');
this.joinThread(threadId, threadTitle, threadDescription, threadImage, answerType, predefinedTexts, pollAnswer, allowOtherAnswer, expiresAt);
},
_loadChatThreads: function () {
if ($('.conversations-view ul').is(':empty')) {
$('.conversations-view').addClass('loading');
}
$(document.body).<API key>('sendMessage', {
'type': '<API key>'
});
},
_loadUnreadStatus: function () {
$(document.body).<API key>('sendMessage', {
'type': '<API key>'
});
},
_onConnect: function (event, data) {
this._loadUnreadStatus();
},
_onThreadsAdded: function (event, data) {
this._addThreads(data.threads);
},
<API key>: function (event, data) {
$('.menu-item[data-page="conversations"]').addClass('unread');
},
_onMessagesAdded: function (event, data) {
if ($(document.body).pakkasmarjaBerries('activePage') === 'conversations') {
return;
}
if (data['thread-type'] === "conversation") {
$('.menu-item[data-page="conversations"]').addClass('unread');
}
}
});
})(); |
module Api
class ChildrenController < ApiController
before_action :<API key>, :only => :show
before_action :sanitize_params, :only => [:update, :create, :unverified]
def index
authorize! :index, Child
render :json => Child.all
end
def show
authorize! :show, Child
child = Child.get params[:id]
if child
render :json => child.compact
else
render :json => '', :status => 404
end
end
def create
authorize! :create, Child
<API key>(params)
@child['<API key>'] = <API key>
@child.save!
render :json => @child.compact
end
def update
authorize! :update, Child
child = update_child_from params
child.save!
render :json => child.compact
end
def unverified
params[:child][:photo] = params[:current_photo_key] unless params[:current_photo_key].nil?
if params[:child][:_id]
child = Child.get(params[:child][:_id])
child = <API key> child, params
child.save
render :json => child.compact
else
params[:child].merge!(:verified => current_user.verified?)
child = <API key>(params)
child.attributes = {:<API key> => current_user.full_name}
if child.save
render :json => child.compact
end
end
end
def ids
render :json => Child.<API key>
end
private
def sanitize_params
super :child
params['child']['histories'] = JSON.parse(params['child']['histories']) if params['child'] && params['child']['histories'].is_a?(String) # histories might come as string from the mobile client.
rescue JSON::ParserError
render :json => {:error => I18n.t('errors.models.enquiry.malformed_query')}, :status => 422
end
def <API key>(params)
@child = Child.by_short_id(:key => child_short_id(params)).first if params[:child][:unique_identifier]
if @child.nil?
@child = Child.new_with_user_name(current_user, params[:child])
else
@child = update_child_from(params)
end
end
def child_short_id(params)
params[:child][:short_id] || params[:child][:unique_identifier].last(7)
end
def update_child_from(params)
child = @child || Child.get(params[:id]) || Child.new_with_user_name(current_user, params[:child])
child.<API key>(params, current_user)
child
end
end
end |
var _ = require('lodash');
var util = require('../../util');
var MappingType = {
is: function(typeName) {
return _.startsWith(typeName, 'mapping(');
},
init: function(typeName, typeCreator, contract) {
this.type = typeName;
var parts = /^mapping\((.*) => (.*)\)/.exec(typeName);
var keyTypeName = parts[1];
this.keyType = typeCreator.create(keyTypeName, contract);
var valueTypeName = parts[2];
this.valueType = typeCreator.create(valueTypeName, contract);
this.storageType = 'storage ref';
this.stackSize = 1;
return this;
},
retrieve: function(storage, hashDict, position) {
var self = this;
if (position.offset > 0) {
util.inc(position.index);
position.offset = 0;
}
var result = MappingType.isPrototypeOf(this.valueType) ?
this.retrieveMapping(storage, hashDict, position) :
this.retrieveNotMapping(storage, hashDict, position);
util.inc(position.index);
return result;
},
retrieveNotMapping: function(storage, hashDict, position) {
var self = this;
return _(storage)
.map(function(entry) {
var hashDetails = _.find(hashDict, function(details) {
return details.hash.equals(entry.key);
});
var result;
if (hashDetails) {
result = {
key: hashDetails.hash,
keySrc: hashDetails.src,
value: entry.value
};
}
return result;
})
.compact()
.filter(function(entry) {
return entry.keySrc.length >= 32 &&
entry.keySrc.slice(entry.keySrc.length - 32).equals(position.index);
})
.map(function(entry) {
var position = {
index: new Buffer(entry.key),
offset: 0
};
return [
self.keyType.parseValue(entry.keySrc.slice(0, entry.keySrc.length - 32)),
self.valueType.retrieve(storage, hashDict, position)
];
})
.object()
.value();
},
retrieveMapping: function(storage, hashDict, position) {
var self = this;
return _(hashDict)
.filter(function(details) {
return details.src.length >= 32 &&
details.src.slice(details.src.length - 32).equals(position.index);
})
.map(function(details) {
var internalPosition = {
index: new Buffer(details.hash),
offset: 0
};
var value = self.valueType.retrieve(storage, hashDict, internalPosition);
return Object.keys(value).length > 0 ?
[
self.keyType.parseValue(details.src.slice(0, details.src.length - 32)),
value
] :
null;
})
.compact()
.object()
.value();
},
retrieveStack: function(stack, index) {
return '[not implemented]';
}
};
module.exports = MappingType; |
require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the Admin::InventoriesHelper. For example:
# describe Admin::InventoriesHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# helper.concat_strings("this","that").should == "this that"
# end
# end
# end
describe Admin::InventoriesHelper do
pending "add some examples to (or delete) #{__FILE__}"
end |
<?php
class <API key> extends BaseAdminController
{
public function actionList()
{
$admin = new <API key>(<API key>::model(), $this);
$admin->setListFields(array(
'id',
'drugs.tallmanlabel',
'drugs.dose_unit',
));
$admin->setCustomDeleteURL('/OphDrPrescription/admin/commondrugsdelete');
$admin->setCustomSaveURL('/OphDrPrescription/admin/commondrugsadd');
$admin->setModelDisplayName('Common Drugs List');
$admin->setFilterFields(
array(
array(
'label' => 'Site',
'dropDownName' => 'site_id',
'defaultValue' => Yii::app()->session['selected_site_id'],
'listModel' => Site::model(),
'listIdField' => 'id',
'listDisplayField' => 'short_name',
),
array(
'label' => 'Subspecialty',
'dropDownName' => 'subspecialty_id',
'defaultValue' => Firm::model()->findByPk(Yii::app()->session['selected_firm_id'])-><API key>->subspecialty_id,
'listModel' => Subspecialty::model(),
'listIdField' => 'id',
'listDisplayField' => 'name',
),
)
);
// we set default search options
if ($this->request->getParam('search') == '') {
$admin->getSearch()->initSearch(array(
'filterid' => array(
'site_id' => Yii::app()->session['selected_site_id'],
'subspecialty_id' => Firm::model()->findByPk(Yii::app()->session['selected_firm_id'])-><API key>->subspecialty_id,
),
)
);
}
$admin-><API key>(
array(
'fieldName' => 'drug_id',
'jsonURL' => '/OphDrPrescription/default/DrugList',
'placeholder' => 'search for drugs',
)
);
//$admin->searchAll();
$admin->listModel();
}
} |
# -*- coding: utf-8 -*-
import unicodecsv
from collections import Counter
from django.http import HttpResponse
from django.shortcuts import render
from .models import Disciplina, Docente, Pesquisa, Extensao, Administrativo
def query_estudantes(query):
result = [
['1-6', query.filter(estudantes__gte=1, estudantes__lte=6).count()],
['7-15', query.filter(estudantes__gte=7, estudantes__lte=15).count()],
['16-25', query.filter(estudantes__gte=16, estudantes__lte=25).count()],
['26-50', query.filter(estudantes__gte=26, estudantes__lte=50).count()],
['51-70', query.filter(estudantes__gte=51, estudantes__lte=70).count()],
['Mais que 70', query.filter(estudantes__gt=70).count()],
]
return result
def RelatorioEnsino(request):
if 'centro' in request.GET and request.GET['centro']:
centro = request.GET['centro']
turmas = Disciplina.objects.filter(docente__centro=centro)
else:
centro = ''
turmas = Disciplina.objects.all()
if 'semestre' in request.GET and request.GET['semestre']:
semestre = request.GET['semestre']
turmas = turmas.filter(semestre=semestre)
else:
semestre = ''
teoricas = turmas.filter(tipo='teorica')
praticas = turmas.filter(tipo='pratica')
estagio = turmas.filter(tipo='estagio')
turmas_tipo = [
('Turmas Teóricas', teoricas.count()),
('Turmas Práticas', praticas.count()),
('Turmas de Estágio', estagio.count())
]
turmas_multicampi = turmas.filter(multicampia=True).count()
multicampia = [
('Turmas sem Multicampia', turmas.count() - turmas_multicampi),
('Turmas Multicampi', turmas_multicampi)
]
turmas_nivel = [
('Turmas de Graduacao', turmas.filter(nivel='graduacao').count()),
('Turmas de Pós-Graduação', turmas.filter(nivel='pos').count())
]
estudantes_turmas = query_estudantes(turmas)
<API key> = query_estudantes(teoricas)
<API key> = query_estudantes(praticas)
<API key> = query_estudantes(estagio)
return render(request, 'relatorio_ensino.html', {
'centro': centro,
'semestre': semestre,
'turmas_tipo': turmas_tipo,
'multicampia': multicampia,
'turmas_nivel': turmas_nivel,
'estudantes_turmas': estudantes_turmas,
'<API key>': <API key>,
'<API key>': <API key>,
'<API key>': <API key>,
})
def RelatorioDocente(request):
if 'centro' in request.GET and request.GET['centro']:
centro = request.GET['centro']
docentes_ensino = Disciplina.objects.filter(docente__centro=centro)
docentes_pesquisa = Pesquisa.objects.filter(docente__centro=centro)
docentes_extensao = Extensao.objects.filter(docente__centro=centro)
docentes_admin = Administrativo.objects.filter(docente__centro=centro)
num_docentes = Docente.objects.filter(centro=centro).count()
else:
centro = ''
docentes_ensino = Disciplina.objects.all()
docentes_pesquisa = Pesquisa.objects.all()
docentes_extensao = Extensao.objects.all()
docentes_admin = Administrativo.objects.all()
num_docentes = Docente.objects.all().count()
if 'semestre' in request.GET and request.GET['semestre']:
semestre = request.GET['semestre']
docentes_ensino = docentes_ensino.filter(semestre=semestre)
docentes_pesquisa = docentes_pesquisa.filter(semestre=semestre)
docentes_extensao = docentes_extensao.filter(semestre=semestre)
docentes_admin = docentes_admin.filter(semestre=semestre)
else:
semestre = ''
docentes_ensino = [disciplina.docente
for disciplina in docentes_ensino.distinct('docente')]
docentes_pesquisa = [projeto.docente
for projeto in docentes_pesquisa.distinct('docente')]
docentes_extensao = [projeto.docente
for projeto in docentes_extensao.distinct('docente')]
docentes_ens_pes = [docente for docente in docentes_pesquisa
if docente in docentes_ensino]
docentes_ens_ext = [docente for docente in docentes_extensao
if docente in docentes_ensino]
<API key> = [docente for docente in docentes_ens_pes
if docente in docentes_ens_ext]
num_docentes_ensino = len(docentes_ensino)
<API key> = len(docentes_pesquisa)
<API key> = len(docentes_extensao)
<API key> = docentes_admin.filter(afastamento=True) \
.distinct('docente').count()
docentes_admin = docentes_admin \
.filter(cargo__in=['fg', 'cd', 'fuc'])
ensino = [
['Com atividades de ensino', num_docentes_ensino],
['Sem atividades de ensino', num_docentes - num_docentes_ensino]
]
pesquisa = [
['Com atividades de pesquisa', <API key>],
['Sem atividades de pesquisa', num_docentes - <API key>]
]
extensao = [
['Com atividades de extensão', <API key>],
['Sem atividades de extensão', num_docentes - <API key>]
]
ens_pes_ext = [
['Sim', len(<API key>)],
['Não', num_docentes - len(<API key>)]
]
ens_pes = [
['Sim', len(docentes_ens_pes)],
['Não', num_docentes - len(docentes_ens_pes)]
]
ens_ext = [
['Sim', len(docentes_ens_ext)],
['Não', num_docentes - len(docentes_ens_ext)]
]
administrativo = [
['Com atividades administrativas', docentes_admin
.distinct('docente').count()],
['Sem atividades administrativas', num_docentes - docentes_admin
.distinct('docente').count()]
]
admin_detalhes = [
['FG', docentes_admin.filter(cargo='fg').distinct('docente').count()],
['CD', docentes_admin.filter(cargo='cd').distinct('docente').count()],
['Coordenação de Colegiado', docentes_admin.filter(cargo='fuc')
.distinct('docente').count()],
]
afastamento = [
['Docentes afastados', <API key>],
['Docentes em exercício', num_docentes - <API key>]
]
return render(request, 'relatorio_docente.html', {
'centro': centro,
'semestre': semestre,
'ensino': ensino,
'ens_pes_ext': ens_pes_ext,
'ens_pes': ens_pes,
'ens_ext': ens_ext,
'pesquisa': pesquisa,
'extensao': extensao,
'administrativo': administrativo,
'admin_detalhes': admin_detalhes,
'afastamento': afastamento
})
def filtro_por_centro(data):
result = [
['CAHL', data.filter(docente__centro='cahl').count()],
['CCAAB', data.filter(docente__centro='ccaab').count()],
['CCS', data.filter(docente__centro='ccs').count()],
['CETEC', data.filter(docente__centro='cetec').count()],
['CFP', data.filter(docente__centro='cfp').count()],
]
return result
def RelatorioProjetos(request):
return render(request, 'relatorio_projetos.html', {
'pesquisa': filtro_por_centro(Pesquisa.objects.all()),
'extensao': filtro_por_centro(Extensao.objects.all()),
'pesquisa_20131': filtro_por_centro(Pesquisa.sem_20131.all()),
'pesquisa_20132': filtro_por_centro(Pesquisa.sem_20132.all()),
'extensao_20131': filtro_por_centro(Extensao.sem_20131.all()),
'extensao_20132': filtro_por_centro(Extensao.sem_20132.all()),
})
def valores_ch(data):
result = [
['Menos que 8', sum([item[1] for item in data.items() if item[0]<136])],
['8h', sum([item[1] for item in data.items() if item[0]>=136 and item[0]<153])],
['9h', sum([item[1] for item in data.items() if item[0]>=153 and item[0]<170])],
['10h', sum([item[1] for item in data.items() if item[0]>=170 and item[0]<187])],
['11h', sum([item[1] for item in data.items() if item[0]>=187 and item[0]<204])],
['12h', sum([item[1] for item in data.items() if item[0]>=204 and item[0]<221])],
['13h', sum([item[1] for item in data.items() if item[0]>=221 and item[0]<238])],
['14h', sum([item[1] for item in data.items() if item[0]>=238 and item[0]<255])],
['15h', sum([item[1] for item in data.items() if item[0]>=255 and item[0]<272])],
['16h', sum([item[1] for item in data.items() if item[0]>=272 and item[0]<289])],
['Mais que 16h', sum([item[1] for item in data.items() if item[0]>289])],
]
return result
def <API key>(request):
if 'centro' in request.GET and request.GET['centro']:
centro = request.GET['centro']
docentes = Docente.objects.filter(centro=centro)
else:
centro = ''
docentes = Docente.objects.all()
ensino_20131 = valores_ch(Counter([i.ch_ensino('20131') for i in docentes]))
ensino_20132 = valores_ch(Counter([i.ch_ensino('20132') for i in docentes]))
return render(request, 'relatorio_ch.html', {
'centro': centro,
'ensino_20131': ensino_20131,
'ensino_20132': ensino_20132,
})
def RelatorioGeral(request):
if 'centro' in request.GET and request.GET['centro']:
centro = request.GET['centro']
docentes = Docente.objects.filter(centro=centro)
else:
centro = ''
docentes = Docente.objects.all()
if 'semestre' in request.GET and request.GET['semestre']:
semestre = request.GET['semestre']
else:
semestre = '20131'
return render(request, 'relatorio_geral.html',{
'docentes': docentes,
'centro': centro,
'semestre': semestre
})
def ExportarDisciplina(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="disciplinas.csv"'
writer = unicodecsv.writer(response, encoding='utf-8')
writer.writerow(['Centro', 'Código', 'Nome', 'Docente', 'Semestre', 'Tipo',
'Nível', 'Multicampia', 'Carga horária', 'Estudantes'])
for disciplina in Disciplina.objects.all():
writer.writerow([disciplina.docente.centro, disciplina.codigo,
disciplina.nome, disciplina.docente, disciplina.semestre,
disciplina.tipo, disciplina.nivel, disciplina.multicampia,
disciplina.cargahoraria, disciplina.estudantes])
return response
def ExportarPesquisa(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="pesquisa.csv"'
writer = unicodecsv.writer(response, encoding='utf-8')
writer.writerow(['Centro', 'Nome', 'Docente', 'Semestre', 'Área',
'Financiador', 'Carga horária', 'Estudantes de Graduação',
'Estudantes de Pós', 'Bolsistas PIBIC/PIBITI', 'Bolsistas PPQ',
'Voluntários', 'Parceria Institucional', 'Parceria Interinstitucional'])
for projeto in Pesquisa.objects.all():
writer.writerow([projeto.docente.centro, projeto.nome, projeto.docente,
projeto.semestre, projeto.area, projeto.financiador,
projeto.cargahoraria, projeto.<API key>,
projeto.estudantes_pos, projeto.bolsistas_pibic,
projeto.bolsistas_ppq, projeto.voluntarios, projeto.parceria,
projeto.parceria_inter])
return response
def ExportarExtensao(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="extensao.csv"'
writer = unicodecsv.writer(response, encoding='utf-8')
writer.writerow(['Centro', 'Nome', 'Docente', 'Semestre', 'Área',
'Financiador', 'Carga horária', 'Estudantes de Graduação',
'Estudantes de Pós', 'Bolsistas PIBEX', 'Bolsistas PPQ',
'Voluntários', 'Parceria Institucional', 'Parceria Interinstitucional'])
for projeto in Extensao.objects.all():
writer.writerow([projeto.docente.centro, projeto.nome, projeto.docente,
projeto.semestre, projeto.area, projeto.financiador,
projeto.cargahoraria, projeto.<API key>,
projeto.estudantes_pos, projeto.bolsistas_pibex,
projeto.bolsistas_ppq, projeto.voluntarios, projeto.parceria,
projeto.parceria_inter])
return response
def <API key>(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="administrativo.csv"'
writer = unicodecsv.writer(response, encoding='utf-8')
writer.writerow(['Centro', 'Docente', 'Semestre', 'Afastamento', 'Cargo',
'Comissões'])
for atividade in Administrativo.objects.all():
writer.writerow([atividade.docente.centro, atividade.docente,
atividade.semestre, atividade.afastamento, atividade.cargo,
atividade.comissoes])
return response |
// Core.Agent.TicketProcess.js - provides the special module functions for TicketProcess
"use strict";
var Core = Core || {};
Core.Agent = Core.Agent || {};
/**
* @namespace Core.Agent.TicketProcess
* @memberof Core.Agent
* @author OTRS AG
* @description
* This namespace contains the special module functions for TicketProcess.
*/
Core.Agent.TicketProcess = (function (TargetNS) {
/**
* @name Init
* @memberof Core.Agent.TicketProcess
* @function
* @description
* This function initializes the special module functions.
*/
TargetNS.Init = function () {
$('#ProcessEntityID').bind('change', function () {
var Data = {
Action: 'AgentTicketProcess',
Subaction: '<API key>',
ProcessEntityID: $('#ProcessEntityID').val(),
IsAjaxRequest: 1,
IsMainWindow: 1
};
if ($('
$.extend(Data, {
IsMainWindow: 0,
IsProcessEnroll: 1,
TicketID: $('#TicketID').val()
});
}
// remove/destroy CKEditor instances
// This is needed to initialize other instances (in other activity dialogs)
// without a page reload
if (typeof CKEDITOR !== 'undefined' && CKEDITOR.instances) {
$.each(CKEDITOR.instances, function (Key) {
CKEDITOR.instances[Key].destroy();
});
}
if ($('#ProcessEntityID').val()) {
// remove the content of the activity dialog
$('#<API key>').empty();
// fade out the empty container so it will fade in again on processes change
// is not recommended to empty after fade out at this point since the transition offect
// will not look so nice
$('#<API key>').fadeOut('fast');
// show loader icon
$('#AJAXLoader').removeClass('Hidden');
// get new ActivityDialog content
Core.AJAX.FunctionCall(
Core.Config.Get('CGIHandle'),
Data,
function (Response) {
var $ElementToUpdate = $('#<API key>'),
JavaScriptString = '',
ErrorMessage;
if (!Response) {
// We are out of the OTRS App scope, that's why an exception would not be caught. Therefor we handle the error manually.
Core.Exception.HandleFinalError(new Core.Exception.ApplicationError("No content received.", 'CommunicationError'));
$('#AJAXLoader').addClass('Hidden');
}
else if ($ElementToUpdate && isJQueryObject($ElementToUpdate) && $ElementToUpdate.length) {
$ElementToUpdate.get(0).innerHTML = Response;
$ElementToUpdate.find('script').each(function() {
JavaScriptString += $(this).html();
$(this).remove();
});
$ElementToUpdate.fadeIn();
try {
/*jslint evil: true */
eval(JavaScriptString);
}
catch (ignore) {}
// Handle special server errors (Response = <div class="ServerError" data-message="Message"></div>)
// Check if first element has class 'ServerError'
if ( $ElementToUpdate.children().first().hasClass('ServerError') ) {
ErrorMessage = $ElementToUpdate.children().first().data('message');
// Add class ServerError to the process select element
$('#ProcessEntityID').addClass('ServerError');
// Set a custom error message to the proccess select element
$('#<API key>').children().first().text(ErrorMessage);
}
Core.Form.Validate.Init();
// Register event for tree selection dialog
Core.UI.TreeSelection.InitTreeSelection();
// move help triggers into field rows for dynamic fields
$('.Row > .FieldHelpContainer').each(function () {
if (!$(this).next('label').find('.Marker').length) {
$(this).prependTo($(this).next('label'));
}
else {
$(this).insertAfter($(this).next('label').find('.Marker'));
}
});
// Initially display dynamic fields with TreeMode = 1 correctly
Core.UI.TreeSelection.<API key>();
$('#AJAXLoader').addClass('Hidden');
$('#AJAXDialog').val('1');
}
else {
// We are out of the OTRS App scope, that's why an exception would not be caught. Therefor we handle the error manually.
Core.Exception.HandleFinalError(new Core.Exception.ApplicationError("No such element id: " + $ElementToUpdate.attr('id') + " in page!", 'CommunicationError'));
$('#AJAXLoader').addClass('Hidden');
}
}, 'html');
}
else {
$('#<API key>').fadeOut(400, function() {
$('#<API key>').empty();
});
}
return false;
});
};
return TargetNS;
}(Core.Agent.TicketProcess || {})); |
<!
Copyright (C) 2019 OpenMotics BV
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http:
<template>
<require from="./styles.css"></require>
<section class="content-header">
<h1 class="pull-left">${'pages.setup.floorsandrooms.title' & t}</h1>
<div class="btn-group pull-right">
<a class="btn btn-sm btn-default" route-href="route: setup.initialisation">
<span class="fa" translate.bind="'icons.left' & t"></span> ${'pages.setup.initialisation.title' & t}
</a>
<a class="active btn btn-sm btn-default disabled">
<i class="fa" translate.bind="'pages.setup.floorsandrooms.icon' & t"></i> ${'pages.setup.floorsandrooms.title' & t}
</a>
<a class="btn btn-sm btn-default" route-href="route: setup.outputs">
${'pages.setup.outputs.title' & t} <span class="fa" translate.bind="'icons.right' & t"></span>
</a>
</div>
</section>
<section class="content clear-both floors-page">
<div class="box box-warning">
<div class="box-header with-border">
<h5 class="box-title">${'pages.setup.floorsandrooms.floors' & t}</h5>
</div>
<p class="description">${'pages.setup.floorsandrooms.description' & t}</p>
<table class="table table-hover">
<thead>
<tr>
<td></td>
<td>${'pages.setup.floorsandrooms.table.name' & t}</td>
<td>${'pages.setup.floorsandrooms.table.rooms' & t}</td>
<td>${'pages.setup.floorsandrooms.table.warnings' & t}</td>
<td></td>
</tr>
</thead>
<tbody>
<div if.bind="loading" class="spinner-overlay">
<i class="fa fa-spinner fa-spin"></i>
</div>
<tr repeat.for="floor of floors" click.delegate="selectedFloor = floor"
css.bind="{'background-color': selectedFloor && selectedFloor.id === floor.id ? 'rgba(0, 166, 90, 0.28)' : ''}">
<td>
<div class="sort-block" if.bind="$parent.floors.length > 1">
<i click.delegate="moveUp($index, floor)" if.bind="$index !== 0" class="fa hand"
translate.bind="'icons.up' & t"></i>
<i click.delegate="moveDown($index, floor)"
if.bind="$index !== $parent.floors.length - 1" class="fa hand"
translate.bind="'icons.down' & t"></i>
</div>
</td>
<td>
<i class="fa hand"
translate.bind="editFloor.id === floor.id ? 'icons.installed' : 'generic.editicon' & t"
click.delegate="editFloor.id === floor.id ? saveFloor() : startEditFloor(floor)"></i>
<span if.bind="editFloor.id !== floor.id">${floor.name}</span>
<input if.bind="editFloor.id === floor.id" value.bind="editFloor.name"
focus.bind="!!editFloor" blur.trigger="(editFloor = undefined) & debounce:200" />
<button if.bind="editFloor.id === floor.id" type="button" class="close au-target unset"
aria-hidden="true" aria-label="Close" click.delegate="editFloor = undefined"
au-target-id="441">
<span>×</span>
</button>
</td>
<td>${floor.roomsNames}</td>
<td class="italic">${floor.warnings}</td>
<td class="hand remove-block">
<confirm abort.delegate="removingFloorId = undefined"
request.delegate="removingFloorId = floor.id" confirm.delegate="removeFloor(floor.id)"
options.bind="{ text: 'pages.setup.floorsandrooms.table.remove' }"
working.bind="removingFloorId === floor.id && working"></confirm>
</td>
</tr>
<tr>
<td></td>
<td class="new-floor-block">
<i class="fa hand" click.delegate="addNewFloor()"
translate.bind="'pages.setup.floorsandrooms.table.plusicon' & t"></i>
<input type="text" id="floorName" class="form-control"
placeholder="${'pages.setup.floorsandrooms.table.addnewfloor' & t}"
value.bind="newFloor" keypress.delegate="handleFloorKeypress($event)">
</td>
</tr>
</tbody>
</table>
</div>
<div if.bind="selectedFloor" class="box box-success">
<div class="box-header with-border">
<h5 class="box-title">${'pages.setup.floorsandrooms.rooms' & t}</h5>
</div>
<span class="rooms-add-info">${'pages.setup.floorsandrooms.roomsadded' & t}</span>
<table class="table table-hover room-table">
<thead>
<tr>
<td class="bold">${'pages.setup.floorsandrooms.table.name' & t}</td>
<td></td>
</tr>
</thead>
<tbody>
<tr repeat.for="room of selectedFloor.rooms">
<td>
<i class="fa hand"
translate.bind="editRoom.id === room.id ? 'icons.installed' : 'generic.editicon' & t"
click.delegate="editRoom.id === room.id ? saveRoom() : startEditRoom(room)"></i>
<span if.bind="editRoom.id !== room.id">${room.name}</span>
<input if.bind="editRoom.id === room.id" value.bind="editRoom.name" focus.bind="!!editRoom"
blur.trigger="(editRoom = undefined) & debounce:200" />
<button class="close au-target unset" if.bind="editRoom.id === room.id" type="button"
aria-hidden="true" aria-label="Close"
click.delegate="editRoom = undefined" au-target-id="441">
<span>×</span>
</button>
</td>
<td class="hand remove-block">
<confirm abort.delegate="removingRoomId = undefined"
request.delegate="removingRoomId = room.id" confirm.delegate="removeRoom(room.id)"
options.bind="{ text: 'pages.setup.floorsandrooms.table.remove' }"
working.bind="removingRoomId === room.id && working"></confirm>
</td>
</tr>
<tr>
<td>
<i class="fa hand" click.delegate="addNewRoom()"
translate.bind="'pages.setup.floorsandrooms.table.plusicon' & t"></i>
<input type="text" id="roomName" class="form-control"
placeholder="${'pages.setup.floorsandrooms.table.addnewroom' & t}"
value.bind="newRoom" keypress.delegate="handleRoomKeypress($event)">
</td>
</tr>
</tbody>
</table>
</div>
<span if.bind="!selectedFloor">${'pages.setup.floorsandrooms.selectitem' & t}</span>
<div class="box box-warning" if.bind="selectedFloor">
<div class="box-header with-border">
<h5 class="box-title">${'pages.setup.floorsandrooms.information' & t}</h5>
</div>
<p class="adding-floor">${'pages.setup.floorsandrooms.addingfloorplan' & t}</p>
<span if.bind="imageLoading" class="loading-block">
<i translate.bind="'icons.loading' & t" class="fa fa-spin"></i>
</span>
<div if.bind="!imageLoading" class="content current-image-block">
<p if.bind="selectedFloor.image.url">${'pages.setup.floorsandrooms.imageinfo' & t}</p>
<p if.bind="!selectedFloor.image.url">${'pages.setup.floorsandrooms.noimage' & t}</p>
<img if.bind="selectedFloor.image.url" src.bind="selectedFloor.image.url" />
</div>
<div class="content current-image-info">
<span>
${'pages.setup.floorsandrooms.imagesize' & t: {
'width': selectedFloor.image.width || 0,
'height': selectedFloor.image.height || 0
}}
</span>
<span class="italic">${selectedFloor.warnings}</span>
<h3>${selectedFloor.image.url ? 'pages.setup.floorsandrooms.replaceImage' :
'pages.setup.floorsandrooms.attachImage' & t}</h3>
<div class="select-file-block">
<label>${'pages.setup.floorsandrooms.image' & t}</label>
<input type="file" name="image" accept=".png,.jpg,.jpeg"
change.delegate="selectedFile = $event.target.files[0]" />
</div>
<div class="upload-block">
<p>${'pages.setup.floorsandrooms.uploadformat' & t}</p>
<button disabled.bind="!selectedFile" class="btn ${selectedFile ? 'btn-primary' : '' }"
click.delegate="uploadImage()">Upload</button>
</div>
<span>${'pages.setup.floorsandrooms.tip' & t}</span>
</div>
</div>
</section>
<section class="content-header as-footer">
<div class="footer">
<a class="btn btn-sm btn-default" route-href="route: setup.initialisation">
<span class="fa" translate.bind="'icons.left' & t"></span> ${'pages.setup.initialisation.title' & t}
</a>
<a class="active btn btn-sm btn-default disabled">
<i class="fa" translate.bind="'pages.setup.floorsandrooms.icon' & t"></i> ${'pages.setup.floorsandrooms.title' & t}
</a>
<a class="btn btn-sm btn-default" route-href="route: setup.outputs">
${'pages.setup.outputs.title' & t} <span class="fa" translate.bind="'icons.right' & t"></span>
</a>
</div>
</section>
</template> |
USE `${BREAKOUT}`;
-- A participant can be part of multiple teams (because he could have participated at previous events)
-- Therefore we need to support that by adding a new join table to show all teams a participant is / was part of
CREATE TABLE user_role_teams
(
user_role_id BIGINT(20) NOT NULL,
teams_id BIGINT(20) NOT NULL,
CONSTRAINT `PRIMARY` PRIMARY KEY (user_role_id, teams_id),
CONSTRAINT <API key> FOREIGN KEY (user_role_id) REFERENCES user_role (id),
CONSTRAINT <API key> FOREIGN KEY (teams_id) REFERENCES team (id)
);
CREATE INDEX <API key>
ON user_role_teams (teams_id);
-- For all participants: Add the information about the current team to the table for all teams as well
INSERT INTO user_role_teams (SELECT
id,
current_team_id
FROM user_role
WHERE role_name = "PARTICIPANT"
AND current_team_id IS NOT NULL); |
# -*- encoding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify #
# (at your option) any later version. #
# This program is distributed in the hope that it will be useful, #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
from osv import osv
from osv import fields
class <API key>(osv.Model):
_name = 'oehealth.insured.group.member'
_columns = {
'insured_group_id': fields.many2one('oehealth.insured.group', string='Insured Group',
help='Insured Group Titular'),
'insured_id': fields.many2one('oehealth.insured', string='Insured',
help='Insured Group Member Name'),
'role': fields.many2one('oehealth.insured.group.member.role', 'Role', required=True),
'kinship': fields.many2one('oehealth.insured.group.member.kinship', 'Kinship', required=False),
'info': fields.text(string='Info'),
'tag_ids': fields.many2many('oehealth.tag',
'<API key>',
'<API key>',
'tag_id',
'Tags'),
}
<API key>() |
# <API key>: true
module Decidim
module Forms
# The data store for a Questionnaire in the Decidim::Forms component.
class Questionnaire < Forms::ApplicationRecord
include Decidim::Templates::Templatable if defined? Decidim::Templates::Templatable
include Decidim::Publicable
include Decidim::<API key>
translatable_fields :title, :description, :tos
belongs_to :questionnaire_for, polymorphic: true
has_many :questions, -> { order(:position) }, class_name: "Question", foreign_key: "<API key>", dependent: :destroy
has_many :answers, class_name: "Answer", foreign_key: "<API key>", dependent: :destroy
after_initialize :set_default_salt
# Public: returns whether the questionnaire questions can be modified or not.
def questions_editable?
has_component = questionnaire_for.respond_to? :component
(has_component && !questionnaire_for.component.published?) || answers.empty?
end
# Public: returns whether the questionnaire is answered by the user or not.
def answered_by?(user)
query = user.is_a?(String) ? { session_token: user } : { user: user }
answers.where(query).any? if questions.present?
end
def pristine?
created_at.to_i == updated_at.to_i && questions.empty?
end
private
# salt is used to generate secure hash in anonymous answers
def set_default_salt
return unless defined?(salt)
self.salt ||= Tokenizer.random_salt
end
end
end
end |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.mskcc.cbio.oncokb.dao.impl;
import java.util.List;
import net.sf.ehcache.hibernate.HibernateUtil;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.mskcc.cbio.oncokb.dao.GeneDao;
import org.mskcc.cbio.oncokb.model.Gene;
import org.mskcc.cbio.oncokb.model.GeneNumber;
/**
* handling db requests for gene, gene_alias, and gene_label
* @author jgao
*/
public class GeneDaoImpl extends GenericDaoImpl<Gene, Integer> implements GeneDao {
/**
* Get a gene by hugo symbol
* @param symbol
* @return gene object or null
*/
public Gene <API key>(String symbol) {
List<Gene> list = findByNamedQuery("<API key>", symbol);
return list.isEmpty() ? null : list.get(0);
}
/**
* Get a gene by Entrez Gene Id.
* @param entrezGeneId
* @return gene object or null.
*/
public Gene <API key>(int entrezGeneId) {
return findById(entrezGeneId);
}
} |
import { <API key> } from './<API key>' ;
export function* _dfs_postorder ( G , seen ) {
for ( let v of G.vitr( ) ) {
if ( seen.has( v ) ) continue ;
yield* <API key>( G , v , seen ) ;
}
} |
DELETE FROM `weenie` WHERE `class_Id` = 43052;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (43052, '<API key>', 2, '2019-02-10 00:00:00') /* Clothing */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (43052, 1, 2) /* ItemType - Armor */
, (43052, 4, 4096) /* ClothingPriority - OuterwearUpperArms */
, (43052, 5, 216) /* EncumbranceVal */
, (43052, 9, 2048) /* ValidLocations - UpperArmArmor */
, (43052, 16, 1) /* ItemUseable - No */
, (43052, 18, 1) /* UiEffects - Magical */
, (43052, 19, 22202) /* Value */
, (43052, 28, 235) /* ArmorLevel */
, (43052, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (43052, 105, 9) /* ItemWorkmanship */
, (43052, 106, 370) /* ItemSpellcraft */
, (43052, 107, 1814) /* ItemCurMana */
, (43052, 108, 1814) /* ItemMaxMana */
, (43052, 109, 398) /* ItemDifficulty */
, (43052, 110, 0) /* <API key> */
, (43052, 115, 0) /* ItemSkillLevelLimit */
, (43052, 131, 54) /* MaterialType - GromnieHide */
, (43052, 158, 7) /* WieldRequirements - Level */
, (43052, 159, 1) /* WieldSkillType - Axe */
, (43052, 160, 150) /* WieldDifficulty */
, (43052, 8041, 101) /* <API key> - Resting */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (43052, 22, True ) /* Inscribable */
, (43052, 100, True ) /* Dyable */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (43052, 5, -0.067) /* ManaRate */
, (43052, 13, 1) /* ArmorModVsSlash */
, (43052, 14, 0.8) /* ArmorModVsPierce */
, (43052, 15, 1) /* ArmorModVsBludgeon */
, (43052, 16, 0.5) /* ArmorModVsCold */
, (43052, 17, 1.221) /* ArmorModVsFire */
, (43052, 18, 0.3) /* ArmorModVsAcid */
, (43052, 19, 0.869) /* ArmorModVsElectric */
, (43052, 39, 1.1) /* DefaultScale */
, (43052, 165, 1) /* ArmorModVsNether */
, (43052, 8004, 9) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (43052, 1, 'Knorr Academy Pauldrons') /* Name */
, (43052, 16, 'Knorr Academy Pauldrons of Rejuvenation') /* LongDesc */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (43052, 1, 0x020000D1) /* Setup */
, (43052, 3, 0x20000014) /* SoundTable */
, (43052, 6, 0x0400007E) /* PaletteBase */
, (43052, 8, 0x06006DED) /* Icon */
, (43052, 22, 0x3400002B) /* PhysicsEffectTable */
, (43052, 8001, 2166685848) /* <API key> - Value, Usable, UiEffects, ValidLocations, Priority, Burden, Workmanship, MaterialType */
, (43052, 8003, 18) /* <API key> - Inscribable, Attackable */
, (43052, 8005, 170113) /* <API key> - CSetup, ObjScale, STable, PeTable, Position, AnimationFrame */;
INSERT INTO `<API key>` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (43052, 8040, 0xCE95002D, 142.0573, 109.8346, 19.99725, -0.539068, 0, 0, -0.842262) /* <API key> */
/* @teleloc 0xCE95002D [142.057300 109.834600 19.997250] -0.539068 0.000000 0.000000 -0.842262 */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (43052, 8000, 0xDCF98F8F) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `spell`, `probability`)
VALUES (43052, 2187, 2) /* RejuvenationSelf7 */
, (43052, 4703, 2) /* <API key> */
, (43052, 4393, 2) /* BladeBane8 */
, (43052, 4397, 2) /* BludgeonBane8 */
, (43052, 2108, 2) /* Impenetrability7 */;
INSERT INTO `<API key>` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (43052, 67110020, 128, 8)
, (43052, 67110366, 116, 12);
INSERT INTO `<API key>` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (43052, 0, 83886788, 83898160);
INSERT INTO `<API key>` (`object_Id`, `index`, `animation_Id`)
VALUES (43052, 0, 16778411); |
import i18n from './i18n';
const request = {
/**
* @param {object} options
*/
async ajax(options) {
return new Promise((resolve, reject) => {
$
.ajax({
dataType: 'json',
options,
})
.fail((jqXHR, textStatus, errorThrown) => {
if (textStatus === 'abort') {
const err = new Error(i18n('Aborted'));
err.aborted = true;
reject(err);
} else if (jqXHR.readyState === 0) {
reject(new Error(i18n('Network error')));
} else if (errorThrown instanceof Error) {
reject(errorThrown);
} else if (typeof jqXHR.responseJSON === 'object' && jqXHR.responseJSON.error) {
reject(new Error(jqXHR.responseJSON.error.message));
} else {
reject(new Error(textStatus));
}
})
.done(resolve);
});
},
/**
* @param {string} url
* @param {JQueryStatic | Node | string | object} dataOrForm
* @param {object} options
*/
post(url, dataOrForm = {}, options = {}) {
let postData;
if (dataOrForm instanceof jQuery && dataOrForm.is('form')) {
// $form
postData = dataOrForm.serialize();
} else if (dataOrForm instanceof Node && $(dataOrForm).is('form')) {
// form
postData = $(dataOrForm).serialize();
} else if (typeof dataOrForm === 'string') {
// foo=bar&box=boz
postData = dataOrForm;
} else {
// {foo: 'bar'}
postData = $.param({
csrf_token: UiContext.csrf_token,
dataOrForm,
}, true);
}
return request.ajax({
url,
method: 'post',
data: postData,
options,
});
},
/**
* @param {string} url
* @param {object} qs
* @param {object} options
*/
get(url, qs = {}, options = {}) {
return request.ajax({
url,
data: qs,
method: 'get',
options,
});
},
};
export default request; |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pyslvs_ui/entities/edit_point.ui'
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from qtpy import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(364, 596)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("icons:bearing.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
Dialog.setSizeGripEnabled(True)
Dialog.setModal(True)
self.horizontalLayout_5 = QtWidgets.QHBoxLayout(Dialog)
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.name_label = QtWidgets.QLabel(Dialog)
self.name_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.name_label.setObjectName("name_label")
self.verticalLayout.addWidget(self.name_label)
self.name_box = QtWidgets.QComboBox(Dialog)
self.name_box.setObjectName("name_box")
self.verticalLayout.addWidget(self.name_box)
self.color_label = QtWidgets.QLabel(Dialog)
self.color_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.color_label.setObjectName("color_label")
self.verticalLayout.addWidget(self.color_label)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.color_box = QtWidgets.QComboBox(Dialog)
self.color_box.setObjectName("color_box")
self.horizontalLayout_2.addWidget(self.color_box)
self.color_pick_button = QtWidgets.QPushButton(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.<API key>(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.color_pick_button.sizePolicy().hasHeightForWidth())
self.color_pick_button.setSizePolicy(sizePolicy)
self.color_pick_button.setObjectName("color_pick_button")
self.horizontalLayout_2.addWidget(self.color_pick_button)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.groupBox = QtWidgets.QGroupBox(Dialog)
self.groupBox.setObjectName("groupBox")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.groupBox)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.type_box = QtWidgets.QComboBox(self.groupBox)
self.type_box.setObjectName("type_box")
self.type_box.addItem("")
self.type_box.addItem("")
self.type_box.addItem("")
self.verticalLayout_3.addWidget(self.type_box)
self.formLayout_2 = QtWidgets.QFormLayout()
self.formLayout_2.setObjectName("formLayout_2")
self.angle_label = QtWidgets.QLabel(self.groupBox)
self.angle_label.setObjectName("angle_label")
self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.angle_label)
self.angle_box = QtWidgets.QDoubleSpinBox(self.groupBox)
self.angle_box.setMaximum(180.0)
self.angle_box.setObjectName("angle_box")
self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.angle_box)
self.verticalLayout_3.addLayout(self.formLayout_2)
self.verticalLayout.addWidget(self.groupBox)
self.pos_group = QtWidgets.QGroupBox(Dialog)
self.pos_group.setObjectName("pos_group")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.pos_group)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.formLayout = QtWidgets.QFormLayout()
self.formLayout.setObjectName("formLayout")
self.x_label = QtWidgets.QLabel(self.pos_group)
self.x_label.setObjectName("x_label")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.x_label)
self.x_box = QtWidgets.QDoubleSpinBox(self.pos_group)
self.x_box.setDecimals(4)
self.x_box.setMinimum(-999999.0)
self.x_box.setMaximum(999999.0)
self.x_box.setObjectName("x_box")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.x_box)
self.y_label = QtWidgets.QLabel(self.pos_group)
self.y_label.setObjectName("y_label")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.y_label)
self.y_box = QtWidgets.QDoubleSpinBox(self.pos_group)
self.y_box.setDecimals(4)
self.y_box.setMinimum(-999999.0)
self.y_box.setMaximum(999999.0)
self.y_box.setObjectName("y_box")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.y_box)
self.horizontalLayout_4.addLayout(self.formLayout)
self.relocate_option = QtWidgets.QPushButton(self.pos_group)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.<API key>(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.relocate_option.sizePolicy().hasHeightForWidth())
self.relocate_option.setSizePolicy(sizePolicy)
self.relocate_option.setText("")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("icons:calculator.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.relocate_option.setIcon(icon1)
self.relocate_option.setIconSize(QtCore.QSize(30, 30))
self.relocate_option.setObjectName("relocate_option")
self.horizontalLayout_4.addWidget(self.relocate_option)
self.verticalLayout.addWidget(self.pos_group)
self.links_label = QtWidgets.QLabel(Dialog)
self.links_label.setObjectName("links_label")
self.verticalLayout.addWidget(self.links_label)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.no_selected = QtWidgets.QListWidget(Dialog)
self.no_selected.setDragEnabled(True)
self.no_selected.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.no_selected.<API key>(QtCore.Qt.MoveAction)
self.no_selected.setObjectName("no_selected")
self.horizontalLayout.addWidget(self.no_selected)
self.label_4 = QtWidgets.QLabel(Dialog)
self.label_4.setObjectName("label_4")
self.horizontalLayout.addWidget(self.label_4)
self.selected = QtWidgets.QListWidget(Dialog)
self.selected.setDragEnabled(True)
self.selected.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.selected.<API key>(QtCore.Qt.MoveAction)
self.selected.setObjectName("selected")
self.horizontalLayout.addWidget(self.selected)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_5.addLayout(self.verticalLayout)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.button_box = QtWidgets.QDialogButtonBox(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.<API key>(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.button_box.sizePolicy().hasHeightForWidth())
self.button_box.setSizePolicy(sizePolicy)
self.button_box.setOrientation(QtCore.Qt.Vertical)
self.button_box.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.button_box.setObjectName("button_box")
self.verticalLayout_2.addWidget(self.button_box)
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem)
self.horizontalLayout_5.addLayout(self.verticalLayout_2)
self.retranslateUi(Dialog)
self.button_box.accepted.connect(Dialog.accept)
self.button_box.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Point"))
self.name_label.setText(_translate("Dialog", "Point Number"))
self.color_label.setText(_translate("Dialog", "Color"))
self.groupBox.setTitle(_translate("Dialog", "Type"))
self.type_box.setItemText(0, _translate("Dialog", "R (pin)"))
self.type_box.setItemText(1, _translate("Dialog", "P (slider block)"))
self.type_box.setItemText(2, _translate("Dialog", "RP (pin in slot)"))
self.angle_label.setText(_translate("Dialog", "Slider angle"))
self.pos_group.setTitle(_translate("Dialog", "Position"))
self.x_label.setText(_translate("Dialog", "X"))
self.y_label.setText(_translate("Dialog", "Y"))
self.links_label.setText(_translate("Dialog", "Links"))
self.label_4.setText(_translate("Dialog", ">>")) |
<?php
/**#@+ @ignore */
require_once DEDALO_ROOT . '/lib/Zend/Media/Id3/LinkFrame.php';
final class <API key> extends <API key>
{} |
<?php
require_once "sql/contour.sql.php";
function sql_textContour($cols = '0',$where = '1 = 1') {
$contourModuloSql = <API key>();
return <<<EOD
SELECT
way,
height::integer,
$contourModuloSql AS
modulo,
$cols
FROM {$GLOBALS['PGIS_TBL_CONTOUR']}
WHERE
$contourModuloSql IN (100,200,500)
AND ($where)
EOD;
} |
"""
Test for LMS instructor background task queue management
"""
from bulk_email.models import CourseEmail, SEND_TO_ALL
from courseware.tests.factories import UserFactory
from xmodule.modulestore.exceptions import ItemNotFoundError
from instructor_task.api import (
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
)
from instructor_task.api_helper import AlreadyRunningError
from instructor_task.models import InstructorTask, PROGRESS
from instructor_task.tests.test_base import (<API key>,
<API key>,
<API key>,
TestReportMixin,
TEST_COURSE_KEY)
class <API key>(<API key>):
"""
Tests API methods that involve the reporting of status for background tasks.
"""
def <API key>(self):
# when fetching running tasks, we get all running tasks, and only running tasks
for _ in range(1, 5):
self.<API key>()
self.<API key>()
progress_task_ids = [self.<API key>().task_id for _ in range(1, 5)]
task_ids = [instructor_task.task_id for instructor_task in <API key>(TEST_COURSE_KEY)]
self.assertEquals(set(task_ids), set(progress_task_ids))
def <API key>(self):
# when fetching historical tasks, we get all tasks, including running tasks
expected_ids = []
for _ in range(1, 5):
expected_ids.append(self.<API key>().task_id)
expected_ids.append(self.<API key>().task_id)
expected_ids.append(self.<API key>().task_id)
task_ids = [instructor_task.task_id for instructor_task
in <API key>(TEST_COURSE_KEY, usage_key=self.problem_url)]
self.assertEquals(set(task_ids), set(expected_ids))
# make the same call using explicit task_type:
task_ids = [instructor_task.task_id for instructor_task
in <API key>(
TEST_COURSE_KEY,
usage_key=self.problem_url,
task_type='rescore_problem'
)]
self.assertEquals(set(task_ids), set(expected_ids))
# make the same call using a non-existent task_type:
task_ids = [instructor_task.task_id for instructor_task
in <API key>(
TEST_COURSE_KEY,
usage_key=self.problem_url,
task_type='dummy_type'
)]
self.assertEquals(set(task_ids), set())
class <API key>(<API key>):
"""Tests API methods that involve the submission of module-based background tasks."""
def setUp(self):
self.initialize_course()
self.student = UserFactory.create(username="student", email="student@edx.org")
self.instructor = UserFactory.create(username="instructor", email="instructor@edx.org")
def <API key>(self):
# confirm that a rescore of a non-existent module returns an exception
problem_url = <API key>.problem_location("NonexistentProblem")
course_id = self.course.id
request = None
with self.assertRaises(ItemNotFoundError):
<API key>(request, problem_url, self.student)
with self.assertRaises(ItemNotFoundError):
<API key>(request, problem_url)
with self.assertRaises(ItemNotFoundError):
<API key>(request, problem_url)
with self.assertRaises(ItemNotFoundError):
<API key>(request, problem_url)
def <API key>(self):
# confirm that a rescore of an existent but unscorable module returns an exception
# (Note that it is easier to test a scoreable but non-rescorable module in test_tasks,
# where we are creating real modules.)
problem_url = self.problem_section.location
course_id = self.course.id
request = None
with self.assertRaises(NotImplementedError):
<API key>(request, problem_url, self.student)
with self.assertRaises(NotImplementedError):
<API key>(request, problem_url)
def <API key>(self, task_function, student=None):
problem_url_name = 'x' * 255
self.<API key>(problem_url_name)
location = <API key>.problem_location(problem_url_name)
with self.assertRaises(ValueError):
if student is not None:
task_function(self.create_task_request(self.instructor), location, student)
else:
task_function(self.create_task_request(self.instructor), location)
def <API key>(self):
self.<API key>(<API key>)
def <API key>(self):
self.<API key>(<API key>, self.student)
def <API key>(self):
self.<API key>(<API key>)
def <API key>(self):
self.<API key>(<API key>)
def _test_submit_task(self, task_function, student=None):
# tests submit, and then tests a second identical submission.
problem_url_name = 'H1P1'
self.<API key>(problem_url_name)
location = <API key>.problem_location(problem_url_name)
if student is not None:
instructor_task = task_function(self.create_task_request(self.instructor), location, student)
else:
instructor_task = task_function(self.create_task_request(self.instructor), location)
# test resubmitting, by updating the existing record:
instructor_task = InstructorTask.objects.get(id=instructor_task.id)
instructor_task.task_state = PROGRESS
instructor_task.save()
with self.assertRaises(AlreadyRunningError):
if student is not None:
task_function(self.create_task_request(self.instructor), location, student)
else:
task_function(self.create_task_request(self.instructor), location)
def <API key>(self):
self._test_submit_task(<API key>)
def <API key>(self):
self._test_submit_task(<API key>, self.student)
def <API key>(self):
self._test_submit_task(<API key>)
def <API key>(self):
self._test_submit_task(<API key>)
class <API key>(TestReportMixin, <API key>):
"""Tests API methods that involve the submission of course-based background tasks."""
def setUp(self):
self.initialize_course()
self.student = UserFactory.create(username="student", email="student@edx.org")
self.instructor = UserFactory.create(username="instructor", email="instructor@edx.org")
def <API key>(self):
"""Create CourseEmail object for testing."""
course_email = CourseEmail.create(self.course.id, self.instructor, SEND_TO_ALL, "Test Subject", "<p>This is a test message</p>")
return course_email.id # pylint: disable=no-member
def _test_resubmission(self, api_call):
"""
Tests the resubmission of an instructor task through the API.
The call to the API is a lambda expression passed via
`api_call`. Expects that the API call returns the resulting
InstructorTask object, and that its resubmission raises
`AlreadyRunningError`.
"""
instructor_task = api_call()
instructor_task = InstructorTask.objects.get(id=instructor_task.id) # pylint: disable=no-member
instructor_task.task_state = PROGRESS
instructor_task.save()
with self.assertRaises(AlreadyRunningError):
api_call()
def <API key>(self):
email_id = self.<API key>()
api_call = lambda: <API key>(
self.create_task_request(self.instructor),
self.course.id,
email_id
)
self._test_resubmission(api_call)
def <API key>(self):
api_call = lambda: <API key>(
self.create_task_request(self.instructor),
self.course.id,
features=[]
)
self._test_resubmission(api_call)
def <API key>(self):
api_call = lambda: <API key>(
self.create_task_request(self.instructor),
self.course.id,
file_name=u'filename.csv'
)
self._test_resubmission(api_call) |
<?php
return [
'listing' => [
'search' => [
'prompt' => 'type in keywords...',
'options' => 'More Search Options',
],
'mode' => 'Mode',
'status' => 'Rank Status',
'mapped-by' => 'mapped by :mapper',
'source' => 'from :source',
'load-more' => 'Load more...',
],
'mode' => [
'any' => 'Any',
'osu' => 'osu!',
'taiko' => 'osu!taiko',
'fruits' => 'osu!catch',
'mania' => 'osu!mania',
],
'status' => [
'any' => 'Any',
'ranked-approved' => 'Ranked & Approved',
'approved' => 'Approved',
'faves' => 'Favourites',
'modreqs' => 'Mod Requests',
'pending' => 'Pending',
'graveyard' => 'Graveyard',
'my-maps' => 'My Maps',
],
'genre' => [
'any' => 'Any',
'unspecified' => 'Unspecified',
'video-game' => 'Video Game',
'anime' => 'Anime',
'rock' => 'Rock',
'pop' => 'Pop',
'other' => 'Other',
'novelty' => 'Novelty',
'hip-hop' => 'Hip Hop',
'electronic' => 'Electronic',
],
'language' => [
'any' => 'Any',
'english' => 'English',
'chinese' => 'Chinese',
'french' => 'French',
'german' => 'German',
'italian' => 'Italian',
'japanese' => 'Japanese',
'korean' => 'Korean',
'spanish' => 'Spanish',
'swedish' => 'Swedish',
'instrumental' => 'Instrumental',
'other' => 'Other',
],
'extra' => [
'video' => 'Has Video',
'storyboard' => 'Has Storyboard',
],
'rank' => [
'any' => 'Any',
'XH' => 'Silver SS',
'X' => 'SS',
'SH' => 'Silver S',
'S' => 'S',
'A' => 'A',
'B' => 'B',
'C' => 'C',
'D' => 'D',
],
]; |
package com.silverpeas.gallery.process;
import com.silverpeas.form.record.<API key>;
import com.silverpeas.gallery.<API key>;
import com.silverpeas.gallery.control.ejb.GalleryBm;
import com.silverpeas.gallery.control.ejb.MediaServiceFactory;
import com.silverpeas.gallery.dao.MediaDAO;
import com.silverpeas.gallery.model.InternalMedia;
import com.silverpeas.gallery.model.Media;
import com.silverpeas.gallery.model.MediaPK;
import com.silverpeas.publicationTemplate.<API key>;
import com.silverpeas.publicationTemplate.<API key>;
import com.silverpeas.util.StringUtil;
import org.silverpeas.core.admin.<API key>;
import org.silverpeas.core.admin.<API key>;
import org.silverpeas.persistence.repository.OperationContext;
import org.silverpeas.process.management.AbstractDataProcess;
import org.silverpeas.process.session.ProcessSession;
/**
* @author Yohann Chastagnier
*/
public abstract class <API key> extends
AbstractDataProcess<<API key>> {
private final Media media;
private <API key> <API key>;
private <API key> <API key>;
/**
* Default constructor
* @param media
*/
protected <API key>(final Media media) {
this.media = media;
}
/*
* (non-Javadoc)
* @see org.silverpeas.process.SilverpeasProcess#process(org.silverpeas.process.management.
* <API key>, org.silverpeas.process.session.ProcessSession)
*/
@Override
public final void process(final <API key> context,
final ProcessSession session) throws Exception {
processData(context, session);
}
/**
* @param context
* @param session
* @throws Exception
*/
abstract protected void processData(final <API key> context,
final ProcessSession session) throws Exception;
/**
* Access to the GalleryBm
* @return
*/
protected GalleryBm getGalleryBm() {
return MediaServiceFactory.getMediaService();
}
/**
* @return the media
*/
protected Media getMedia() {
return media;
}
/**
* Access to gallery content manager
* @return
*/
protected <API key> <API key>() {
if (<API key> == null) {
<API key> = new <API key>();
}
return <API key>;
}
/**
* Gets an instance of a GenericRecordSet objects manager.
* @return a <API key> instance.
*/
protected <API key> <API key>() {
return <API key>.getInstance();
}
/**
* Gets an instance of <API key>.
* @return an instance of <API key>.
*/
protected <API key> <API key>() {
return <API key>.getInstance();
}
/**
* Gets an XML form name if it exists for the media
* @param context
* @return
*/
protected String getXMLFormName(final <API key> context) {
String formName =
<API key>().<API key>(context.<API key>(),
"XMLFormName");
if (StringUtil.isDefined(formName)) {
try {
final String xmlFormShortName =
formName.substring(formName.indexOf("/") + 1, formName.indexOf("."));
<API key>().<API key>(
context.<API key>() + ":" + xmlFormShortName, formName);
} catch (final <API key> e) {
formName = null;
}
}
return formName;
}
/**
* Centralizes the media creation
* @param albumId
* @param context
* @throws Exception
*/
protected void createMedia(final String albumId, final <API key> context)
throws Exception {
// Sets technical data
getMedia().setMediaPK(new MediaPK("unknown", context.<API key>()));
getMedia().setCreator(context.getUser());
// Insert media in database
getMedia().getMediaPK().setId(MediaDAO
.saveMedia(context.getConnection(), OperationContext.fromUser(context.getUser()),
getMedia()));
// Insert path of the media
MediaDAO.saveMediaPath(context.getConnection(), getMedia(), albumId);
}
/**
* Centralizes the media update
* @param <API key>
* @param context
* @throws Exception
*/
protected void updateMedia(final boolean <API key>,
final <API key> context) throws Exception {
if (getMedia() instanceof InternalMedia) {
if (!StringUtil.isDefined(getMedia().getTitle())) {
getMedia().setTitle(((InternalMedia) getMedia()).getFileName());
}
}
MediaDAO.saveMedia(context.getConnection(), OperationContext.fromUser(context.getUser())
.<API key>(!<API key>), getMedia());
}
/**
* Access to the shared <API key>
* @return
*/
protected <API key> <API key>() {
if (<API key> == null) {
<API key> = <API key>.<API key>();
}
return <API key>;
}
} |
<?php
declare(strict_types=1);
namespace OC\Activity;
use OCP\Activity\ActivitySettings;
use OCP\Activity\ISetting;
use OCP\IL10N;
/**
* Adapt the old interface based settings into the new abstract
* class based one
*/
class <API key> extends ActivitySettings {
private $oldSettings;
private $l10n;
public function __construct(ISetting $oldSettings, IL10N $l10n) {
$this->oldSettings = $oldSettings;
$this->l10n = $l10n;
}
public function getIdentifier() {
return $this->oldSettings->getIdentifier();
}
public function getName() {
return $this->oldSettings->getName();
}
public function getGroupIdentifier() {
return 'other';
}
public function getGroupName() {
return $this->l10n->t('Other activities');
}
public function getPriority() {
return $this->oldSettings->getPriority();
}
public function canChangeMail() {
return $this->oldSettings->canChangeMail();
}
public function <API key>() {
return $this->oldSettings-><API key>();
}
} |
BlogListController.$inject = [
'$scope',
'$location',
'$http',
'api',
'gettext',
'upload',
'<API key>',
'$q',
'blogSecurityService',
'notify',
'config',
'urls',
'moment',
'modal',
'blogService',
];
export default function BlogListController(
$scope,
$location,
$http,
api,
gettext,
upload,
<API key>,
$q,
blogSecurityService,
notify,
config,
urls,
moment,
modal,
blogService
) {
$scope.maxResults = 25;
$scope.states = [
{name: 'active', code: 'open', text: gettext('Active blogs')},
{name: 'archived', code: 'closed', text: gettext('Archived blogs')},
];
$scope.activeState = <API key> ? $scope.states[1] : $scope.states[0];
$scope.creationStep = 'Details';
$scope.<API key> = gettext('Click to request access');
$scope.blogMembers = [];
$scope.changeState = function(state) {
$scope.activeState = state;
$location.path('/liveblog/' + state.name);
fetchBlogs();
};
$scope.modalActive = false;
$scope.bulkActions = 0;
$scope.mailto = 'mailto:upgrade@liveblog.pro?subject=' +
encodeURIComponent(location.hostname) +
' ' +
config.subscriptionLevel;
function clearCreateBlogForm() {
$scope.preview = {};
$scope.progress = {width: 0};
$scope.newBlog = {
title: '',
description: '',
};
$scope.newBlogError = '';
$scope.creationStep = 'Details';
$scope.blogMembers = [];
}
clearCreateBlogForm();
$scope.isAdmin = blogSecurityService.isAdmin;
$scope.<API key> = blogSecurityService.canCreateABlog;
$scope.<API key> = blogSecurityService.canAccessBlog;
// blog list embed code.
function fetchBloglistEmbed() {
const criteria = {source: {
query: {filtered: {filter: {term: {key: 'blogslist'}}}},
}};
api.blogslist.query(criteria, false).then((embed) => {
let url;
if (embed._items.length) {
url = embed._items[0].value;
} else if (config.debug) {
url = 'http://localhost:5000/blogslist_embed';
}
if (url) {
$scope.bloglistEmbed = '<iframe id="liveblog-bloglist" width="100%" ' +
'scrolling="no" src="' + url + '" frameborder="0" allowfullscreen></iframe>';
}
});
}
function bulkDelete(blog) {
api.blogs.remove(angular.copy(blog)).then((message) => {
notify.pop();
notify.info(gettext('Blog removed'));
}, () => {
notify.pop();
notify.error(gettext('Something went wrong'));
});
}
$scope.askRemoveBlog = function() {
modal.confirm(gettext('Are you sure you want to delete the blog(s)?'))
.then(() => {
var selectedBlogs = [];
angular.forEach($scope.blogs._items, (blog) => {
if (blog.selected) {
bulkDelete(blog);
}
});
$scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
});
};
$scope.cancelEmbed = function() {
$scope.embedModal = false;
};
$scope.openEmbed = function() {
fetchBloglistEmbed();
$scope.embedModal = true;
};
$scope.blogSelect = function($event, isSelected) {
$event.stopPropagation();
if (isSelected) {
$scope.bulkActions += 1;
} else {
$scope.bulkActions -= 1;
}
};
$scope.bulkActionCancel = () => {
angular.forEach($scope.blogs._items, (blog) => {
blog.selected = false;
});
$scope.bulkActions = 0;
};
$scope.bulkAction = function(activeState) {
let selectedBlogs = [];
angular.forEach($scope.blogs._items, (blog) => {
if (blog.selected) {
selectedBlogs.push(blog);
const deferred = $q.defer();
const changedBlog = {
blog_status: activeState.name == 'active' ? 'closed' : 'open',
};
let newBlog = angular.copy(blog);
angular.extend(newBlog, changedBlog);
delete newBlog._latest_version;
delete newBlog._current_version;
delete newBlog._version;
delete newBlog.<API key>;
delete newBlog._type;
delete newBlog.selected;
delete newBlog.firstcreated;
newBlog.original_creator = blog.original_creator._id;
blogService.update(blog, newBlog).then((blog) => {
notify.pop();
if (blog.blog_status == 'closed') {
notify.info(gettext('Blog(s) moved to archived'));
} else {
notify.info(gettext('Blog(s) is actived now'));
}
deferred.resolve();
$scope.bulkActions = 0;
});
return deferred.promise;
}
});
$scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
};
$scope.cancelCreate = function() {
clearCreateBlogForm();
$scope.newBlogModalActive = false;
};
$scope.cancelUpgrade = function() {
$scope.embedUpgrade = false;
};
$scope.openNewBlog = function() {
blogSecurityService
.showUpgradeModal()
.then((showUpgradeModal) => {
if (showUpgradeModal) {
$scope.embedUpgrade = true;
} else {
$scope.newBlogModalActive = true;
}
});
};
$scope.creationInProcess = false;
$scope.createBlog = function() {
$scope.creationInProcess = true;
const members = _.map($scope.blogMembers, (obj) => ({user: obj._id}));
// Upload image only if we have a valid one chosen
const promise = $scope.preview.url ? $scope.upload($scope.preview) : $q.when();
return promise.then(() => api.blogs
.save({
title: $scope.newBlog.title,
description: $scope.newBlog.description,
picture_url: $scope.newBlog.picture_url,
picture: $scope.newBlog.picture,
picture_renditions: $scope.newBlog.picture_renditions,
members: members,
})
.then((blog) => {
$scope.creationInProcess = false;
$scope.edit(blog);
}, (error) => {
$scope.creationInProcess = false;
// Error handler
$scope.newBlogError = gettext('Something went wrong. Please try again later');
}));
};
$scope.upload = function(config) {
const form = {};
if (config.img) {
form.media = config.img;
} else if (config.url) {
form.URL = config.url;
}
if (form.hasOwnProperty('media') || form.hasOwnProperty('url')) {
// return a promise of upload which will call the success/error callback
return urls.resource('archive').then((uploadUrl) => upload.start({
method: 'POST',
url: uploadUrl,
data: form,
})
.then((response) => {
if (response.data._status === 'ERR') {
return;
}
var pictureUrl = response.data.renditions.viewImage.href;
$scope.newBlog.picture_url = pictureUrl;
$scope.newBlog.picture = response.data._id;
$scope.newBlog.picture_renditions = response.data.renditions;
}, (error) => {
notify.error(
error.statusText !== '' ? error.statusText : gettext('There was a problem with your upload')
);
}, (progress) => {
$scope.progress.width = Math.round(progress.loaded / progress.total * 100.0);
}));
}
};
$scope.remove = function(blog) {
_.remove($scope.blogs._items, blog);
};
$scope.edit = function(blog) {
$location.path('/liveblog/edit/' + blog._id);
};
$scope.openAccessRequest = function(blog) {
$scope.accessRequestedTo = blog;
$scope.showBlogAccessModal = true;
if (config.subscriptionLevel
&& ['solo', 'team'].indexOf(config.subscriptionLevel) !== -1) {
$scope.<API key>(blog);
} else {
$scope.allowAccessRequest = true;
}
};
$scope.closeAccessRequest = function() {
$scope.accessRequestedTo = false;
$scope.showBlogAccessModal = false;
};
$scope.<API key> = function(blog) {
$scope.allowAccessRequest = false;
const theoricalMembers = [];
if (blog.members) {
blog.members.forEach((member) => {
if (theoricalMembers.indexOf(member.user) === -1) {
theoricalMembers.push(member.user);
}
});
}
$http({
url: config.server.url + '/blogs/' + blog._id + '/request_membership',
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
})
.then((response) => {
if (response.data._items.length > 0) {
response.data._items.forEach((item) => {
if (theoricalMembers.indexOf(item._id) === -1) {
theoricalMembers.push(item._id);
}
});
}
if (theoricalMembers.length < config.assignableUsers[config.subscriptionLevel]) {
$scope.allowAccessRequest = true;
}
});
};
$scope.requestAccess = function(blog) {
let showRequestDialog = true;
// Check to see if the current user hasn't been accepted during this session (before refreshing)
if (blog.members) {
_.each(blog.members, (member) => {
if (member.user === $scope.$root.currentUser._id) {
showRequestDialog = false;
}
});
}
if (showRequestDialog) {
notify.info(gettext('Sending request'));
api('request_membership')
.save({blog: blog._id})
.then(
(data) => {
notify.pop();
notify.info(gettext('Request sent'));
},
(data) => {
notify.pop();
let message = gettext('Something went wrong, plase try again later!');
if (data.data._message === 'A request has already been sent') {
message = gettext('A request has already been sent');
}
notify.error(message, 5000);
}
);
$scope.closeAccessRequest();
} else {
notify.pop();
notify.error(gettext('You are already member of this blog\'s team'));
}
};
$scope.switchTab = function(newTab) {
$scope.creationStep = newTab;
};
$scope.handleKeyDown = function(event, action) {
// prevent form submission and editor 'artifact'
if (event.keyCode === 13) {
event.preventDefault();
switch (action) {
case 'goToTeamTab':
// We need at least a valid title from the first tab
if ($scope.newBlog.title) {
$scope.switchTab('Team');
}
break;
}
}
};
$scope.addMember = function(user) {
$scope.blogMembers.push(user);
};
$scope.removeMember = function(user) {
$scope.blogMembers.splice($scope.blogMembers.indexOf(user), 1);
};
$scope.removeImage = function() {
modal.confirm(gettext('Are you sure you want to remove the blog image?')).then(() => {
$scope.preview.url = '';
$scope.progress.width = 0;
});
};
$scope.<API key> = function() {
if (!config.assignableUsers.hasOwnProperty(config.subscriptionLevel)) {
return false;
}
return $scope.blogMembers.length >= config.assignableUsers[config.subscriptionLevel];
};
// Set grid or list view
$scope.setBlogsView = function(blogsView) {
if (typeof blogsView !== 'undefined') {
$scope.blogsView = blogsView;
localStorage.setItem('blogsView', blogsView);
} else if (typeof localStorage.getItem('blogsView') === 'undefined'
|| localStorage.getItem('blogsView') === null) {
$scope.blogsView = 'grid';
} else {
$scope.blogsView = localStorage.getItem('blogsView');
}
};
$scope.setBlogsView();
function getCriteria() {
const params = $location.search();
const criteria = {
max_results: $scope.maxResults,
embedded: {original_creator: 1},
sort: '[("versioncreated", -1)]',
source: {
query: {filtered: {filter: {term: {blog_status: $scope.activeState.code}}}},
},
};
if (params.q) {
criteria.source.query.filtered.query = {
query_string: {
query: '*' + params.q + '*',
fields: ['title', 'description'],
},
};
}
if (params.page) {
criteria.page = parseInt(params.page, 10);
}
return criteria;
}
function fetchBlogs() {
$scope.blogsLoading = true;
api.blogs.query(getCriteria(), false).then((blogs) => {
$scope.blogs = blogs;
$scope.blogsLoading = false;
});
}
// initialize bloglist embed code.
fetchBloglistEmbed();
// initialize blogs list
fetchBlogs();
// fetch when maxResults is updated from the searchbar-directive
$scope.$watch('maxResults', fetchBlogs);
// fetch when criteria are updated from url (searchbar-directive)
$scope.$on('$routeUpdate', fetchBlogs);
// Reload bloglist on membership's approval
$scope.$on('blogs', fetchBlogs);
} |
# <API key>: true
require "spec_helper"
describe "Monitoring committee member manages voting results", type: :system do
include_context "when monitoring committee member manages voting"
let(:elections_component) { create(:elections_component, participatory_space: voting) }
let!(:election) { create(:election, :bb_test, :tally_ended, component: elections_component, number_of_votes: 10) }
let!(:ps_closure) { create_list(:ps_closure, 4, :with_results, election: election, number_of_votes: 5) }
before do
switch_to_host(organization.host)
login_as user, scope: :user
visit <API key>.edit_voting_path(voting)
end
context "when there are more than one finished elections" do
let!(:other_election) { create(:election, :complete, :published, :finished, component: elections_component) }
it "lists all the finished elections for the voting" do
click_link "Validate Results"
expect(page).to have_content(translated(other_election.title))
click_link translated(election.title)
expect(page).to have_content("Results for the election #{translated(election.title)}")
end
end
describe "results verification and publishing", :slow do
include_context "with test bulletin board"
it "shows the results for the election" do
click_link "Validate Results"
expect(page).to have_content("Results for the election #{translated(election.title)}")
within ".question_" do
expect(page).to have_content("Total ballots")
expect(page).to have_content("20")
expect(page).to have_content("10")
expect(page).to have_content("30")
end
election.questions.each do |question|
within ".question_#{question.id}" do
expect(page).to have_content(translated(question.title))
question.answers.each do |answer|
within ".answer_#{answer.id}" do
expect(page).to have_content(translated(answer.title))
expect(page).to have_content(answer.results_total)
end
end
end
end
click_button "Publish results"
expect(page).to have_content("Publishing results...")
expect(page).to have_content("The results were successfully published")
end
end
end |
/*
Put anything you reference with "url()" in ../assets/
This way, you can minify your application, and just remove the "source" folder for production
*/
#app {
}
.app > * {
box-shadow: -4px -4px 4px rgba(0,0,0,0.3);
background: #555;
width: 320px;
}
.left {
color: white;
}
.item {
position: relative;
border-bottom: 1px solid #0E0E0E;
padding: 16px 12px;
background-color: #333333;
}
.item.onyx-selected {
background-color: #226B9A;
}
.panels {
min-height: 320px;
min-width: 320px;
}
.panels > * {
border: 2px solid #333;
font-size: 5em;
text-align: center;
}
.wide > * {
min-width: 50%;
}
.collapsible > * {
min-width: 250px;
}
#app_title {
font: normal normal normal 24px/26px Courgette, Purisa, Helvetica, Arial, sans-serif;
}
#app_todoList_image {
margin-right: 15px;
}
.<API key>, .<API key> {
padding: 15px;
margin: 15px;
}
.edit-input-label {
color: #FFF;
padding-top: 12px;
}
.<API key> h1 {
color: #FFF;
}
.<API key> p {
color: #FFF;
}
.onyx-button {
margin-left: 15px;
}
.enyo-list-port {
background: url(../assets/bg.png);
}
.<API key> {
background-color: #444;
} |
/* eslint-env nodejs, mocha */
/* global describe:false, app:false, request:false, expect:false */
describe('User', () => {
var passportStub = require('passport-stub');
var User = require('../server/models').User;
var ValidationError = require('mongoose').Error.ValidationError;
before((done) => {
app.db.connection.db.dropDatabase(() => {
done();
});
});
after((done) => {
app.db.connection.db.dropDatabase(() => {
passportStub.uninstall();
done();
});
});
describe('when creating user', () => {
it('fail if password is missing', (done) => {
var user = User({
name: 'Testulf',
email: 'testulf@example.com',
});
user.save((err) => {
expect(err).to.be.instanceOf(ValidationError);
expect(err.errors).to.have.property('password');
done();
});
});
});
}); |
package com.tisawesomeness.minecord.command.utility;
import com.tisawesomeness.minecord.ReactMenu;
import com.tisawesomeness.minecord.ReactMenu.MenuStatus;
import com.tisawesomeness.minecord.command.meta.CommandContext;
import com.tisawesomeness.minecord.command.meta.Result;
import com.tisawesomeness.minecord.config.config.Config;
import com.tisawesomeness.minecord.mc.item.Recipe;
import lombok.NonNull;
import net.dv8tion.jda.api.EmbedBuilder;
import java.util.ArrayList;
import java.util.Arrays;
public class IngredientCommand extends <API key> {
public @NonNull String getId() {
return "ingredient";
}
@Override
public Object[] getHelpArgs(String prefix, String tag, Config config) {
return new Object[]{prefix, tag, config.<API key>()};
}
public void run(String[] argsOrig, CommandContext ctx) {
String[] args = Arrays.copyOf(argsOrig, argsOrig.length);
// Check for argument length
if (args.length == 0) {
ctx.showHelp();
return;
}
ctx.triggerCooldown();
// Parse page number
int page = 0;
if (args.length > 1) {
if (args[args.length - 1].matches("^[0-9]+$")) {
page = Integer.valueOf(args[args.length - 1]) - 1;
args = Arrays.copyOf(args, args.length - 1);
}
}
if (page < 0) {
ctx.invalidArgs("The page number must be positive.");
return;
}
// Search through the recipe database
ArrayList<String> recipes = Recipe.searchIngredient(String.join(" ", args), "en_US");
if (recipes == null) {
ctx.invalidArgs("That item does not exist! Did you spell it correctly?");
return;
}
if (recipes.size() == 0) {
ctx.warn("That item is not an ingredient for any recipes!");
return;
}
if (page >= recipes.size()) {
ctx.warn("That page does not exist!");
return;
}
// Create menu
MenuStatus status = ReactMenu.getMenuStatus(ctx);
if (status == MenuStatus.NO_PERMISSION) {
ctx.noBotPermissions(MenuStatus.NO_PERMISSION.getReason());
return;
}
if (status.isValid()) {
new Recipe.RecipeMenu(recipes, page, "en_US").post(ctx.getE().getChannel(), ctx.getE().getAuthor());
ctx.commandResult(Result.SUCCESS);
return;
}
EmbedBuilder eb = Recipe.displayImg(recipes.get(page), "en_US")
.setColor(ctx.getColor())
.setFooter(String.format("Page %s/%s%s", page + 1, recipes.size(), status.getReason()), null);
ctx.replyRaw(eb);
}
} |
class <API key> < ActiveRecord::Migration[5.2]
def change
remove_index :events, name: :<API key>
remove_index :comments, name: :<API key>
remove_index :comments, name: :<API key>
remove_index :comments, name: :<API key>
remove_index :comments, name: :<API key>
remove_index :discussion_readers, name: :revoked_at_null
remove_index :discussion_readers, name: :accepted_at_null
remove_index :discussion_readers, name: :<API key>
remove_index :discussion_readers, name: :<API key>
remove_index :discussion_readers, name: :<API key>
remove_index :discussion_readers, name: :<API key>
remove_index :discussion_readers, name: :<API key>
end
end |
'use strict;'
/* redux */
import {compose, createStore, applyMiddleware, combineReducers} from 'redux'
import { routerReducer } from 'react-router-redux'
import thunk from 'redux-thunk'
import <API key> from '<API key>'
/* storage */
import * as storage from 'redux-storage'
import createEngine from '<API key>'
import debounce from '<API key>'
import filter from '<API key>'
import localforage from 'localforage'
import LRU from 'lru-cache'
/* reducers/actions */
import markers from './redux/markers'
import filters from './redux/filters'
import streamer from './redux/streamer'
import settings from './redux/settings'
import {remote} from 'electron'
const forageConfig = {
name: 'Butter',
version: 1.0,
size: 4980736
}
const loadCache = () => {
const store = localforage.createInstance(Object.assign({storeName: 'butter_cache'},
forageConfig))
return store.keys().then((keys) => (
Promise.all(keys.map(k => store.getItem(k)))
)).then(dehydrate => createCache(store, dehydrate))
}
const createCache = (store, dehydrate = []) => {
const cache = LRU({
max: 1000,
dispose: (k) => store.removeItem(k)
})
cache.load(dehydrate)
cache.tick = setTimeout(() => {
console.error('saving cache')
cache.dump().map(hit => setTimeout(() => store.setItem(hit.k, hit), 0))
}, 15000)
return cache
}
const providersFromTab = (tab) => (
tab.providers.map(uri => {
const name = uri.split('?')[0]
let instance = null
try {
const Provider = remote.require(`butter-provider-${name}`)
instance = new Provider(uri)
} catch (e) {
console.error('couldnt load provider', name)
return null
}
return instance
}).filter(e => e)
)
const reducersFromTabs = (tabs, cache) => {
let providerReducers = {}
let providerActions = {}
const tabsReducers = Object.keys(tabs).reduce((acc, k) => {
const tab = tabs[k]
const providers = providersFromTab(tab)
providers.forEach(provider => {
const reduxer = <API key>(provider, cache)
providerReducers[provider.id] = reduxer.reducer
providerActions[provider.id] = reduxer.actions
})
return Object.assign(acc, {
[k]: Object.assign(tab, {
providers: providers.map(({config, id}) => ({config, id}))
})
})
}, {})
return {
providerReducers: {
collections: combineReducers(providerReducers),
tabs: (state, action) => ({
tabsReducers
})
},
providerActions
}
}
const buildRootReducer = (tabs, cachedSettings, cache) => {
const {providerActions, providerReducers} = reducersFromTabs(tabs, cache)
return combineReducers({
providerReducers,
markers: markers.reducer,
filters: filters.reducer,
streamer: streamer.reducer,
settings: settings.reducerCreator(cachedSettings),
router: routerReducer,
cache: () => cache,
providerActions: () => providerActions,
})
}
const butterCreateStore = ({tabs, ...cachedSettings}) => {
const persistEngine = debounce(
filter(
createEngine('butterstorage',
Object.assign({
storeName: 'redux_storage'
}, forageConfig)
), ['markers', 'settings']),
1500)
const middlewares = [thunk, storage.createMiddleware(persistEngine)]
const composeEnhancers = (typeof window !== 'undefined' && window.<API key>) || compose
const enhancer = composeEnhancers(applyMiddleware(...middlewares))
return loadCache()
.then(cache => {
const rootReducer = buildRootReducer(tabs, cachedSettings, cache)
const persistReducer = storage.reducer(rootReducer)
const store = createStore(persistReducer, enhancer)
storage.createLoader(persistEngine)(store)
.catch(() => console.log('Failed to load previous state'))
.then(() => {
const {providerActions} = store.getState()
Object.values(providerActions)
.map(a => store.dispatch(a.FETCH({page: 0})))
})
return {store}
})
}
export {butterCreateStore as default} |
class AdditionalFee < ActiveRecord::Base
belongs_to :competition_group
<API key> :competition_group
belongs_to :age_range
<API key> :age_range, :unless => "age_range_id.blank?"
<API key> :name
<API key> :amount, :<API key> => 0.0
end |
# -*- encoding: utf-8 -*-
# OpenERP, Open Source Management Solution
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
# This program is Free Software; you can redistribute it and/or
# as published by the Free Software Foundation; either version 2
# 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.
import time
from report import report_sxw
from tools.translate import _
class sunat_8_1_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context=None):
super(sunat_8_1_report, self).__init__(cr, uid, name, context)
self.localcontext.update( {
'time': time,
})
self.context = context
report_sxw.report_sxw('report.l10n_pe.sunat_8_1', 'l10n_pe.ple_8_1',
'addons/l10n_pe_ple08/report/sunat_8_1.rml', parser=sunat_8_1_report, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#include <iostream>
#include <cmath>
using namespace std;
long num;
void checkPrime();
void checkArmstrong();
void checkPerfect();
int main()
{
short choice;
cout << "Enter a number: ";
cin >> num;
while (num < 0) {
cout << "\nERROR: The entered number must be positive! Please input again!" << endl;
cout << "\nEnter a number: ";
cin >> num;
}
cout << "\nWhat do you want to check?\n\n1. Check for Prime Number\n2. Check for Armstrong Number\n3. Check for Perfect Number\nYour Choice (1/2/3): ";
cin >> choice;
switch(choice)
{
case 1: checkPrime(); break;
case 2: checkArmstrong(); break;
case 3: checkPerfect(); break;
default: cout << "ERROR: Invalid choice! Please make your choice again!" << endl;
}
}
void checkPrime()
{
short counter = 0;
for (int i = 1 ; i <= num/2 ; i++)
if (num % i == 0)
counter++;
cout << "\n" << num << ((counter == 1)?" is ":" is NOT ") << "a Prime number!" << endl;
}
void checkArmstrong()
{
int sum = 0;
for (long n = num ; n > 0 ; n /= 10)
sum += pow(n%10, 3);
cout << "\n" << num << ((sum == num)?" is ":" is NOT ") << "an Armstrong number!" << endl;
}
void checkPerfect()
{
short sum = 0;
for(int i = 1 ; i <= num/2 ; i++) // (num/2) -> Because, "Proper Divisors"
if(num % i == 0)
sum += i;
cout << "\n" << num << ((sum == num)?" is ":" is NOT ") << "a Perfect number." << endl;
} |
{% set can_edit = h.check_access('package_update', {'id':pkg.id }) %}
{% set url_action = 'resource_edit' if url_is_edit and can_edit else 'resource_read' %}
{% set url = h.url_for(controller='package', action=url_action, id=pkg.name, resource_id=res.id) %}
<li class="resource-item" data-id="{{ res.id }}">
{% block resource_item_title %}
<a class="heading" href="{{ url }}" title="{{ res.name or res.description }}">
{{ h.<API key>(res) | truncate(50) }}<span class="format-label" property="dc:format" data-format="{{ res.format.lower() or 'data' }}">{{ res.format }}</span>
{{ h.popular('views', res.tracking_summary.total, min=10) }}
</a>
{% endblock %}
<p class="description">
{% set descriptions = h.<API key>(res) %}
{% set description = descriptions | join(' ') %}
{{ h.markdown_extract(description, extract_length=80) }}
</p>
{% block <API key> %}
{% if not url_is_edit %}
<div class="dropdown btn-group">
<a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-share"></i>
{{ _('Explore') }}
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
{% block <API key> %}
<li>
<a href="{{ url }}">
{% if res.can_be_previewed %}
<i class="fa fa-bar-chart-o"></i>
{{ _('Preview') }}
{% else %}
<i class="fa fa-info-circle"></i>
{{ _('More information') }}
{% endif %}
</a>
</li>
{% if res.url and h.is_url(res.url) %}
<li>
<a href="{{ res.url }}" class="<API key>" target="_blank">
{% if res.can_be_previewed %}
<i class="fa <API key>"></i>
{{ _('Download') }}
{% else %}
<i class="fa fa-external-link"></i>
{{ _('Go to resource') }}
{% endif %}
</a>
</li>
{% endif %}
{% if can_edit %}
<li>
<a href="{{ h.url_for(controller='package', action='resource_edit', id=pkg.name, resource_id=res.id) }}">
<i class="fa fa-pencil-square-o"></i>
{{ _('Edit') }}
</a>
</li>
{% endif %}
{% endblock %}
</ul>
</div>
{% endif %}
{% endblock %}
</li> |
import { extend } from 'leaflet/src/core/Util'
import { Simple } from 'leaflet/src/geo/crs/CRS.Simple'
import { toTransformation } from 'leaflet/src/geometry/Transformation'
export const ZCRS = extend({}, Simple, {
transformation: toTransformation(1, 0, 1, 0)
}) |
<?php
namespace OCA\Passman\Controller;
use \OCA\Passman\BusinessLayer\TagBusinessLayer;
use \OCP\AppFramework\Http\TemplateResponse;
use \OCP\AppFramework\Controller;
use \OCP\AppFramework\Http;
use \OCP\AppFramework\Http\JSONResponse;
class TagController extends Controller {
private $userId;
private $tagBusinessLayer;
public function __construct($appName, $request, $tagBusinessLayer, $userId) {
parent::__construct($appName, $request);
$this->userId = $userId;
$this->tagBusinessLayer = $tagBusinessLayer;
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*/
public function search() {
$tag = $this->params('k');
$response = $this->tagBusinessLayer->search($tag, $this->userId);
$d = new \stdClass();
$d->text = 'is:Deleted';
$response[] = $d;
return new JSONResponse($response);
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*/
public function loadall() {
$response = $this->tagBusinessLayer->loadAll($this->userId);
return new JSONResponse($response);
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*/
public function load($tag) {
if ($this->tagBusinessLayer->search($tag, $this->userId, true)) {
$response = $this->tagBusinessLayer->load($tag, $this->userId);
}
return new JSONResponse($response);
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*/
public function update($min_pw_strength,$renewal_period,$tag_id,$tag_label) {
$tag = array();
$tag['min_pw_strength'] = $min_pw_strength;
$tag['renewal_period'] = $renewal_period;
$tag['tag_id'] = $tag_id;
$tag['tag_label'] = $tag_label;
$response['tag'] = $this->tagBusinessLayer->update($tag, $this->userId);
return new JSONResponse($response);
}
} |
package com.processpuzzle.fundamental_types.quantity.domain;
public class Units {
public static final String MILLIMETRE = "mm";
public static final String CENTIMETRE = "cm";
public static final String DECIMETRE = "dm";
public static final String METRE = "m";
public static final String KILOMETRE = "km";
public static final String GRAMM = "g";
public static final String DEKAGRAMM = "dkg";
public static final String KILOGRAMM = "kg";
public static final String QUINTAL = "q";
public static final String TON = "t";
public static final String MILLISECONDS = "msec";
public static final String SECOND = "s";
public static final String MINUTE = "min";
public static final String HOUR = "h";
public static final String DAY = "d";
public static final String WEEK = "wk";
public static final String MONTH = "mth";
public static final String YEAR = "yr";
public static final String PIECE = "pc";
public static final String PERSON = "person";
} |
package org.mg.wekalib.eval2;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Random;
import org.junit.Assert;
import org.junit.Test;
import org.mg.wekalib.eval2.data.<API key>;
import org.mg.wekalib.eval2.model.RandomForestModel;
import org.mg.wekalib.evaluation.PredictionUtil;
import org.mg.wekalib.evaluation.Predictions;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.RandomForest;
import weka.core.Instances;
public class CVTest
{
@Test
public void <API key>()
{
try
{
HashMap<PredictionUtil.<API key>, Double> valP = new HashMap<>();
HashMap<PredictionUtil.<API key>, Double> valE = new HashMap<>();
int run = 0;
double maxDiff = 0;
// run repeated CVs on the same data until the max difference
// between CV() and Weka-CV
// in mean statistics for each value is below 0.005
do
{
CV cv = new CV();
cv.setRandomSeed(run);
cv.setStratified(true);
Instances inst = new Instances(new FileReader(
System.getProperty("user.home") + "/data/weka/nominal/sonar.arff"));
inst.setClassIndex(inst.numAttributes() - 1);
cv.setDataSet(new <API key>(inst, 1));
cv.setModel(new RandomForestModel());
cv.runSequentially();
Predictions p = cv.getResult();
for (PredictionUtil.<API key> m : PredictionUtil.<API key>
.values())
{
double v = valP.containsKey(m) ? valP.get(m) : 0;
double v2 = PredictionUtil.<API key>(p, m, 1.0);
valP.put(m, (v * run + v2) / (run + 1));
}
Evaluation eval = new Evaluation(inst);
RandomForest rf = new RandomForest();
eval.crossValidateModel(rf, inst, 10, new Random(run), new Object[0]);
Assert.assertEquals(p.actual.length, (int) eval.numInstances());
for (PredictionUtil.<API key> m : PredictionUtil.<API key>
.values())
{
double v = valE.containsKey(m) ? valE.get(m) : 0;
double v2 = PredictionUtil.<API key>(eval, m, 1.0);
valE.put(m, (v * run + v2) / (run + 1));
}
maxDiff = 0;
for (PredictionUtil.<API key> m : PredictionUtil.<API key>
.values())
maxDiff = Math.max(Math.abs(valP.get(m) - valE.get(m)), maxDiff);
run++;
System.out.println(run + " " + maxDiff);
}
while (maxDiff > 0.005);
System.out.println("CVs stats about equal");
}
catch (Exception e)
{
e.printStackTrace();
}
}
} |
#pragma once
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include "pptx_text_context.h"
#include "pptx_slide_context.h"
#include "pptx_output_xml.h"
#include "<API key>.h"
#include "oox_chart_context.h"
#include "pptx_table_context.h"
#include "mediaitems.h"
namespace NSFonts
{
class IApplicationFonts;
}
namespace cpdoccore {
namespace odf_reader
{
class odf_document;
class office_element;
}
namespace oox {
namespace package
{
class pptx_document;
}
class <API key> : boost::noncopyable
{
public:
<API key>(odf_reader::odf_document * odfDocument);
~<API key>();
void set_output_document(package::pptx_document * document);
void set_font_directory (std::wstring pathFonts);
void start_document();
void end_document();
void start_chart(std::wstring name);
void end_chart();
void start_body();
void end_body();
void <API key>();
void <API key>();
bool start_page(const std::wstring & pageName,
const std::wstring & pageStyleName,
const std::wstring & pageLayoutName,
const std::wstring & pageMasterName);
void end_page();
bool start_page_notes();
void end_page_notes();
bool start_master_notes();
void end_master_notes();
bool start_layout( int layout_index);
void end_layout();
bool start_master(int master_index);
void end_master();
void start_theme(std::wstring & name);
void end_theme();
void add_jsaProject(const std::string &content);
std::pair<int,int> add_author_comments(std::wstring author);
pptx_slide_context & get_slide_context() { return pptx_slide_context_; }
<API key> & <API key>() { return <API key>; }
odf_reader::odf_document * root()
{
return odf_document_;
}
pptx_xml_slide & current_slide();
<API key> & current_layout();
<API key> & current_master();
pptx_xml_theme & current_theme();
pptx_xml_slideNotes & current_notes();
<API key> & current_notesMaster();
<API key> & <API key>();
oox_chart_context & current_chart();
math_context & get_math_context() { return math_context_; }
pptx_text_context & get_text_context() { return pptx_text_context_; }
pptx_table_context & get_table_context() { return pptx_table_context_; }
mediaitems_ptr & get_mediaitems() { return pptx_slide_context_.get_mediaitems(); }
//void start_hyperlink(const std::wstring & styleName);
//void end_hyperlink(std::wstring const & href);
bool process_masters_;
void process_layouts();
void process_styles();
void <API key>();
void process_theme(std::wstring name);
int <API key>;
private:
int last_uniq_big_id;
void create_new_slide(std::wstring const & name);
void <API key>(int id);
void <API key>(int id);
void <API key>();
void <API key>();
package::pptx_document * output_document_;
odf_reader::odf_document * odf_document_;
pptx_slide_context pptx_slide_context_;
pptx_text_context pptx_text_context_;
pptx_table_context pptx_table_context_;
<API key> <API key>;
math_context math_context_;
std::vector<<API key>> charts_;
std::vector<pptx_xml_slide_ptr> slides_;
std::vector<<API key>> notes_;
std::vector<<API key>> slideMasters_;
std::vector<<API key>> slideLayouts_;
std::vector<pptx_xml_theme_ptr> themes_;
<API key> slideNotesMaster_;
pptx_xml_<API key> authors_comments_;
<API key> presentation_;
std::wstring <API key>;
std::wstring <API key>;
<API key> <API key>;
};
}
} |
module Codewars.Kata.Unique where
import Data.List
findUniqueNumber :: [Int] -> Int
findUniqueNumber [a] = a
findUniqueNumber (a : (b : c))
| a /= b = a
| otherwise = findUniqueNumber c
-- | All numbers in the unsorted list are present twice,
-- except the one you have to find.
findUnique :: [Int] -> Int
findUnique = findUniqueNumber . sort |
import { ExamStatus } from 'Scripts/Models/ExamStatus';
export class Exam {
public Id: string;
public Title: string;
public Subtitle: string;
public Rating: string;
public Questions: number;
public QuestionsAnswered: number[];
public QuestionsBookmarked: number[];
public <API key>: number;
public BeginsInSeconds?: number;
public RemainingSeconds?: number;
public CanOpen: boolean;
public CanReset: boolean;
public CanShowAnswer: boolean;
public Status: ExamStatus;
public Score?: number;
public IsNewlyCompleted: boolean;
public Passed: boolean;
} |
using Implem.Libraries.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Implem.Pleasanter.Libraries.Requests
{
public class Forms : Dictionary<string, string>
{
public bool Exists(string key)
{
return this.Get(key) != null;
}
public string Data(string key)
{
return this.Get(key) ?? string.Empty;
}
public string ControlId()
{
return Data("ControlId");
}
public bool Bool(string key)
{
return Data(key).ToBool();
}
public int Int(string key)
{
return Data(key).ToInt();
}
public long Long(string key)
{
return Data(key).ToLong();
}
public decimal Decimal(Context context, string key)
{
return Data(key).ToDecimal(context.CultureInfo());
}
public decimal? Decimal(Context context, string key, bool nullable)
{
return nullable && Data(key).IsNullOrEmpty()
? null
: (decimal?)Data(key).ToDecimal(context.CultureInfo());
}
public DateTime DateTime(string key)
{
return Data(key).ToDateTime();
}
public List<int> IntList(string name)
{
return Data(name)
.Deserialize<List<int>>()?
.ToList() ?? new List<int>();
}
public List<long> LongList(string name)
{
return Data(name)
.Deserialize<List<long>>()?
.ToList() ?? new List<long>();
}
public List<string> List(string name)
{
return Data(name)
.Deserialize<List<string>>()?
.Where(o => o != string.Empty)
.ToList() ?? new List<string>();
}
}
} |
'use strict';
describe('Controller: AboutCtrl', function () {
// load the controller's module
beforeEach(module('zapatonApp'));
var AboutCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AboutCtrl = $controller('AboutCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
}); |
#include "udplistener.h"
#include "../networkconfwidget.h"
#include <QUdpSocket>
#include <QThread>
#include <QDebug>
const quint16 UdpListener::DEFAULT_PORT = 40000;
const QHostAddress UdpListener::DEFAULT_ADDRESS = QHostAddress::LocalHost;
const QString UdpListener::ID = QString("External program (UDP)");
UdpListener::UdpListener(QObject *parent) : BlocksSource(parent)
{
type = EXTERNAL_SERVER;
initialize();
}
UdpListener::UdpListener(QHostAddress listeningAddress, quint16 port, QObject *parent) :
BlocksSource(parent)
{
initialize(listeningAddress, port);
}
UdpListener::~UdpListener()
{
serverThread->quit();
serverThread->wait();
stopListening();
QHashIterator<int, UDPClient *> i(clients);
while (i.hasNext()) {
i.next();
BlocksSource::releaseID(i.key());
delete i.value();
}
clients.clear();
}
void UdpListener::initialize(QHostAddress nlisteningAddress, quint16 nport)
{
currentSocket = NULL;
readWrite = true;
listeningAddress = nlisteningAddress;
port = nport;
serverThread = new(std::nothrow) QThread();
if (serverThread == NULL) {
qFatal("Cannot allocate memory for serverThread X{");
}
moveToThread(serverThread);
serverThread->start();
}
void UdpListener::sendBlock(Block *block)
{
QByteArray data;
if (currentSocket != NULL) {
int sourceid = block->getSourceid();
if (!clients.contains(sourceid))
qCritical() << tr("[UdpListener::sendBlock] Invalid sourceid: %1").arg(sourceid);
else {
UDPClient * client = clients.value(sourceid);
if (encodeOutput)
data = block->getData().toBase64();
else
data = block->getData();
currentSocket->writeDatagram(data ,client->getAdress(),client->getPort());
}
} else {
qCritical() << "[UdpListener::sendBlock] No UDP socket present, dropping the block.";
}
delete block;
}
bool UdpListener::startListening()
{
if (currentSocket != NULL) {
stopListening();
}
// recreate server in all cases
currentSocket = new(std::nothrow) QUdpSocket(this);
if (currentSocket == NULL) {
qFatal("Cannot allocate memory for QUdpSocket X{");
}
if (currentSocket->bind(listeningAddress, port)) {
connect(currentSocket, SIGNAL(readyRead()), SLOT(<API key>()));
emit log(tr("UDP server started %1:%2").arg(listeningAddress.toString()).arg(port), "", Pip3lineConst::LSTATUS);
emit started();
} else {
emit log(currentSocket->errorString(),metaObject()->className(),Pip3lineConst::LERROR);
delete currentSocket;
currentSocket = NULL;
return false;
}
return true;
}
void UdpListener::stopListening()
{
if (currentSocket != NULL) {
currentSocket->close();
delete currentSocket;
currentSocket = NULL;
emit log(tr("UDP server stopped %1:%2").arg(listeningAddress.toString()).arg(port), "", Pip3lineConst::LSTATUS);
}
emit stopped();
}
QString UdpListener::getName()
{
return ID;
}
bool UdpListener::isReflexive()
{
return true;
}
void UdpListener::<API key>()
{
while (currentSocket->hasPendingDatagrams()) {
QByteArray datagram;
QHostAddress currentClient;
quint16 currentClientPort;
datagram.resize(currentSocket->pendingDatagramSize());
currentSocket->readDatagram(datagram.data(), datagram.size(),
¤tClient, ¤tClientPort);
if (decodeInput)
datagram = QByteArray::fromBase64(datagram);
qDebug() << "UDP datagram received" << currentClient.toString() << ":" << currentClientPort << datagram.toHex();
int id = BlocksSource::newSourceID(this);
Block * datab = new(std::nothrow) Block(datagram, id);
if (datab == NULL) qFatal("Cannot allocate memory for Block X{");
UDPClient *client = new(std::nothrow) UDPClient(currentClient, currentClientPort);
if (client == NULL) qFatal("Cannot allocate memory for UDPClient X{");
clients.insert(id,client);
emit blockReceived(datab);
}
}
QWidget *UdpListener::requestGui(QWidget * parent)
{
NetworkConfWidget *ncw = new(std::nothrow)NetworkConfWidget(NetworkConfWidget::UDP_SERVER,parent);
if (ncw == NULL) {
qFatal("Cannot allocate memory for NetworkConfWidget X{");
}
ncw->setPort(port);
ncw->setIP(listeningAddress);
ncw-><API key>(true);
connect(ncw, SIGNAL(newIp(QHostAddress)), this, SLOT(setListeningAddress(QHostAddress)));
connect(ncw, SIGNAL(newPort(quint16)), this, SLOT(setPort(quint16)));
connect(ncw, SIGNAL(start()), this, SLOT(startListening()));
connect(ncw, SIGNAL(stop()), this, SLOT(stopListening()));
connect(ncw,SIGNAL(restart()), this, SLOT(restart()));
connect(this, SIGNAL(started()), ncw, SLOT(onServerStarted()));
connect(this, SIGNAL(stopped()), ncw, SLOT(onServerStopped()));
return ncw;
}
void UdpListener::setPort(const quint16 &value)
{
if (value != port) {
port = value;
}
}
void UdpListener::setListeningAddress(const QHostAddress &value)
{
if (value != listeningAddress) {
listeningAddress = value;
}
}
UDPClient::UDPClient(const UDPClient &other)
{
adress = other.adress;
port = other.port;
}
UDPClient::UDPClient(QHostAddress clientAddress, quint16 clientPort)
{
adress = clientAddress;
port = clientPort;
}
QHostAddress UDPClient::getAdress() const
{
return adress;
}
void UDPClient::setAdress(const QHostAddress &value)
{
adress = value;
}
quint16 UDPClient::getPort() const
{
return port;
}
void UDPClient::setPort(const quint16 &value)
{
port = value;
}
bool UDPClient::operator==(const UDPClient &other) const
{
return other.adress == adress && other.port == port;
}
UDPClient& UDPClient::operator=(const UDPClient &other)
{
adress = other.adress;
port = other.port;
return *this;
} |
-- phpMyAdmin SQL Dump
-- version 3.4.9
-- http:
-- Host: mysql50-102.wc2:3306
-- Generation Time: Jun 10, 2012 at 03:10 AM
SET SQL_MODE="<API key>";
SET time_zone = "+00:00";
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET NAMES utf8 */;
-- Table structure for table `blogs`
CREATE TABLE IF NOT EXISTS `blogs` (
`bid` int(11) NOT NULL auto_increment,
`blogName` varchar(64) NOT NULL,
`blogURL` varchar(64) NOT NULL,
`blogRSS` varchar(128) NOT NULL,
`access_ts` int(11) NOT NULL default '0',
`active` tinyint(4) NOT NULL default '1',
PRIMARY KEY (`bid`),
UNIQUE KEY `blogURL` (`blogURL`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10000;
-- Table structure for table `clicks`
CREATE TABLE IF NOT EXISTS `clicks` (
`pid` int(11) NOT NULL,
`ip` varchar(16) NOT NULL,
`timestamp` int(11) NOT NULL,
`hourstamp` int(11) NOT NULL,
PRIMARY KEY (`pid`,`ip`,`hourstamp`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Table structure for table `posts`
CREATE TABLE IF NOT EXISTS `posts` (
`postID` int(11) NOT NULL auto_increment,
`blogID` int(11) NOT NULL,
`link` varchar(320) NOT NULL,
`title` varchar(192) NOT NULL,
`postContent` varchar(512) default NULL,
`thumbnail` varchar(128) default NULL,
`tags` varchar(32) default NULL,
`language` set('en','si','ta','dv') NOT NULL default 'en',
`serverTimestamp` int(11) NOT NULL default '0',
`tweetCount` int(11) NOT NULL default '0',
`fbCount` int(11) NOT NULL default '0',
`api_ts` int(11) NOT NULL default '0',
`postBuzz` float NOT NULL default '0',
`trend` float NOT NULL default '0',
PRIMARY KEY (`postID`),
UNIQUE KEY `link` (`link`),
KEY `blogID` (`blogID`),
KEY `serverTimestamp` (`serverTimestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=100000;
-- Table structure for table `terms`
CREATE TABLE IF NOT EXISTS `terms` (
`tid` int(11) NOT NULL auto_increment,
`term` varchar(31) NOT NULL,
`stopword` tinyint(4) NOT NULL default '0',
`term_freq` int(11) default NULL,
`doc_freq` int (11) default NULL,
`tf_idf` float default NULL,
PRIMARY KEY (`tid`),
UNIQUE KEY `term` (`term`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=100000;
-- Insert stopwords into `terms`
INSERT INTO `terms` (`term` ,`stopword`)
VALUES ("...", 1),
("a", 1),
("able", 1),
("about", 1),
("above", 1),
("according", 1),
("accordingly", 1),
("across", 1),
("actually", 1),
("after", 1),
("afterwards", 1),
("again", 1),
("against", 1),
("ain't", 1),
("all", 1),
("allow", 1),
("allows", 1),
("almost", 1),
("alone", 1),
("along", 1),
("already", 1),
("also", 1),
("although", 1),
("always", 1),
("am", 1),
("among", 1),
("amongst", 1),
("an", 1),
("and", 1),
("another", 1),
("any", 1),
("anybody", 1),
("anyhow", 1),
("anyone", 1),
("anything", 1),
("anyway", 1),
("anyways", 1),
("anywhere", 1),
("apart", 1),
("appear", 1),
("appreciate", 1),
("appropriate", 1),
("are", 1),
("aren't", 1),
("around", 1),
("as", 1),
("aside", 1),
("ask", 1),
("asking", 1),
("associated", 1),
("at", 1),
("available", 1),
("away", 1),
("awfully", 1),
("be", 1),
("became", 1),
("because", 1),
("become", 1),
("becomes", 1),
("becoming", 1),
("been", 1),
("before", 1),
("beforehand", 1),
("behind", 1),
("being", 1),
("believe", 1),
("below", 1),
("beside", 1),
("besides", 1),
("best", 1),
("better", 1),
("between", 1),
("beyond", 1),
("both", 1),
("brief", 1),
("but", 1),
("by", 1),
("c'mon", 1),
("c's", 1),
("came", 1),
("can", 1),
("can't", 1),
("cannot", 1),
("cant", 1),
("cause", 1),
("causes", 1),
("certain", 1),
("certainly", 1),
("changes", 1),
("clearly", 1),
("co", 1),
("com", 1),
("come", 1),
("comes", 1),
("concerning", 1),
("consequently", 1),
("consider", 1),
("considering", 1),
("contain", 1),
("containing", 1),
("contains", 1),
("corresponding", 1),
("could", 1),
("couldn't", 1),
("course", 1),
("currently", 1),
("definitely", 1),
("described", 1),
("despite", 1),
("did", 1),
("didn't", 1),
("different", 1),
("do", 1),
("does", 1),
("doesn't", 1),
("doing", 1),
("don't", 1),
("done", 1),
("down", 1),
("downwards", 1),
("during", 1),
("each", 1),
("edu", 1),
("eg", 1),
("eight", 1),
("either", 1),
("else", 1),
("elsewhere", 1),
("enough", 1),
("entirely", 1),
("especially", 1),
("et", 1),
("etc", 1),
("even", 1),
("ever", 1),
("every", 1),
("everybody", 1),
("everyone", 1),
("everything", 1),
("everywhere", 1),
("ex", 1),
("exactly", 1),
("example", 1),
("except", 1),
("far", 1),
("few", 1),
("fifth", 1),
("first", 1),
("five", 1),
("followed", 1),
("following", 1),
("follows", 1),
("for", 1),
("former", 1),
("formerly", 1),
("forth", 1),
("four", 1),
("from", 1),
("further", 1),
("furthermore", 1),
("get", 1),
("gets", 1),
("getting", 1),
("given", 1),
("gives", 1),
("go", 1),
("goes", 1),
("going", 1),
("gone", 1),
("got", 1),
("gotten", 1),
("greetings", 1),
("had", 1),
("hadn't", 1),
("happens", 1),
("hardly", 1),
("has", 1),
("hasn't", 1),
("have", 1),
("haven't", 1),
("having", 1),
("he", 1),
("he's", 1),
("hello", 1),
("help", 1),
("hence", 1),
("her", 1),
("here", 1),
("here's", 1),
("hereafter", 1),
("hereby", 1),
("herein", 1),
("hereupon", 1),
("hers", 1),
("herself", 1),
("hi", 1),
("him", 1),
("himself", 1),
("his", 1),
("hither", 1),
("hopefully", 1),
("how", 1),
("howbeit", 1),
("however", 1),
("i'd", 1),
("i'll", 1),
("i'm", 1),
("i've", 1),
("ie", 1),
("if", 1),
("ignored", 1),
("immediate", 1),
("in", 1),
("inasmuch", 1),
("inc", 1),
("indeed", 1),
("indicate", 1),
("indicated", 1),
("indicates", 1),
("inner", 1),
("insofar", 1),
("instead", 1),
("into", 1),
("inward", 1),
("is", 1),
("isn't", 1),
("it", 1),
("it'd", 1),
("it'll", 1),
("it's", 1),
("its", 1),
("itself", 1),
("just", 1),
("keep", 1),
("keeps", 1),
("kept", 1),
("know", 1),
("known", 1),
("knows", 1),
("last", 1),
("lately", 1),
("later", 1),
("latter", 1),
("latterly", 1),
("least", 1),
("less", 1),
("lest", 1),
("let", 1),
("let's", 1),
("like", 1),
("liked", 1),
("likely", 1),
("little", 1),
("look", 1),
("looking", 1),
("looks", 1),
("ltd", 1),
("mainly", 1),
("many", 1),
("may", 1),
("maybe", 1),
("me", 1),
("mean", 1),
("meanwhile", 1),
("merely", 1),
("might", 1),
("more", 1),
("moreover", 1),
("most", 1),
("mostly", 1),
("much", 1),
("must", 1),
("my", 1),
("myself", 1),
("name", 1),
("namely", 1),
("nd", 1),
("near", 1),
("nearly", 1),
("necessary", 1),
("need", 1),
("needs", 1),
("neither", 1),
("never", 1),
("nevertheless", 1),
("new", 1),
("next", 1),
("nine", 1),
("no", 1),
("nobody", 1),
("non", 1),
("none", 1),
("noone", 1),
("nor", 1),
("normally", 1),
("not", 1),
("nothing", 1),
("novel", 1),
("now", 1),
("nowhere", 1),
("obviously", 1),
("of", 1),
("off", 1),
("often", 1),
("oh", 1),
("ok", 1),
("okay", 1),
("old", 1),
("on", 1),
("once", 1),
("one", 1),
("ones", 1),
("only", 1),
("onto", 1),
("or", 1),
("other", 1),
("others", 1),
("otherwise", 1),
("ought", 1),
("our", 1),
("ours", 1),
("ourselves", 1),
("out", 1),
("outside", 1),
("over", 1),
("overall", 1),
("own", 1),
("particular", 1),
("particularly", 1),
("per", 1),
("perhaps", 1),
("placed", 1),
("please", 1),
("plus", 1),
("possible", 1),
("presumably", 1),
("probably", 1),
("provides", 1),
("que", 1),
("quite", 1),
("qv", 1),
("rather", 1),
("rd", 1),
("re", 1),
("really", 1),
("reasonably", 1),
("regarding", 1),
("regardless", 1),
("regards", 1),
("relatively", 1),
("respectively", 1),
("right", 1),
("said", 1),
("same", 1),
("saw", 1),
("say", 1),
("saying", 1),
("says", 1),
("second", 1),
("secondly", 1),
("see", 1),
("seeing", 1),
("seem", 1),
("seemed", 1),
("seeming", 1),
("seems", 1),
("seen", 1),
("self", 1),
("selves", 1),
("sensible", 1),
("sent", 1),
("serious", 1),
("seriously", 1),
("seven", 1),
("several", 1),
("shall", 1),
("she", 1),
("should", 1),
("shouldn't", 1),
("since", 1),
("six", 1),
("so", 1),
("some", 1),
("somebody", 1),
("somehow", 1),
("someone", 1),
("something", 1),
("sometime", 1),
("sometimes", 1),
("somewhat", 1),
("somewhere", 1),
("soon", 1),
("sorry", 1),
("specified", 1),
("specify", 1),
("specifying", 1),
("still", 1),
("sub", 1),
("such", 1),
("sup", 1),
("sure", 1),
("t's", 1),
("take", 1),
("taken", 1),
("tell", 1),
("tends", 1),
("th", 1),
("than", 1),
("thank", 1),
("thanks", 1),
("thanx", 1),
("that", 1),
("that's", 1),
("thats", 1),
("the", 1),
("their", 1),
("theirs", 1),
("them", 1),
("themselves", 1),
("then", 1),
("thence", 1),
("there", 1),
("there's", 1),
("thereafter", 1),
("thereby", 1),
("therefore", 1),
("therein", 1),
("theres", 1),
("thereupon", 1),
("these", 1),
("they", 1),
("they'd", 1),
("they'll", 1),
("they're", 1),
("they've", 1),
("think", 1),
("third", 1),
("this", 1),
("thorough", 1),
("thoroughly", 1),
("those", 1),
("though", 1),
("three", 1),
("through", 1),
("throughout", 1),
("thru", 1),
("thus", 1),
("to", 1),
("together", 1),
("too", 1),
("took", 1),
("toward", 1),
("towards", 1),
("tried", 1),
("tries", 1),
("truly", 1),
("try", 1),
("trying", 1),
("twice", 1),
("two", 1),
("un", 1),
("under", 1),
("unfortunately", 1),
("unless", 1),
("unlikely", 1),
("until", 1),
("unto", 1),
("up", 1),
("upon", 1),
("us", 1),
("use", 1),
("used", 1),
("useful", 1),
("uses", 1),
("using", 1),
("usually", 1),
("value", 1),
("various", 1),
("very", 1),
("via", 1),
("viz", 1),
("vs", 1),
("want", 1),
("wants", 1),
("was", 1),
("wasn't", 1),
("way", 1),
("we", 1),
("we'd", 1),
("we'll", 1),
("we're", 1),
("we've", 1),
("welcome", 1),
("well", 1),
("went", 1),
("were", 1),
("weren't", 1),
("what", 1),
("what's", 1),
("whatever", 1),
("when", 1),
("whence", 1),
("whenever", 1),
("where", 1),
("where's", 1),
("whereafter", 1),
("whereas", 1),
("whereby", 1),
("wherein", 1),
("whereupon", 1),
("wherever", 1),
("whether", 1),
("which", 1),
("while", 1),
("whither", 1),
("who", 1),
("who's", 1),
("whoever", 1),
("whole", 1),
("whom", 1),
("whose", 1),
("why", 1),
("will", 1),
("willing", 1),
("wish", 1),
("with", 1),
("within", 1),
("without", 1),
("won't", 1),
("wonder", 1),
("would", 1),
("wouldn't", 1),
("yes", 1),
("yet", 1),
("you", 1),
("you'd", 1),
("you'll", 1),
("you're", 1),
("you've", 1),
("your", 1),
("yours", 1),
("yourself", 1),
("yourselves", 1),
("zero", 1);
-- Table structure for table `post_terms`
CREATE TABLE IF NOT EXISTS `post_terms` (
`pid` int(11) NOT NULL,
`tid` int(11) NOT NULL,
`frequency` int(11) NOT NULL default '0',
PRIMARY KEY (`pid`, `tid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Table structure for table `users`
CREATE TABLE IF NOT EXISTS `users` (
`userid` varchar(64) NOT NULL,
`hash` varchar(64) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Insert default user into `users`
INSERT INTO `users` (`userid` ,`hash`)
VALUES ('indi', SHA1( 'indi' ));
-- Table structure for table `logins`
CREATE TABLE IF NOT EXISTS `logins` (
`id` int(11) NOT NULL auto_increment,
`user` varchar(64) default NULL,
`ipaddr` varchar(32) NOT NULL,
`timestamp` int(11) NOT NULL,
`useragent` varchar(196) NOT NULL,
PRIMARY KEY (`id`),
KEY `user` (`user`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Constraints for dumped tables
-- Constraints for table `clicks`
ALTER TABLE `clicks`
ADD CONSTRAINT `clicks_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `posts` (`postID`) ON DELETE CASCADE;
-- Constraints for table `post_terms`
ALTER TABLE `post_terms`
ADD CONSTRAINT `post_terms_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `posts` (`postID`) ON DELETE CASCADE;
ALTER TABLE `post_terms`
ADD CONSTRAINT `post_terms_ibfk_2` FOREIGN KEY (`tid`) REFERENCES `terms` (`tid`) ON DELETE CASCADE;
-- Constraints for table `posts`
ALTER TABLE `posts`
ADD CONSTRAINT `posts_ibfk_2` FOREIGN KEY (`blogID`) REFERENCES `blogs` (`bid`) ON DELETE CASCADE ON UPDATE CASCADE;
-- Constraints for table `logins`
ALTER TABLE `logins`
ADD CONSTRAINT `logins_ibfk_1` FOREIGN KEY (`user`) REFERENCES `users` (`userid`) ON DELETE SET NULL ON UPDATE SET NULL;
/*!40101 SET <API key>=@<API key> */;
/*!40101 SET <API key>=@<API key> */;
/*!40101 SET <API key>=@<API key> */; |
class <API key> < ActiveRecord::Migration
def change
create_table :concept_results do |t|
t.integer "activity_session_id"
t.integer "concept_id", null: false
t.json "metadata"
end
end
end |
package tigase.server;
import tigase.conf.<API key>;
import tigase.disco.XMPPService;
import tigase.stats.StatisticsList;
import tigase.sys.TigaseRuntime;
import tigase.util.<API key>;
import tigase.util.UpdatesChecker;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.JID;
import tigase.xmpp.<API key>;
import tigase.xmpp.StanzaType;
import static tigase.server.MessageRouterConfig.*;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.<API key>;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class MessageRouter
*
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class MessageRouter
extends <API key>
implements MessageRouterIfc {
// implements XMPPService {
// public static final String INFO_XMLNS =
// "http://jabber.org/protocol/disco#info";
// public static final String ITEMS_XMLNS =
// "http://jabber.org/protocol/disco#items";
private static final Logger log = Logger.getLogger(MessageRouter.class.getName());
private <API key> config = null;
// private static final long startupTime = System.currentTimeMillis();
// private Set<String> localAddresses = new CopyOnWriteArraySet<String>();
private String disco_name = DISCO_NAME_PROP_VAL;
private boolean disco_show_version =
<API key>;
private UpdatesChecker updates_checker = null;
private Map<String, XMPPService> xmppServices = new ConcurrentHashMap<>();
private Map<String, <API key>> registrators = new ConcurrentHashMap<>();
private Map<String, MessageReceiver> receivers = new ConcurrentHashMap<>();
private boolean inProperties = false;
private Set<String> <API key> =
new <API key><>();
private Map<JID, ServerComponent> components_byId = new ConcurrentHashMap<>();
private Map<String, ServerComponent> components = new ConcurrentHashMap<>();
/**
* Method description
*
*
* @param component
*/
public void addComponent(ServerComponent component) {
log.log(Level.INFO, "Adding component: ", component.getClass().getSimpleName());
for (<API key> registr : registrators.values()) {
if (registr != component) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Adding: {0} component to {1} registrator.",
new Object[] { component.getName(),
registr.getName() });
}
registr.addComponent(component);
} // end of if (reg != component)
} // end of for ()
components.put(component.getName(), component);
components_byId.put(component.getComponentId(), component);
if (component instanceof XMPPService) {
xmppServices.put(component.getName(), (XMPPService) component);
}
}
/**
* Method description
*
*
* @param registr
*/
public void addRegistrator(<API key> registr) {
log.log(Level.INFO, "Adding registrator: {0}", registr.getClass().getSimpleName());
registrators.put(registr.getName(), registr);
addComponent(registr);
for (ServerComponent comp : components.values()) {
// if (comp != registr) {
registr.addComponent(comp);
// } // end of if (comp != registr)
} // end of for (ServerComponent comp : components)
}
/**
* Method description
*
*
* @param receiver
*/
public void addRouter(MessageReceiver receiver) {
log.info("Adding receiver: " + receiver.getClass().getSimpleName());
addComponent(receiver);
receivers.put(receiver.getName(), receiver);
}
/**
* Method description
*
*
* @param packet
*
*
*
* @return a value of <code>int</code>
*/
@Override
public int hashCodeForPacket(Packet packet) {
// This is actually quite tricky part. We want to both avoid
// packet reordering and also even packets distribution among
// different threads.
// If packet comes from a connection manager we must use packetFrom
// address. However if the packet comes from SM, PubSub or other similar
// component all packets would end-up in the same queue.
// So, kind of a workaround here....
// TODO: develop a proper solution discovering which components are
// connection managers and use their names here instead of static names.
if ((packet.getPacketFrom() != null) && (packet.getPacketFrom().getLocalpart() !=
null)) {
if (<API key>.contains(packet.getPacketFrom().getLocalpart())) {
return packet.getPacketFrom().hashCode();
}
}
if ((packet.getPacketTo() != null) && (packet.getPacketTo().getLocalpart() != null)) {
if (<API key>.contains(packet.getPacketTo().getLocalpart())) {
return packet.getPacketTo().hashCode();
}
}
if (packet.getStanzaTo() != null) {
return packet.getStanzaTo().getBareJID().hashCode();
}
if ((packet.getPacketFrom() != null) &&!getComponentId().equals(packet
.getPacketFrom())) {
// This comes from connection manager so the best way is to get hashcode
// by the connectionId, which is in the getFrom()
return packet.getPacketFrom().hashCode();
}
if ((packet.getPacketTo() != null) &&!getComponentId().equals(packet.getPacketTo())) {
return packet.getPacketTo().hashCode();
}
// If not, then a better way is to get hashCode from the elemTo address
// as this would be by the destination address user name:
return 1;
}
/**
* Method description
*
*
*
*
* @return a value of <code>int</code>
*/
@Override
public int processingInThreads() {
return Runtime.getRuntime().availableProcessors() * 4;
}
/**
* Method description
*
*
*
*
* @return a value of <code>int</code>
*/
@Override
public int <API key>() {
return 1;
}
// private String isToLocalComponent(String jid) {
// String nick = JIDUtils.getNodeNick(jid);
// if (nick == null) {
// return null;
// String host = JIDUtils.getNodeHost(jid);
// if (isLocalDomain(host) && components.get(nick) != null) {
// return nick;
// return null;
// private boolean isLocalDomain(String domain) {
// return localAddresses.contains(domain);
/**
* Method description
*
*
* @param packet
*/
@Override
public void processPacket(Packet packet) {
// We do not process packets with not destination address
// Just dropping them and writing a log message
if (packet.getTo() == null) {
log.log(Level.WARNING, "Packet with TO attribute set to NULL: {0}", packet);
return;
} // end of if (packet.getTo() == null)
// Intentionally comparing to static, final String
// This is kind of a hack to handle packets addressed specifically for the
// SessionManager
// TODO: Replace the hack with a proper solution
// if (packet.getTo() == NULL_ROUTING) {
// log.info("NULL routing, it is normal if server doesn't know how to"
// + " process packet: " + packet.toStringSecure());
// try {
// Packet error =
// Authorization.<API key>.getResponseMessage(packet,
// "Feature not supported yet.", true);
// addOutPacketNB(error);
// } catch (<API key> e) {
// log.warning("Packet processing exception: " + e);
// return;
// if (log.isLoggable(Level.FINER)) {
// log.finer("Processing packet: " + packet.getElemName()
// + ", type: " + packet.getType());
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing packet: {0}", packet);
}
// Detect inifinite loop if from == to
// Maybe it is not needed anymore...
// There is a need to process packets with the same from and to address
// let't try to relax restriction and block all packets with error type
// 2008-06-16
if (((packet.getType() == StanzaType.error) && (packet.getFrom() != null) && packet
.getFrom().equals(packet.getTo()))) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Possible infinite loop, dropping packet: {0}", packet);
}
return;
}
if (isLocalDiscoRequest(packet)) {
Queue<Packet> results = new ArrayDeque<>();
processDiscoQuery(packet, results);
if (results.size() > 0) {
for (Packet res : results) {
// No more recurrential calls!!
addOutPacketNB(res);
} // end of for ()
}
return;
}
// It is not a service discovery packet, we have to find a component to
// process
// the packet. The below block of code is to "quickly" find a component if
// the
// the packet is addressed to the component ID where the component ID is
// either
// of one below:
// 1. component name + "@" + default domain name
// 2. component name + "@" + any virtual host name
// 3. component name + "." + default domain name
// 4. component name + "." + any virtual host name
// TODO: check the efficiency for packets addressed to c2s component
ServerComponent comp = getLocalComponent(packet.getTo());
if (comp != null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "1. Packet will be processed by: {0}, {1}", new Object[] {
comp.getComponentId(),
packet });
}
Queue<Packet> results = new ArrayDeque<Packet>();
if (comp == this) {
// This is addressed to the MessageRouter itself. Has to be processed
// separately to avoid recurential calls by the packet processing
// method.
processPacketMR(packet, results);
} else {
// All other components process the packet the same way.
comp.processPacket(packet, results);
}
if (results.size() > 0) {
for (Packet res : results) {
// No more recurrential calls!!
addOutPacketNB(res);
// processPacket(res);
} // end of for ()
}
// If the component is found the processing ends here as there can be
// only one component with specific ID.
return;
}
// This packet is not processed yet
// The packet can be addressed to just a domain, one of the virtual hosts
// The code below finds all components which handle packets addressed
// to a virtual domains (implement VHostListener and return 'true' from
// handlesLocalDomains() method call)
String host = packet.getTo().getDomain();
ServerComponent[] comps = <API key>(host);
if (comps == null) {
// Still no component found, now the most expensive lookup.
// Checking regex routings provided by the component.
comps = <API key>(packet.getTo().getBareJID().toString());
}
if ((comps == null) &&!isLocalDomain(host)) {
// None of the component want to process the packet.
// If the packet is addressed to non-local domain then it is processed by
// all components dealing with external world, like s2s
comps = <API key>(host);
}
// Ok, if any component has been found then process the packet in a standard
// way
if (comps != null) {
// Processing packet and handling results out
Queue<Packet> results = new ArrayDeque<Packet>();
for (ServerComponent serverComponent : comps) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "2. Packet will be processed by: {0}, {1}",
new Object[] { serverComponent.getComponentId(),
packet });
}
serverComponent.processPacket(packet, results);
if (results.size() > 0) {
for (Packet res : results) {
// No more recurrential calls!!
addOutPacketNB(res);
// processPacket(res);
} // end of for ()
}
}
} else {
// No components for the packet, sending an error back
if (log.isLoggable(Level.FINEST)) {
log.finest("There is no component for the packet, sending it back");
}
try {
addOutPacketNB(Authorization.SERVICE_UNAVAILABLE.getResponseMessage(packet,
"There is no service found to process your request.", true));
} catch (<API key> e) {
// This packet is to local domain, we don't want to send it out
// drop packet :-(
log.warning("Can't process packet to local domain, dropping..." + packet
.toStringSecure());
}
}
}
/**
* Method description
*
*
* @param packet
* @param results
*/
public void processPacketMR(Packet packet, Queue<Packet> results) {
Iq iq = null;
if (packet instanceof Iq) {
iq = (Iq) packet;
} else {
// Not a command for sure...
log.warning("I expect command (Iq) packet here, instead I got: " + packet
.toString());
return;
}
if (packet.getPermissions() != Permissions.ADMIN) {
try {
Packet res = Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You are not authorized for this action.", true);
results.offer(res);
// processPacket(res);
} catch (<API key> e) {
log.warning("Packet processing exception: " + e);
}
return;
}
if (log.isLoggable(Level.FINEST)) {
log.finest("Command received: " + iq.toString());
}
switch (iq.getCommand()) {
case OTHER :
if (iq.getStrCommand() != null) {
if (iq.getStrCommand().startsWith("controll/")) {
String[] spl = iq.getStrCommand().split("/");
String cmd = spl[1];
if (cmd.equals("stop")) {
Packet result = iq.commandResult(Command.DataType.result);
results.offer(result);
// processPacket(result);
new Timer("Stopping...", true).schedule(new TimerTask() {
@Override
public void run() {
System.exit(0);
}
}, 2000);
}
}
}
break;
default :
break;
}
}
/**
* Method description
*
*
* @param component
*/
public void removeComponent(ServerComponent component) {
for (<API key> registr : registrators.values()) {
if (registr != component) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Adding: {0} component to {1} registrator.",
new Object[] { component.getName(),
registr.getName() });
}
registr.deleteComponent(component);
} // end of if (reg != component)
} // end of for ()
components.remove(component.getName());
components_byId.remove(component.getComponentId());
if (component instanceof XMPPService) {
xmppServices.remove(component.getName());
}
}
/**
* Method description
*
*
* @param receiver
*/
public void removeRouter(MessageReceiver receiver) {
log.info("Removing receiver: " + receiver.getClass().getSimpleName());
receivers.remove(receiver.getName());
removeComponent(receiver);
}
/**
* Method description
*
*/
@Override
public void start() {
super.start();
}
/**
* Method description
*
*/
@Override
public void stop() {
Set<String> comp_names = new TreeSet<String>();
comp_names.addAll(components.keySet());
for (String name : comp_names) {
ServerComponent comp = components.remove(name);
if ((comp != this) && (comp != null)) {
comp.release();
}
}
super.stop();
}
/**
* Method description
*
*
* @param params
*
*
*
* @return a value of <code>Map<String,Object></code>
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> defs = super.getDefaults(params);
MessageRouterConfig.getDefaults(defs, params, getName());
return defs;
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
@Override
public String <API key>() {
return "im";
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
@Override
public String getDiscoDescription() {
return disco_name + (disco_show_version
? (" ver. " + XMPPServer.<API key>())
: "");
}
// public List<Element> getDiscoItems(String node, String jid) {
// return null;
/**
* Method description
*
*
* @param list
*/
@Override
public void getStatistics(StatisticsList list) {
super.getStatistics(list);
list.add(getName(), "Local hostname", getDefHostName().getDomain(), Level.INFO);
TigaseRuntime runtime = TigaseRuntime.getTigaseRuntime();
list.add(getName(), "Uptime", runtime.getUptimeString(), Level.INFO);
NumberFormat format = NumberFormat.getNumberInstance();
format.<API key>(4);
list.add(getName(), "Load average", format.format(runtime.getLoadAverage()), Level
.FINE);
list.add(getName(), "CPUs no", runtime.getCPUsNumber(), Level.FINEST);
list.add(getName(), "Threads count", runtime.getThreadsNumber(), Level.FINEST);
float cpuUsage = runtime.getCPUUsage();
float heapUsage = runtime.getHeapMemUsage();
float nonHeapUsage = runtime.getNonHeapMemUsage();
list.add(getName(), "CPU usage [%]", cpuUsage, Level.FINE);
list.add(getName(), "HEAP usage [%]", heapUsage, Level.FINE);
list.add(getName(), "NONHEAP usage [%]", nonHeapUsage, Level.FINE);
format = NumberFormat.getNumberInstance();
format.<API key>(1);
// if (format instanceof DecimalFormat) {
// DecimalFormat decf = (DecimalFormat)format;
// decf.applyPattern(decf.toPattern()+"%");
list.add(getName(), "CPU usage", format.format(cpuUsage) + "%", Level.INFO);
MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
MemoryUsage nonHeap = ManagementFactory.getMemoryMXBean().<API key>();
format = NumberFormat.getIntegerInstance();
if (format instanceof DecimalFormat) {
DecimalFormat decf = (DecimalFormat) format;
decf.applyPattern(decf.toPattern() + " KB");
}
list.add(getName(), "Max Heap mem", format.format(heap.getMax() / 1024), Level.INFO);
list.add(getName(), "Used Heap", format.format(heap.getUsed() / 1024), Level.INFO);
list.add(getName(), "Free Heap", format.format((heap.getMax() - heap.getUsed()) /
1024), Level.FINE);
list.add(getName(), "Max NonHeap mem", format.format(nonHeap.getMax() / 1024), Level
.FINE);
list.add(getName(), "Used NonHeap", format.format(nonHeap.getUsed() / 1024), Level
.FINE);
list.add(getName(), "Free NonHeap", format.format((nonHeap.getMax() - nonHeap
.getUsed()) / 1024), Level.FINE);
}
/**
* Method description
*
*
* @param config
*/
@Override
public void setConfig(<API key> config) {
components.put(getName(), this);
this.config = config;
addRegistrator(config);
}
/**
* Method description
*
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
if (inProperties) {
return;
} else {
inProperties = true;
} // end of if (inProperties) else
<API key>.add("c2s");
<API key>.add("bosh");
<API key>.add("s2s");
if (props.get(<API key>) != null) {
disco_show_version = (Boolean) props.get(<API key>);
}
if (props.get(DISCO_NAME_PROP_KEY) != null) {
disco_name = (String) props.get(DISCO_NAME_PROP_KEY);
}
try {
super.setProperties(props);
<API key>(getName(), null, getDiscoDescription(), "server", "im",
false);
if (props.size() == 1) {
// If props.size() == 1, it means this is a single property update and
// MR does
// not support it yet.
return;
}
HashSet<String> inactive_msgrec = new HashSet<String>(receivers.keySet());
MessageRouterConfig conf = new MessageRouterConfig(props);
String[] reg_names = conf.getRegistrNames();
for (String name : reg_names) {
inactive_msgrec.remove(name);
// First remove it and later, add it again if still active
<API key> cr = registrators.remove(name);
String cls_name = (String) props.get(<API key> + name +
".class");
try {
if ((cr == null) ||!cr.getClass().getName().equals(cls_name)) {
if (cr != null) {
cr.release();
}
cr = conf.getRegistrInstance(name);
cr.setName(name);
} // end of if (cr == null)
addRegistrator(cr);
} catch (Exception e) {
e.printStackTrace();
} // end of try-catch
} // end of for (String name: reg_names)
String[] msgrcv_names = conf.<API key>();
for (String name : msgrcv_names) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Loading and registering message receiver: {0}", name);
}
inactive_msgrec.remove(name);
// First remove it and later, add it again if still active
ServerComponent mr = receivers.remove(name);
xmppServices.remove(name);
String cls_name = (String) props.get(<API key> + name + ".class");
try {
// boolean start = false;
if ((mr == null) || ((mr != null) &&!conf.<API key>(cls_name, mr
.getClass()))) {
if (mr != null) {
if (mr instanceof MessageReceiver) {
removeRouter((MessageReceiver) mr);
} else {
removeComponent(mr);
}
mr.release();
}
mr = conf.getMsgRcvInstance(name);
mr.setName(name);
if (mr instanceof MessageReceiver) {
((MessageReceiver) mr).setParent(this);
((MessageReceiver) mr).start();
// start = true;
}
} // end of if (cr == null)
if (mr instanceof MessageReceiver) {
addRouter((MessageReceiver) mr);
} else {
addComponent(mr);
}
System.out.println("Loading component: " + mr.getComponentInfo());
// if (start) {
// ((MessageReceiver) mr).start();
} // end of try
catch (<API key> e) {
log.log(Level.WARNING, "class for component = {0} could not be found " +
"- disabling component", name);
// conf.setComponentActive(name, false);
} // end of try
catch (Exception e) {
e.printStackTrace();
} // end of try-catch
} // end of for (String name: reg_names)
// String[] inactive_msgrec = conf.<API key>();
for (String name : inactive_msgrec) {
ServerComponent mr = receivers.remove(name);
xmppServices.remove(name);
if (mr != null) {
try {
if (mr instanceof MessageReceiver) {
removeRouter((MessageReceiver) mr);
} else {
removeComponent(mr);
}
mr.release();
} catch (Exception ex) {
log.log(Level.WARNING, "exception releasing component:", ex);
}
}
}
// for (MessageReceiver mr : tmp_rec.values()) {
// mr.release();
// } // end of for ()
// tmp_rec.clear();
if ((Boolean) props.get(<API key>)) {
<API key>((Long) props.get(<API key>));
} else {
log.log(Level.INFO, "Disabling updates checker.");
stopUpdatesChecker();
}
} finally {
inProperties = false;
} // end of try-finally
for (ServerComponent comp : components.values()) {
log.log(Level.INFO, "Initialization completed notification to: {0}", comp
.getName());
comp.<API key>();
}
// log.info("Initialization completed notification to: " +
// config.getName());
// config.<API key>();
}
/**
* Method description
*
*
* @param def
*
*
*
* @return a value of <code>Integer</code>
*/
@Override
protected Integer getMaxQueueSize(int def) {
return def * 10;
}
private void <API key>(long interval) {
stopUpdatesChecker();
updates_checker = new UpdatesChecker(interval, this,
"This is automated message generated by updates checking module.\n" +
" You can disable this function changing configuration option: " + "'/" +
getName() + "/" + <API key> + "' or adjust" +
" updates checking interval time changing option: " + "'/" + getName() + "/" +
<API key> + "' which" + " now set to " + interval +
" days.");
updates_checker.start();
}
private void processDiscoQuery(final Packet packet, final Queue<Packet> results) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing disco query by: {0}", packet.toStringSecure());
}
JID toJid = packet.getStanzaTo();
JID fromJid = packet.getStanzaFrom();
String node = packet.<API key>(Iq.IQ_QUERY_PATH, "node");
Element query = packet.getElement().getChild("query").clone();
if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, INFO_XMLNS)) {
if (isLocalDomain(toJid.toString()) && (node == null)) {
try {
query = getDiscoInfo(node, (toJid.getLocalpart() == null)
? JID.jidInstance(getName(), toJid.toString(), null)
: toJid, fromJid);
} catch (<API key> e) {
log.log(Level.WARNING,
"processing by stringprep throw exception for = {0}@{1}", new Object[] {
getName(),
toJid.toString() });
}
for (XMPPService comp : xmppServices.values()) {
// Buggy custom component may throw exceptions here (NPE most likely)
// which may cause service disco problems for well-behaving components
// too
// So this is kind of a protection
try {
List<Element> features = comp.getDiscoFeatures(fromJid);
if (features != null) {
query.addChildren(features);
}
} catch (Exception e) {
log.log(Level.WARNING, "Component service disco problem: " + comp.getName(),
e);
}
}
} else {
for (XMPPService comp : xmppServices.values()) {
// Buggy custom component may throw exceptions here (NPE most likely)
// which may cause service disco problems for well-behaving components
// too
// So this is kind of a protection
try {
// if (jid.startsWith(comp.getName() + ".")) {
Element resp = comp.getDiscoInfo(node, toJid, fromJid);
if (resp != null) {
query.addChildren(resp.getChildren());
}
} catch (Exception e) {
log.log(Level.WARNING, "Component service disco problem: " + comp.getName(),
e);
}
}
}
}
if (packet.isXMLNSStaticStr(Iq.IQ_QUERY_PATH, ITEMS_XMLNS)) {
boolean localDomain = isLocalDomain(toJid.toString());
if (localDomain) {
for (XMPPService comp : xmppServices.values()) {
// Buggy custom component may throw exceptions here (NPE most likely)
// which may cause service disco problems for well-behaving components
// too
// So this is kind of a protection
try {
// if (localDomain || (nick != null && comp.getName().equals(nick)))
List<Element> items = comp.getDiscoItems(node, toJid, fromJid);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,
"Localdomain: {0}, DiscoItems processed by: {1}, items: {2}",
new Object[] { toJid,
comp.getComponentId(),
(items == null)
? null
: items.toString() });
}
if ((items != null) && (items.size() > 0)) {
query.addChildren(items);
}
} catch (Exception e) {
log.log(Level.WARNING, "Component service disco problem: " + comp.getName(),
e);
}
} // end of for ()
} else {
ServerComponent comp = getLocalComponent(toJid);
if ((comp != null) && (comp instanceof XMPPService)) {
List<Element> items = ((XMPPService) comp).getDiscoItems(node, toJid, fromJid);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "DiscoItems processed by: {0}, items: {1}",
new Object[] { comp.getComponentId(), (items == null)
? null
: items.toString() });
}
if ((items != null) && (items.size() > 0)) {
query.addChildren(items);
}
}
}
}
results.offer(packet.okResult(query, 0));
}
private void stopUpdatesChecker() {
if (updates_checker != null) {
updates_checker.interrupt();
updates_checker = null;
}
}
private ServerComponent[] <API key>(String domain) {
return vHostManager.<API key>(domain);
}
private ServerComponent[] <API key>(String domain) {
return vHostManager.<API key>(domain);
}
private ServerComponent getLocalComponent(JID jid) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Called for : {0}", jid);
}
// Fast lookup in the server components to find a candidate
// by the component ID (JID). If the packet is addressed directly
// to the component ID then this is where the processing must happen.
// Normally the component id is: component name + "@" + default hostname
// However the component may "choose" to have any ID.
ServerComponent comp = components_byId.get(jid);
if (comp != null) {
return comp;
}
if (log.isLoggable(Level.FINEST)) {
log.log( Level.FINEST, "No componentID matches (fast lookup against exact address): "
+ "{0}, for map: {1}; trying VHost lookup",
new Object[] { jid, components_byId.keySet() } );
}
// Note, component ID consists of the component name + default hostname
// which can be different from a virtual host. There might be many
// virtual hosts and the packet can be addressed to the component by
// the component name + virtual host name
// Code below, tries to find a destination by the component name + any
// active virtual hostname.
if (jid.getLocalpart() != null) {
comp = components.get(jid.getLocalpart());
if ((comp != null) && (isLocalDomain(jid.getDomain()) || jid.getDomain().equals(
getDefHostName().getDomain()))) {
return comp;
}
}
if ( log.isLoggable( Level.FINEST ) ){
log.log( Level.FINEST,
"No component name matches (VHost lookup against component name): "
+ "{0}, for map: {1}, for all VHosts: {2}; trying other forms of addressing",
new Object[] { jid, components.keySet(), vHostManager.getAllVHosts() } );
}
// Instead of a component ID built of: component name + "@" domain name
// Some components have an ID of: component name + "." domain name
// Code below tries to find a packet receiver if the address have the other
// type of form.
int idx = jid.getDomain().indexOf('.');
if (idx > 0) {
String cmpName = jid.getDomain().substring(0, idx);
String basename = jid.getDomain().substring(idx + 1);
comp = components.get(cmpName);
if ((comp != null) && (isLocalDomain(basename) || basename.equals(getDefHostName()
.getDomain()))) {
if ( log.isLoggable( Level.FINEST ) ){
log.log( Level.FINEST,
"Component matched: {0}, for comp: {1}, basename: {3}",
new Object[] { jid, components.keySet(), comp, basename } );
}
return comp;
}
if ( log.isLoggable( Level.FINEST ) ){
log.log( Level.FINEST,
"Component match failed: {0}, for comp: {1}, basename: {3}",
new Object[] { jid, components.keySet(), comp, basename } );
}
}
return null;
}
private ServerComponent[] <API key>(String id) {
LinkedHashSet<ServerComponent> comps = new LinkedHashSet<ServerComponent>();
for (MessageReceiver mr : receivers.values()) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Checking routings for: " + mr.getName());
}
if (mr.isInRegexRoutings(id)) {
comps.add(mr);
}
}
if (comps.size() > 0) {
return comps.toArray(new ServerComponent[comps.size()]);
} else {
return null;
}
}
private boolean isDiscoDisabled(ServerComponent comp, JID to) {
if (comp != null) {
return (comp instanceof DisableDisco);
} else {
ServerComponent[] comps = <API key>(to.getDomain());
if (comps != null) {
for (ServerComponent c : comps) {
if (c instanceof DisableDisco) {
return true;
}
}
}
}
return false;
}
private boolean isLocalDiscoRequest(Packet packet) {
boolean result = false;
JID to = packet.getStanzaTo();
ServerComponent comp = (to == null)
? null
: getLocalComponent(to);
result = packet.isServiceDisco() && (packet.getType() == StanzaType.get) && (packet
.getStanzaFrom() != null) && ((packet.getStanzaTo() == null) || (((comp !=
null) || isLocalDomain(packet.getStanzaTo().toString())) &&!isDiscoDisabled(comp,
to)));
// .getStanzaFrom() != null) && ((packet.getStanzaTo() == null) || ((comp != null) &&
// !(comp instanceof DisableDisco)) || isLocalDomain(packet.getStanzaTo()
// .toString()))) {
return result;
}
}
//~ Formatted in Tigase Code Convention on 13/10/16 |
/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include "spice-client.h"
#include "spice-common.h"
#include "glib-compat.h"
#include "spice-channel-priv.h"
#include "spice-session-priv.h"
#include "spice-marshal.h"
#include "bio-gio.h"
#include <glib/gi18n.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#include <netinet/tcp.h> // TCP_NODELAY
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <ctype.h>
#include "gio-coroutine.h"
static void <API key>(SpiceChannel *channel, SpiceMsgIn *msg);
static void <API key>(SpiceChannel *channel, SpiceMsgOut *out);
static void <API key>(SpiceChannel *channel);
static void channel_reset(SpiceChannel *channel, gboolean migrating);
static void <API key>(SpiceChannel *channel);
static void <API key>(SpiceChannel *channel);
static gboolean channel_connect(SpiceChannel *channel, gboolean tls);
/**
* SECTION:spice-channel
* @short_description: the base channel class
* @title: Spice Channel
* @section_id:
* @see_also: #SpiceSession, #SpiceMainChannel and other channels
* @stability: Stable
* @include: spice-channel.h
*
* #SpiceChannel is the base class for the different kind of Spice
* channel connections, such as #SpiceMainChannel, or
* #SpiceInputsChannel.
*/
/* gobject glue */
#define <API key>(obj) \
(<API key> ((obj), SPICE_TYPE_CHANNEL, SpiceChannelPrivate))
<API key> (SpiceChannel, spice_channel, G_TYPE_OBJECT,
<API key> (g_define_type_id, sizeof (<API key>)));
/* Properties */
enum {
PROP_0,
PROP_SESSION,
PROP_CHANNEL_TYPE,
PROP_CHANNEL_ID,
<API key>,
};
/* Signals */
enum {
SPICE_CHANNEL_EVENT,
<API key>,
<API key>,
};
static guint signals[<API key>];
static void <API key>(SpiceChannel *channel);
static void <API key>(SpiceChannel *channel);
static void spice_channel_init(SpiceChannel *channel)
{
SpiceChannelPrivate *c;
c = channel->priv = <API key>(channel);
c->out_serial = 1;
c->in_serial = 1;
c->fd = -1;
c-><API key> = FALSE;
strcpy(c->name, "?");
c->caps = g_array_new(FALSE, TRUE, sizeof(guint32));
c->common_caps = g_array_new(FALSE, TRUE, sizeof(guint32));
c->remote_caps = g_array_new(FALSE, TRUE, sizeof(guint32));
c->remote_common_caps = g_array_new(FALSE, TRUE, sizeof(guint32));
<API key>(channel, <API key>);
<API key>(channel, <API key>);
#if HAVE_SASL
<API key>(channel, <API key>);
#endif
g_queue_init(&c->xmit_queue);
STATIC_MUTEX_INIT(c->xmit_queue_lock);
}
static void <API key>(GObject *gobject)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
const char *desc = <API key>(c->channel_type);
snprintf(c->name, sizeof(c->name), "%s-%d:%d",
desc, c->channel_type, c->channel_id);
CHANNEL_DEBUG(channel, "%s", __FUNCTION__);
const char *disabled = g_getenv("<API key>");
if (disabled && strstr(disabled, desc))
c->disable_channel_msg = TRUE;
<API key>(c->session, channel);
/* Chain up to the parent class */
if (G_OBJECT_CLASS(<API key>)->constructed)
G_OBJECT_CLASS(<API key>)->constructed(gobject);
}
static void <API key>(GObject *gobject)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
CHANNEL_DEBUG(channel, "%s %p", __FUNCTION__, gobject);
<API key>(channel, <API key>);
if (c->session) {
g_object_unref(c->session);
c->session = NULL;
}
g_clear_error(&c->error);
/* Chain up to the parent class */
if (G_OBJECT_CLASS(<API key>)->dispose)
G_OBJECT_CLASS(<API key>)->dispose(gobject);
}
static void <API key>(GObject *gobject)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
CHANNEL_DEBUG(channel, "%s %p", __FUNCTION__, gobject);
<API key>(gobject);
STATIC_MUTEX_CLEAR(c->xmit_queue_lock);
if (c->caps)
g_array_free(c->caps, TRUE);
if (c->common_caps)
g_array_free(c->common_caps, TRUE);
if (c->remote_caps)
g_array_free(c->remote_caps, TRUE);
if (c->remote_common_caps)
g_array_free(c->remote_common_caps, TRUE);
/* Chain up to the parent class */
if (G_OBJECT_CLASS(<API key>)->finalize)
G_OBJECT_CLASS(<API key>)->finalize(gobject);
}
static void <API key>(GObject *gobject,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
switch (prop_id) {
case PROP_SESSION:
g_value_set_object(value, c->session);
break;
case PROP_CHANNEL_TYPE:
g_value_set_int(value, c->channel_type);
break;
case PROP_CHANNEL_ID:
g_value_set_int(value, c->channel_id);
break;
case <API key>:
g_value_set_ulong(value, c->total_read_bytes);
break;
default:
<API key>(gobject, prop_id, pspec);
break;
}
}
G_GNUC_INTERNAL
gint <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
<API key>(c != NULL, 0);
return c->channel_id;
}
G_GNUC_INTERNAL
gint <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
<API key>(c != NULL, 0);
return c->channel_type;
}
static void <API key>(GObject *gobject,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
switch (prop_id) {
case PROP_SESSION:
c->session = g_value_dup_object(value);
break;
case PROP_CHANNEL_TYPE:
c->channel_type = g_value_get_int(value);
break;
case PROP_CHANNEL_ID:
c->channel_id = g_value_get_int(value);
break;
default:
<API key>(gobject, prop_id, pspec);
break;
}
}
static void <API key>(SpiceChannelClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
klass->iterate_write = <API key>;
klass->iterate_read = <API key>;
klass->channel_reset = channel_reset;
gobject_class->constructed = <API key>;
gobject_class->dispose = <API key>;
gobject_class->finalize = <API key>;
gobject_class->get_property = <API key>;
gobject_class->set_property = <API key>;
klass->handle_msg = <API key>;
<API key>
(gobject_class, PROP_SESSION,
g_param_spec_object("spice-session",
"Spice session",
"",
SPICE_TYPE_SESSION,
G_PARAM_READWRITE |
<API key> |
<API key>));
<API key>
(gobject_class, PROP_CHANNEL_TYPE,
g_param_spec_int("channel-type",
"Channel type",
"",
-1, INT_MAX, -1,
G_PARAM_READWRITE |
<API key> |
<API key>));
<API key>
(gobject_class, PROP_CHANNEL_ID,
g_param_spec_int("channel-id",
"Channel ID",
"",
-1, INT_MAX, -1,
G_PARAM_READWRITE |
<API key> |
<API key>));
<API key>
(gobject_class, <API key>,
g_param_spec_ulong("total-read-bytes",
"Total read bytes",
"",
0, G_MAXULONG, 0,
G_PARAM_READABLE |
<API key>));
/**
* SpiceChannel::channel-event:
* @channel: the channel that emitted the signal
* @event: a #SpiceChannelEvent
*
* The #SpiceChannel::channel-event signal is emitted when the
* state of the connection is changed. In case of errors,
* <API key>() may provide additional informations
* on the source of the error.
**/
signals[SPICE_CHANNEL_EVENT] =
g_signal_new("channel-event",
G_OBJECT_CLASS_TYPE(gobject_class),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET(SpiceChannelClass, channel_event),
NULL, NULL,
<API key>,
G_TYPE_NONE,
1,
<API key>);
/**
* SpiceChannel::open-fd:
* @channel: the channel that emitted the signal
* @with_tls: wether TLS connection is requested
*
* The #SpiceChannel::open-fd signal is emitted when a new
* connection is requested. This signal is emitted when the
* connection is made with <API key>().
**/
signals[<API key>] =
g_signal_new("open-fd",
G_OBJECT_CLASS_TYPE(gobject_class),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET(SpiceChannelClass, open_fd),
NULL, NULL,
<API key>,
G_TYPE_NONE,
1,
G_TYPE_INT);
<API key>(klass, sizeof(SpiceChannelPrivate));
SSL_library_init();
<API key>();
}
/* private header api */
static inline void <API key>(uint8_t *header, gboolean is_mini_header,
uint16_t type)
{
if (is_mini_header) {
((SpiceMiniDataHeader *)header)->type = type;
} else {
((SpiceDataHeader *)header)->type = type;
}
}
static inline void <API key>(uint8_t *header, gboolean is_mini_header,
uint32_t size)
{
if (is_mini_header) {
((SpiceMiniDataHeader *)header)->size = size;
} else {
((SpiceDataHeader *)header)->size = size;
}
}
G_GNUC_INTERNAL
uint16_t <API key>(uint8_t *header, gboolean is_mini_header)
{
if (is_mini_header) {
return ((SpiceMiniDataHeader *)header)->type;
} else {
return ((SpiceDataHeader *)header)->type;
}
}
G_GNUC_INTERNAL
uint32_t <API key>(uint8_t *header, gboolean is_mini_header)
{
if (is_mini_header) {
return ((SpiceMiniDataHeader *)header)->size;
} else {
return ((SpiceDataHeader *)header)->size;
}
}
static inline int <API key>(gboolean is_mini_header)
{
return is_mini_header ? sizeof(SpiceMiniDataHeader) : sizeof(SpiceDataHeader);
}
static inline void <API key>(uint8_t *header, gboolean is_mini_header,
uint64_t serial)
{
if (!is_mini_header) {
((SpiceDataHeader *)header)->serial = serial;
}
}
static inline void <API key>(uint8_t *header, gboolean is_mini_header)
{
if (!is_mini_header) {
((SpiceDataHeader *)header)->sub_list = 0;
}
}
static inline uint64_t <API key>(SpiceMsgIn *in)
{
SpiceChannelPrivate *c = in->channel->priv;
uint8_t *header = in->header;
if (c->use_mini_header) {
return c->in_serial;
} else {
return ((SpiceDataHeader *)header)->serial;
}
}
static inline uint64_t <API key>(SpiceMsgOut *out)
{
SpiceChannelPrivate *c = out->channel->priv;
if (c->use_mini_header) {
return c->out_serial;
} else {
return ((SpiceDataHeader *)out->header)->serial;
}
}
static inline uint32_t <API key>(uint8_t *header, gboolean is_mini_header)
{
if (is_mini_header) {
return 0;
} else {
return ((SpiceDataHeader *)header)->sub_list;
}
}
/* private msg api */
G_GNUC_INTERNAL
SpiceMsgIn *spice_msg_in_new(SpiceChannel *channel)
{
SpiceMsgIn *in;
<API key>(channel != NULL, NULL);
in = g_slice_new0(SpiceMsgIn);
in->refcount = 1;
in->channel = channel;
return in;
}
G_GNUC_INTERNAL
SpiceMsgIn *<API key>(SpiceChannel *channel, SpiceMsgIn *parent,
SpiceSubMessage *sub)
{
SpiceMsgIn *in;
<API key>(channel != NULL, NULL);
in = spice_msg_in_new(channel);
<API key>(in->header, channel->priv->use_mini_header, sub->type);
<API key>(in->header, channel->priv->use_mini_header, sub->size);
in->data = (uint8_t*)(sub+1);
in->dpos = sub->size;
in->parent = parent;
spice_msg_in_ref(parent);
return in;
}
G_GNUC_INTERNAL
void spice_msg_in_ref(SpiceMsgIn *in)
{
g_return_if_fail(in != NULL);
in->refcount++;
}
G_GNUC_INTERNAL
void spice_msg_in_unref(SpiceMsgIn *in)
{
g_return_if_fail(in != NULL);
in->refcount
if (in->refcount > 0)
return;
if (in->parsed)
in->pfree(in->parsed);
if (in->parent) {
spice_msg_in_unref(in->parent);
} else {
g_free(in->data);
}
g_slice_free(SpiceMsgIn, in);
}
G_GNUC_INTERNAL
int spice_msg_in_type(SpiceMsgIn *in)
{
<API key>(in != NULL, -1);
return <API key>(in->header, in->channel->priv->use_mini_header);
}
G_GNUC_INTERNAL
void *spice_msg_in_parsed(SpiceMsgIn *in)
{
<API key>(in != NULL, NULL);
return in->parsed;
}
G_GNUC_INTERNAL
void *spice_msg_in_raw(SpiceMsgIn *in, int *len)
{
<API key>(in != NULL, NULL);
<API key>(len != NULL, NULL);
*len = in->dpos;
return in->data;
}
static void hexdump(const char *prefix, unsigned char *data, int len)
{
int i;
for (i = 0; i < len; i++) {
if (i % 16 == 0)
fprintf(stderr, "%s:", prefix);
if (i % 4 == 0)
fprintf(stderr, " ");
fprintf(stderr, " %02x", data[i]);
if (i % 16 == 15)
fprintf(stderr, "\n");
}
if (i % 16 != 0)
fprintf(stderr, "\n");
}
G_GNUC_INTERNAL
void <API key>(SpiceMsgIn *in)
{
SpiceChannelPrivate *c = in->channel->priv;
fprintf(stderr, "--\n<< hdr: %s serial %" PRIu64 " type %d size %d sub-list %d\n",
c->name, <API key>(in),
<API key>(in->header, c->use_mini_header),
<API key>(in->header, c->use_mini_header),
<API key>(in->header, c->use_mini_header));
hexdump("<< msg", in->data, in->dpos);
}
G_GNUC_INTERNAL
void <API key>(SpiceMsgOut *out, unsigned char *data, int len)
{
SpiceChannelPrivate *c = out->channel->priv;
fprintf(stderr, "--\n>> hdr: %s serial %" PRIu64 " type %d size %d sub-list %d\n",
c->name,
<API key>(out),
<API key>(out->header, c->use_mini_header),
<API key>(out->header, c->use_mini_header),
<API key>(out->header, c->use_mini_header));
hexdump(">> msg", data, len);
}
static gboolean msg_check_read_only (int channel_type, int msg_type)
{
if (msg_type < 100) // those are the common messages
return FALSE;
switch (channel_type) {
/* messages allowed to be sent in read-only mode */
case SPICE_CHANNEL_MAIN:
switch (msg_type) {
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
return FALSE;
}
break;
case <API key>:
return FALSE;
}
return TRUE;
}
G_GNUC_INTERNAL
SpiceMsgOut *spice_msg_out_new(SpiceChannel *channel, int type)
{
SpiceChannelPrivate *c = channel->priv;
SpiceMsgOut *out;
<API key>(c != NULL, NULL);
out = g_slice_new0(SpiceMsgOut);
out->refcount = 1;
out->channel = channel;
out->ro_check = msg_check_read_only(c->channel_type, type);
out->marshallers = c->marshallers;
out->marshaller = <API key>();
out->header = <API key>(out->marshaller,
<API key>(c->use_mini_header));
<API key>(out->marshaller, <API key>(c->use_mini_header));
<API key>(out->header, c->use_mini_header, type);
<API key>(out->header, c->use_mini_header, c->out_serial);
<API key>(out->header, c->use_mini_header);
c->out_serial++;
return out;
}
G_GNUC_INTERNAL
void spice_msg_out_ref(SpiceMsgOut *out)
{
g_return_if_fail(out != NULL);
out->refcount++;
}
G_GNUC_INTERNAL
void spice_msg_out_unref(SpiceMsgOut *out)
{
g_return_if_fail(out != NULL);
out->refcount
if (out->refcount > 0)
return;
<API key>(out->marshaller);
g_slice_free(SpiceMsgOut, out);
}
/* system context */
static gboolean <API key>(gpointer user_data)
{
SpiceChannel *channel = SPICE_CHANNEL(user_data);
SpiceChannelPrivate *c = channel->priv;
/*
* Note:
*
* - This must be done before the wakeup as that may eventually
* call channel_reset() which checks this.
* - The lock calls are really necessary, this fixes the following race:
* 1) usb-event-thread calls spice_msg_out_send()
* 2) spice_msg_out_send calls g_timeout_add_full(...)
* 3) we run, set <API key> to 0
* 4) spice_msg_out_send stores the result of g_timeout_add_full() in
* <API key>, overwriting the 0 we just stored
* 5) <API key> now says there is a wakeup pending which is
* false
*/
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
c-><API key> = 0;
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
<API key>(channel, FALSE);
return FALSE;
}
/* any context (system/co-routine/usb-event-thread) */
G_GNUC_INTERNAL
void spice_msg_out_send(SpiceMsgOut *out)
{
SpiceChannelPrivate *c;
gboolean was_empty;
g_return_if_fail(out != NULL);
g_return_if_fail(out->channel != NULL);
c = out->channel->priv;
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
if (c->xmit_queue_blocked) {
g_warning("message queue is blocked, dropping message");
goto end;
}
was_empty = g_queue_is_empty(&c->xmit_queue);
g_queue_push_tail(&c->xmit_queue, out);
/* One wakeup is enough to empty the entire queue -> only do a wakeup
if the queue was empty, and there isn't one pending already. */
if (was_empty && !c-><API key>) {
c-><API key> =
/* Use g_timeout_add_full so that can specify the priority */
g_timeout_add_full(G_PRIORITY_HIGH, 0,
<API key>,
out->channel, NULL);
}
end:
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
}
/* coroutine context */
G_GNUC_INTERNAL
void <API key>(SpiceMsgOut *out)
{
g_return_if_fail(out != NULL);
<API key>(out->channel, out);
}
/*
* Write all 'data' of length 'datalen' bytes out to
* the wire
*/
/* coroutine context */
static void <API key>(SpiceChannel *channel,
const void *data,
size_t datalen)
{
SpiceChannelPrivate *c = channel->priv;
const char *ptr = data;
size_t offset = 0;
GIOCondition cond;
while (offset < datalen) {
gssize ret;
GError *error = NULL;
if (c->has_error) return;
cond = 0;
if (c->tls) {
ret = SSL_write(c->ssl, ptr+offset, datalen-offset);
if (ret < 0) {
ret = SSL_get_error(c->ssl, ret);
if (ret == SSL_ERROR_WANT_READ)
cond |= G_IO_IN;
if (ret == <API key>)
cond |= G_IO_OUT;
ret = -1;
}
} else {
ret = <API key>(<API key>(c->out),
ptr+offset, datalen-offset, NULL, &error);
if (ret < 0) {
if (g_error_matches(error, G_IO_ERROR, <API key>)) {
cond = G_IO_OUT;
} else {
CHANNEL_DEBUG(channel, "Send error %s", error->message);
}
g_clear_error(&error);
ret = -1;
}
}
if (ret == -1) {
if (cond != 0) {
// TODO: should use g_pollable_input/<API key>() in 2.28 ?
<API key>(&c->coroutine, c->sock, cond);
continue;
} else {
CHANNEL_DEBUG(channel, "Closing the channel: spice_channel_flush %d", errno);
c->has_error = TRUE;
return;
}
}
if (ret == 0) {
CHANNEL_DEBUG(channel, "Closing the connection: spice_channel_flush");
c->has_error = TRUE;
return;
}
offset += ret;
}
}
#if HAVE_SASL
/*
* Encode all buffered data, write all encrypted data out
* to the wire
*/
static void <API key>(SpiceChannel *channel, const void *data, size_t len)
{
SpiceChannelPrivate *c = channel->priv;
const char *output;
unsigned int outputlen;
int err;
err = sasl_encode(c->sasl_conn, data, len, &output, &outputlen);
if (err != SASL_OK) {
g_warning ("Failed to encode SASL data %s",
sasl_errstring(err, NULL, NULL));
c->has_error = TRUE;
return;
}
//CHANNEL_DEBUG(channel, "Flush SASL %d: %p %d", len, output, outputlen);
<API key>(channel, output, outputlen);
}
#endif
/* coroutine context */
static void spice_channel_write(SpiceChannel *channel, const void *data, size_t len)
{
#if HAVE_SASL
SpiceChannelPrivate *c = channel->priv;
if (c->sasl_conn)
<API key>(channel, data, len);
else
#endif
<API key>(channel, data, len);
}
/* coroutine context */
static void <API key>(SpiceChannel *channel, SpiceMsgOut *out)
{
uint8_t *data;
int free_data;
size_t len;
uint32_t msg_size;
g_return_if_fail(channel != NULL);
g_return_if_fail(out != NULL);
g_return_if_fail(channel == out->channel);
if (out->ro_check &&
<API key>(channel)) {
g_warning("Try to send message while read-only. Please report a bug.");
return;
}
msg_size = <API key>(out->marshaller) -
<API key>(channel->priv->use_mini_header);
<API key>(out->header, channel->priv->use_mini_header, msg_size);
data = <API key>(out->marshaller, 0, &len, &free_data);
/* <API key>(out, data, len); */
spice_channel_write(channel, data, len);
if (free_data)
g_free(data);
spice_msg_out_unref(out);
}
/*
* Read at least 1 more byte of data straight off the wire
* into the requested buffer.
*/
/* coroutine context */
static int <API key>(SpiceChannel *channel, void *data, size_t len)
{
SpiceChannelPrivate *c = channel->priv;
gssize ret;
GIOCondition cond;
reread:
if (c->has_error) return 0; /* has_error is set by disconnect(), return no error */
cond = 0;
if (c->tls) {
ret = SSL_read(c->ssl, data, len);
if (ret < 0) {
ret = SSL_get_error(c->ssl, ret);
if (ret == SSL_ERROR_WANT_READ)
cond |= G_IO_IN;
if (ret == <API key>)
cond |= G_IO_OUT;
ret = -1;
}
} else {
GError *error = NULL;
ret = <API key>(<API key>(c->in),
data, len, NULL, &error);
if (ret < 0) {
if (g_error_matches(error, G_IO_ERROR, <API key>)) {
cond = G_IO_IN;
} else {
CHANNEL_DEBUG(channel, "Read error %s", error->message);
}
g_clear_error(&error);
ret = -1;
}
}
if (ret == -1) {
if (cond != 0) {
// TODO: should use g_pollable_input/<API key>() ?
<API key>(&c->coroutine, c->sock, cond);
goto reread;
} else {
c->has_error = TRUE;
return -errno;
}
}
if (ret == 0) {
CHANNEL_DEBUG(channel, "Closing the connection: spice_channel_read() - ret=0");
c->has_error = TRUE;
return 0;
}
return ret;
}
#if HAVE_SASL
/*
* Read at least 1 more byte of data out of the SASL decrypted
* data buffer, into the internal read buffer
*/
static int <API key>(SpiceChannel *channel, void *data, size_t len)
{
SpiceChannelPrivate *c = channel->priv;
/* CHANNEL_DEBUG(channel, "Read %lu SASL %p size %d offset %d", len, c->sasl_decoded, */
/* c->sasl_decoded_length, c->sasl_decoded_offset); */
if (c->sasl_decoded == NULL || c->sasl_decoded_length == 0) {
char encoded[8192]; /* should stay lower than maxbufsize */
int err, ret;
g_warn_if_fail(c->sasl_decoded_offset == 0);
ret = <API key>(channel, encoded, sizeof(encoded));
if (ret < 0)
return ret;
err = sasl_decode(c->sasl_conn, encoded, ret,
&c->sasl_decoded, &c->sasl_decoded_length);
if (err != SASL_OK) {
g_warning("Failed to decode SASL data %s",
sasl_errstring(err, NULL, NULL));
c->has_error = TRUE;
return -EINVAL;
}
c->sasl_decoded_offset = 0;
}
if (c->sasl_decoded_length == 0)
return 0;
len = MIN(c->sasl_decoded_length - c->sasl_decoded_offset, len);
memcpy(data, c->sasl_decoded + c->sasl_decoded_offset, len);
c->sasl_decoded_offset += len;
if (c->sasl_decoded_offset == c->sasl_decoded_length) {
c->sasl_decoded_length = c->sasl_decoded_offset = 0;
c->sasl_decoded = NULL;
}
return len;
}
#endif
/*
* Fill the 'data' buffer up with exactly 'len' bytes worth of data
*/
/* coroutine context */
static int spice_channel_read(SpiceChannel *channel, void *data, size_t length)
{
SpiceChannelPrivate *c = channel->priv;
gsize len = length;
int ret;
while (len > 0) {
if (c->has_error) return 0; /* has_error is set by disconnect(), return no error */
#if HAVE_SASL
if (c->sasl_conn)
ret = <API key>(channel, data, len);
else
#endif
ret = <API key>(channel, data, len);
if (ret < 0)
return ret;
g_assert(ret <= len);
len -= ret;
data = ((char*)data) + ret;
#if DEBUG
if (len > 0)
CHANNEL_DEBUG(channel, "still needs %" G_GSIZE_FORMAT, len);
#endif
}
c->total_read_bytes += length;
return length;
}
/* coroutine context */
static void <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
EVP_PKEY *pubkey;
int nRSASize;
BIO *bioKey;
RSA *rsa;
char *password;
uint8_t *encrypted;
int rc;
bioKey = BIO_new(BIO_s_mem());
g_return_if_fail(bioKey != NULL);
BIO_write(bioKey, c->peer_msg->pub_key, <API key>);
pubkey = d2i_PUBKEY_bio(bioKey, NULL);
g_return_if_fail(pubkey != NULL);
rsa = pubkey->pkey.rsa;
nRSASize = RSA_size(rsa);
encrypted = g_alloca(nRSASize);
/*
The use of RSA encryption limit the potential maximum password length.
for <API key> it is RSA_size(rsa) - 41.
*/
g_object_get(c->session, "password", &password, NULL);
if (password == NULL)
password = g_strdup("");
rc = RSA_public_encrypt(strlen(password) + 1, (uint8_t*)password,
encrypted, rsa, <API key>);
g_warn_if_fail(rc > 0);
spice_channel_write(channel, encrypted, nRSASize);
memset(encrypted, 0, nRSASize);
EVP_PKEY_free(pubkey);
BIO_free(bioKey);
g_free(password);
}
/* coroutine context */
static void <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
if (c-><API key>)
g_set_error_literal(&c->error,
SPICE_CLIENT_ERROR,
SPICE_CLIENT_ERROR_<API key>,
_("Authentication failed: password and username are required"));
else
g_set_error_literal(&c->error,
SPICE_CLIENT_ERROR,
<API key>,
_("Authentication failed: password is required"));
c->event = <API key>;
c->has_error = TRUE; /* force disconnect */
}
/* coroutine context */
static gboolean <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
uint32_t link_res;
int rc;
rc = spice_channel_read(channel, &link_res, sizeof(link_res));
if (rc != sizeof(link_res)) {
CHANNEL_DEBUG(channel, "incomplete auth reply (%d/%" G_GSIZE_FORMAT ")",
rc, sizeof(link_res));
c->event = <API key>;
return FALSE;
}
if (link_res != SPICE_LINK_ERR_OK) {
CHANNEL_DEBUG(channel, "link result: reply %d", link_res);
<API key>(channel);
return FALSE;
}
c->state = <API key>;
<API key>(channel, signals[SPICE_CHANNEL_EVENT], 0, <API key>);
if (c->state == <API key>) {
<API key>(channel);
}
if (c->state != <API key>)
spice_channel_up(channel);
return TRUE;
}
G_GNUC_INTERNAL
void spice_channel_up(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
CHANNEL_DEBUG(channel, "channel up, state %d", c->state);
if (<API key>(channel)->channel_up)
<API key>(channel)->channel_up(channel);
}
/* coroutine context */
static void <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
uint8_t *buffer, *p;
int protocol, i;
c->link_hdr.magic = SPICE_MAGIC;
c->link_hdr.size = sizeof(c->link_msg);
g_object_get(c->session, "protocol", &protocol, NULL);
switch (protocol) {
case 1: /* protocol 1 == major 1, old 0.4 protocol, last active minor */
c->link_hdr.major_version = 1;
c->link_hdr.minor_version = 3;
c->parser = <API key>(c->channel_type, NULL);
c->marshallers = <API key>();
break;
case SPICE_VERSION_MAJOR: /* protocol 2 == current */
c->link_hdr.major_version = SPICE_VERSION_MAJOR;
c->link_hdr.minor_version = SPICE_VERSION_MINOR;
c->parser = <API key>(c->channel_type, NULL);
c->marshallers = <API key>();
break;
default:
g_critical("unknown major %d", protocol);
return;
}
c->link_msg.connection_id = <API key>(c->session);
c->link_msg.channel_type = c->channel_type;
c->link_msg.channel_id = c->channel_id;
c->link_msg.caps_offset = sizeof(c->link_msg);
c->link_msg.num_common_caps = c->common_caps->len;
c->link_msg.num_channel_caps = c->caps->len;
c->link_hdr.size += (c->link_msg.num_common_caps +
c->link_msg.num_channel_caps) * sizeof(uint32_t);
buffer = g_malloc0(sizeof(c->link_hdr) + c->link_hdr.size);
p = buffer;
memcpy(p, &c->link_hdr, sizeof(c->link_hdr)); p += sizeof(c->link_hdr);
memcpy(p, &c->link_msg, sizeof(c->link_msg)); p += sizeof(c->link_msg);
for (i = 0; i < c->common_caps->len; i++) {
*(uint32_t *)p = g_array_index(c->common_caps, uint32_t, i);
p += sizeof(uint32_t);
}
for (i = 0; i < c->caps->len; i++) {
*(uint32_t *)p = g_array_index(c->caps, uint32_t, i);
p += sizeof(uint32_t);
}
CHANNEL_DEBUG(channel, "channel type %d id %d num common caps %d num caps %d",
c->link_msg.channel_type,
c->link_msg.channel_id,
c->link_msg.num_common_caps,
c->link_msg.num_channel_caps);
spice_channel_write(channel, buffer, p - buffer);
g_free(buffer);
}
/* coroutine context */
static gboolean <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
int rc;
rc = spice_channel_read(channel, &c->peer_hdr, sizeof(c->peer_hdr));
if (rc != sizeof(c->peer_hdr)) {
g_warning("incomplete link header (%d/%" G_GSIZE_FORMAT ")",
rc, sizeof(c->peer_hdr));
goto error;
}
if (c->peer_hdr.magic != SPICE_MAGIC) {
g_warning("invalid SPICE_MAGIC!");
goto error;
}
CHANNEL_DEBUG(channel, "Peer version: %d:%d", c->peer_hdr.major_version, c->peer_hdr.minor_version);
if (c->peer_hdr.major_version != c->link_hdr.major_version) {
g_warning("major mismatch (got %d, expected %d)",
c->peer_hdr.major_version, c->link_hdr.major_version);
goto error;
}
c->peer_msg = g_malloc0(c->peer_hdr.size);
if (c->peer_msg == NULL) {
g_warning("invalid peer header size: %u", c->peer_hdr.size);
goto error;
}
return TRUE;
error:
/* Windows socket seems to give early CONNRESET errors. The server
does not linger when closing the socket if the protocol is
incompatible. Try with the oldest protocol in this case: */
if (c->link_hdr.major_version != 1) {
SPICE_DEBUG("%s: error, switching to protocol 1 (spice 0.4)", c->name);
c->state = <API key>;
g_object_set(c->session, "protocol", 1, NULL);
return FALSE;
}
c->event = <API key>;
return FALSE;
}
#if HAVE_SASL
/*
* NB, keep in sync with similar method in spice/server/reds.c
*/
static gchar *addr_to_string(GSocketAddress *addr)
{
GInetSocketAddress *iaddr = <API key>(addr);
guint16 port;
GInetAddress *host;
gchar *hoststr;
gchar *ret;
host = <API key>(iaddr);
port = <API key>(iaddr);
hoststr = <API key>(host);
ret = g_strdup_printf("%s;%hu", hoststr, port);
g_free(hoststr);
return ret;
}
static gboolean
<API key>(SpiceChannel *channel,
sasl_interact_t *interact)
{
SpiceChannelPrivate *c;
int ninteract;
gboolean ret = TRUE;
<API key>(channel != NULL, FALSE);
<API key>(channel->priv != NULL, FALSE);
c = channel->priv;
/* FIXME: we could keep connection open and ask connection details if missing */
for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++) {
switch (interact[ninteract].id) {
case SASL_CB_AUTHNAME:
case SASL_CB_USER:
c-><API key> = TRUE;
if (<API key>(c->session) == NULL)
return FALSE;
interact[ninteract].result = <API key>(c->session);
interact[ninteract].len = strlen(interact[ninteract].result);
break;
case SASL_CB_PASS:
if (<API key>(c->session) == NULL) {
/* Even if we reach this point, we have to continue looking for
* SASL_CB_AUTHNAME|SASL_CB_USER, otherwise we would return a
* wrong error to the applications */
ret = FALSE;
continue;
}
interact[ninteract].result = <API key>(c->session);
interact[ninteract].len = strlen(interact[ninteract].result);
break;
}
}
CHANNEL_DEBUG(channel, "Filled SASL interact");
return ret;
}
/*
*
* Init msg from server
*
* u32 mechlist-length
* u8-array mechlist-string
*
* Start msg to server
*
* u32 mechname-length
* u8-array mechname-string
* u32 clientout-length
* u8-array clientout-string
*
* Start msg from server
*
* u32 serverin-length
* u8-array serverin-string
* u8 continue
*
* Step msg to server
*
* u32 clientout-length
* u8-array clientout-string
*
* Step msg from server
*
* u32 serverin-length
* u8-array serverin-string
* u8 continue
*/
#define <API key> 300
#define <API key> 100
#define SASL_MAX_DATA_LEN (1024 * 1024)
/* Perform the SASL authentication process
*/
static gboolean <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c;
sasl_conn_t *saslconn = NULL;
<API key> secprops;
const char *clientout;
char *serverin = NULL;
unsigned int clientoutlen;
int err;
char *localAddr = NULL, *remoteAddr = NULL;
const void *val;
sasl_ssf_t ssf;
static const sasl_callback_t saslcb[] = {
{ .id = SASL_CB_USER },
{ .id = SASL_CB_AUTHNAME },
{ .id = SASL_CB_PASS },
{ .id = 0 },
};
sasl_interact_t *interact = NULL;
guint32 len;
char *mechlist = NULL;
const char *mechname;
gboolean ret = FALSE;
GSocketAddress *addr = NULL;
guint8 complete;
<API key>(channel != NULL, FALSE);
<API key>(channel->priv != NULL, FALSE);
c = channel->priv;
/* Sets up the SASL library as a whole */
err = sasl_client_init(NULL);
CHANNEL_DEBUG(channel, "Client initialize SASL authentication %d", err);
if (err != SASL_OK) {
g_critical("failed to initialize SASL library: %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
/* Get local address in form IPADDR:PORT */
addr = <API key>(c->sock, NULL);
if (!addr) {
g_critical("failed to get local address");
goto error;
}
if ((<API key>(addr) == <API key> ||
<API key>(addr) == <API key>) &&
(localAddr = addr_to_string(addr)) == NULL)
goto error;
g_clear_object(&addr);
/* Get remote address in form IPADDR:PORT */
addr = <API key>(c->sock, NULL);
if (!addr) {
g_critical("failed to get peer address");
goto error;
}
if ((<API key>(addr) == <API key> ||
<API key>(addr) == <API key>) &&
(remoteAddr = addr_to_string(addr)) == NULL)
goto error;
g_clear_object(&addr);
CHANNEL_DEBUG(channel, "Client SASL new host:'%s' local:'%s' remote:'%s'",
<API key>(c->session), localAddr, remoteAddr);
/* Setup a handle for being a client */
err = sasl_client_new("spice",
<API key>(c->session),
localAddr,
remoteAddr,
saslcb,
SASL_SUCCESS_DATA,
&saslconn);
if (err != SASL_OK) {
g_critical("Failed to create SASL client context: %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
if (c->ssl) {
sasl_ssf_t ssf;
ssf = SSL_get_cipher_bits(c->ssl, NULL);
err = sasl_setprop(saslconn, SASL_SSF_EXTERNAL, &ssf);
if (err != SASL_OK) {
g_critical("cannot set SASL external SSF %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
}
memset(&secprops, 0, sizeof secprops);
/* If we've got TLS, we don't care about SSF */
secprops.min_ssf = c->ssl ? 0 : 56; /* Equiv to DES supported by all Kerberos */
secprops.max_ssf = c->ssl ? 0 : 100000; /* Very strong ! AES == 256 */
secprops.maxbufsize = 100000;
/* If we're not TLS, then forbid any anonymous or trivially crackable auth */
secprops.security_flags = c->ssl ? 0 :
<API key> | <API key>;
err = sasl_setprop(saslconn, SASL_SEC_PROPS, &secprops);
if (err != SASL_OK) {
g_critical("cannot set security props %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
/* Get the supported mechanisms from the server */
spice_channel_read(channel, &len, sizeof(len));
if (c->has_error)
goto error;
if (len > <API key>) {
g_critical("mechlistlen %d too long", len);
goto error;
}
mechlist = g_malloc0(len + 1);
spice_channel_read(channel, mechlist, len);
mechlist[len] = '\0';
if (c->has_error) {
goto error;
}
restart:
/* Start the auth negotiation on the client end first */
CHANNEL_DEBUG(channel, "Client start negotiation mechlist '%s'", mechlist);
err = sasl_client_start(saslconn,
mechlist,
&interact,
&clientout,
&clientoutlen,
&mechname);
if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
g_critical("Failed to start SASL negotiation: %d (%s)",
err, sasl_errdetail(saslconn));
goto error;
}
/* Need to gather some credentials from the client */
if (err == SASL_INTERACT) {
if (!<API key>(channel, interact)) {
CHANNEL_DEBUG(channel, "Failed to collect auth credentials");
goto error;
}
goto restart;
}
CHANNEL_DEBUG(channel, "Server start negotiation with mech %s. Data %d bytes %p '%s'",
mechname, clientoutlen, clientout, clientout);
if (clientoutlen > SASL_MAX_DATA_LEN) {
g_critical("SASL negotiation data too long: %d bytes",
clientoutlen);
goto error;
}
/* Send back the chosen mechname */
len = strlen(mechname);
spice_channel_write(channel, &len, sizeof(guint32));
spice_channel_write(channel, mechname, len);
/* NB, distinction of NULL vs "" is *critical* in SASL */
if (clientout) {
len = clientoutlen + 1;
spice_channel_write(channel, &len, sizeof(guint32));
spice_channel_write(channel, clientout, len);
} else {
len = 0;
spice_channel_write(channel, &len, sizeof(guint32));
}
if (c->has_error)
goto error;
CHANNEL_DEBUG(channel, "Getting sever start negotiation reply");
/* Read the 'START' message reply from server */
spice_channel_read(channel, &len, sizeof(len));
if (c->has_error)
goto error;
if (len > SASL_MAX_DATA_LEN) {
g_critical("SASL negotiation data too long: %d bytes",
len);
goto error;
}
/* NB, distinction of NULL vs "" is *critical* in SASL */
if (len > 0) {
serverin = g_malloc0(len);
spice_channel_read(channel, serverin, len);
serverin[len - 1] = '\0';
len
} else {
serverin = NULL;
}
spice_channel_read(channel, &complete, sizeof(guint8));
if (c->has_error)
goto error;
CHANNEL_DEBUG(channel, "Client start result complete: %d. Data %d bytes %p '%s'",
complete, len, serverin, serverin);
/* Loop-the-loop...
* Even if the server has completed, the client must *always* do at least one step
* in this loop to verify the server isn't lying about something. Mutual auth */
for (;;) {
if (complete && err == SASL_OK)
break;
restep:
err = sasl_client_step(saslconn,
serverin,
len,
&interact,
&clientout,
&clientoutlen);
if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
g_critical("Failed SASL step: %d (%s)",
err, sasl_errdetail(saslconn));
goto error;
}
/* Need to gather some credentials from the client */
if (err == SASL_INTERACT) {
if (!<API key>(channel,
interact)) {
CHANNEL_DEBUG(channel, "%s", "Failed to collect auth credentials");
goto error;
}
goto restep;
}
if (serverin) {
g_free(serverin);
serverin = NULL;
}
CHANNEL_DEBUG(channel, "Client step result %d. Data %d bytes %p '%s'", err, clientoutlen, clientout, clientout);
/* Previous server call showed completion & we're now locally complete too */
if (complete && err == SASL_OK)
break;
/* Not done, prepare to talk with the server for another iteration */
/* NB, distinction of NULL vs "" is *critical* in SASL */
if (clientout) {
len = clientoutlen + 1;
spice_channel_write(channel, &len, sizeof(guint32));
spice_channel_write(channel, clientout, len);
} else {
len = 0;
spice_channel_write(channel, &len, sizeof(guint32));
}
if (c->has_error)
goto error;
CHANNEL_DEBUG(channel, "Server step with %d bytes %p", clientoutlen, clientout);
spice_channel_read(channel, &len, sizeof(guint32));
if (c->has_error)
goto error;
if (len > SASL_MAX_DATA_LEN) {
g_critical("SASL negotiation data too long: %d bytes", len);
goto error;
}
/* NB, distinction of NULL vs "" is *critical* in SASL */
if (len) {
serverin = g_malloc0(len);
spice_channel_read(channel, serverin, len);
serverin[len - 1] = '\0';
len
} else {
serverin = NULL;
}
spice_channel_read(channel, &complete, sizeof(guint8));
if (c->has_error)
goto error;
CHANNEL_DEBUG(channel, "Client step result complete: %d. Data %d bytes %p '%s'",
complete, len, serverin, serverin);
/* This server call shows complete, and earlier client step was OK */
if (complete) {
g_free(serverin);
serverin = NULL;
if (err == SASL_CONTINUE) /* something went wrong */
goto complete;
break;
}
}
/* Check for suitable SSF if non-TLS */
if (!c->ssl) {
err = sasl_getprop(saslconn, SASL_SSF, &val);
if (err != SASL_OK) {
g_critical("cannot query SASL ssf on connection %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
ssf = *(const int *)val;
CHANNEL_DEBUG(channel, "SASL SSF value %d", ssf);
if (ssf < 56) { /* 56 == DES level, good for Kerberos */
g_critical("negotiation SSF %d was not strong enough", ssf);
goto error;
}
}
complete:
CHANNEL_DEBUG(channel, "%s", "SASL authentication complete");
spice_channel_read(channel, &len, sizeof(len));
if (len == SPICE_LINK_ERR_OK) {
ret = TRUE;
/* This must come *after* check-auth-result, because the former
* is defined to be sent unencrypted, and setting saslconn turns
* on the SSF layer encryption processing */
c->sasl_conn = saslconn;
goto cleanup;
}
error:
if (saslconn)
sasl_dispose(&saslconn);
<API key>(channel);
ret = FALSE;
cleanup:
g_free(localAddr);
g_free(remoteAddr);
g_free(mechlist);
g_free(serverin);
g_clear_object(&addr);
return ret;
}
#endif /* HAVE_SASL */
/* coroutine context */
static gboolean <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c;
int rc, num_caps, i;
uint32_t *caps;
<API key>(channel != NULL, FALSE);
<API key>(channel->priv != NULL, FALSE);
c = channel->priv;
rc = spice_channel_read(channel, (uint8_t*)c->peer_msg + c->peer_pos,
c->peer_hdr.size - c->peer_pos);
c->peer_pos += rc;
if (c->peer_pos != c->peer_hdr.size) {
g_critical("%s: %s: incomplete link reply (%d/%d)",
c->name, __FUNCTION__, rc, c->peer_hdr.size);
goto error;
}
switch (c->peer_msg->error) {
case SPICE_LINK_ERR_OK:
/* nothing */
break;
case <API key>:
c->state = <API key>;
CHANNEL_DEBUG(channel, "switching to tls");
c->tls = TRUE;
return FALSE;
default:
g_warning("%s: %s: unhandled error %d",
c->name, __FUNCTION__, c->peer_msg->error);
goto error;
}
num_caps = c->peer_msg->num_channel_caps + c->peer_msg->num_common_caps;
CHANNEL_DEBUG(channel, "%s: %d caps", __FUNCTION__, num_caps);
/* see original spice/client code: */
/* g_return_if_fail(c->peer_msg + c->peer_msg->caps_offset * sizeof(uint32_t) > c->peer_msg + c->peer_hdr.size); */
caps = (uint32_t *)((uint8_t *)c->peer_msg + c->peer_msg->caps_offset);
g_array_set_size(c->remote_common_caps, c->peer_msg->num_common_caps);
for (i = 0; i < c->peer_msg->num_common_caps; i++, caps++) {
g_array_index(c->remote_common_caps, uint32_t, i) = *caps;
CHANNEL_DEBUG(channel, "got common caps %u:0x%X", i, *caps);
}
g_array_set_size(c->remote_caps, c->peer_msg->num_channel_caps);
for (i = 0; i < c->peer_msg->num_channel_caps; i++, caps++) {
g_array_index(c->remote_caps, uint32_t, i) = *caps;
CHANNEL_DEBUG(channel, "got channel caps %u:0x%X", i, *caps);
}
if (!<API key>(channel,
<API key>)) {
CHANNEL_DEBUG(channel, "Server supports spice ticket auth only");
<API key>(channel);
} else {
<API key> auth = { 0, };
#if HAVE_SASL
if (<API key>(channel, <API key>)) {
CHANNEL_DEBUG(channel, "Choosing SASL mechanism");
auth.auth_mechanism = <API key>;
spice_channel_write(channel, &auth, sizeof(auth));
if (!<API key>(channel))
return FALSE;
} else
#endif
if (<API key>(channel, <API key>)) {
auth.auth_mechanism = <API key>;
spice_channel_write(channel, &auth, sizeof(auth));
<API key>(channel);
} else {
g_warning("No compatible AUTH mechanism");
goto error;
}
}
c->use_mini_header = <API key>(channel,
<API key>);
CHANNEL_DEBUG(channel, "use mini header: %d", c->use_mini_header);
return TRUE;
error:
c->has_error = TRUE;
c->event = <API key>;
return FALSE;
}
/* system context */
G_GNUC_INTERNAL
void <API key>(SpiceChannel *channel, gboolean cancel)
{
GCoroutine *c = &channel->priv->coroutine;
if (cancel)
<API key>(c);
g_coroutine_wakeup(c);
}
G_GNUC_INTERNAL
gboolean <API key>(SpiceChannel *channel)
{
return <API key>(channel->priv->session);
}
/* coroutine context */
G_GNUC_INTERNAL
void <API key>(SpiceChannel *channel,
handler_msg_in msg_handler, gpointer data)
{
SpiceChannelPrivate *c = channel->priv;
SpiceMsgIn *in;
int msg_size;
int msg_type;
int sub_list_offset = 0;
in = spice_msg_in_new(channel);
/* receive message */
spice_channel_read(channel, in->header,
<API key>(c->use_mini_header));
if (c->has_error)
goto end;
msg_size = <API key>(in->header, c->use_mini_header);
/* FIXME: do not allow others to take ref on in, and use realloc here?
* this would avoid malloc/free on each message?
*/
in->data = g_malloc0(msg_size);
spice_channel_read(channel, in->data, msg_size);
if (c->has_error)
goto end;
in->dpos = msg_size;
msg_type = <API key>(in->header, c->use_mini_header);
sub_list_offset = <API key>(in->header, c->use_mini_header);
if (msg_type == SPICE_MSG_LIST || sub_list_offset) {
SpiceSubMessageList *sub_list;
SpiceSubMessage *sub;
SpiceMsgIn *sub_in;
int i;
sub_list = (SpiceSubMessageList *)(in->data + sub_list_offset);
for (i = 0; i < sub_list->size; i++) {
sub = (SpiceSubMessage *)(in->data + sub_list->sub_messages[i]);
sub_in = <API key>(channel, in, sub);
sub_in->parsed = c->parser(sub_in->data, sub_in->data + sub_in->dpos,
<API key>(sub_in->header,
c->use_mini_header),
c->peer_hdr.minor_version,
&sub_in->psize, &sub_in->pfree);
if (sub_in->parsed == NULL) {
g_critical("failed to parse sub-message: %s type %d",
c->name, <API key>(sub_in->header, c->use_mini_header));
goto end;
}
msg_handler(channel, sub_in, data);
spice_msg_in_unref(sub_in);
}
}
/* ack message */
if (c->message_ack_count) {
c->message_ack_count
if (!c->message_ack_count) {
SpiceMsgOut *out = spice_msg_out_new(channel, SPICE_MSGC_ACK);
<API key>(out);
c->message_ack_count = c->message_ack_window;
}
}
if (msg_type == SPICE_MSG_LIST) {
goto end;
}
/* parse message */
in->parsed = c->parser(in->data, in->data + msg_size, msg_type,
c->peer_hdr.minor_version, &in->psize, &in->pfree);
if (in->parsed == NULL) {
g_critical("failed to parse message: %s type %d",
c->name, msg_type);
goto end;
}
/* process message */
/* <API key>(in); */
msg_handler(channel, in, data);
end:
/* If the server uses full header, the serial is not necessarily equal
* to c->in_serial (the server can sometimes skip serials) */
c->last_message_serial = <API key>(in);
c->in_serial++;
spice_msg_in_unref(in);
}
static const char *to_string[] = {
NULL,
[ SPICE_CHANNEL_MAIN ] = "main",
[ <API key> ] = "display",
[ <API key> ] = "inputs",
[ <API key> ] = "cursor",
[ <API key> ] = "playback",
[ <API key> ] = "record",
[ <API key> ] = "tunnel",
[ <API key> ] = "smartcard",
[ <API key> ] = "usbredir",
[ SPICE_CHANNEL_PORT ] = "port",
[ <API key> ] = "webdav",
};
/**
* <API key>:
* @type: a channel-type property value
*
* Convert a channel-type property value to a string.
*
* Returns: string representation of @type.
* Since: 0.20
**/
const gchar* <API key>(gint type)
{
const char *str = NULL;
if (type >= 0 && type < G_N_ELEMENTS(to_string)) {
str = to_string[type];
}
return str ? str : "unknown channel type";
}
/**
* <API key>:
* @str: a string representation of the channel-type property
*
* Convert a channel-type property value to a string.
*
* Returns: the channel-type property value for a @str channel
* Since: 0.21
**/
gint <API key>(const gchar *str)
{
int i;
<API key>(str != NULL, -1);
for (i = 0; i < G_N_ELEMENTS(to_string); i++)
if (g_strcmp0(str, to_string[i]) == 0)
return i;
return -1;
}
G_GNUC_INTERNAL
gchar *<API key>(void)
{
return g_strjoin(", ",
<API key>(SPICE_CHANNEL_MAIN),
<API key>(<API key>),
<API key>(<API key>),
<API key>(<API key>),
<API key>(<API key>),
<API key>(<API key>),
#ifdef USE_SMARTCARD
<API key>(<API key>),
#endif
#ifdef USE_USBREDIR
<API key>(<API key>),
#endif
#ifdef USE_PHODAV
<API key>(<API key>),
#endif
NULL);
}
/**
* spice_channel_new:
* @s: the @SpiceSession the channel is linked to
* @type: the requested SPICECHANNELPRIVATE type
* @id: the channel-id
*
* Create a new #SpiceChannel of type @type, and channel ID @id.
*
* Returns: a weak reference to #SpiceChannel, the session owns the reference
**/
SpiceChannel *spice_channel_new(SpiceSession *s, int type, int id)
{
SpiceChannel *channel;
GType gtype = 0;
<API key>(s != NULL, NULL);
switch (type) {
case SPICE_CHANNEL_MAIN:
gtype = <API key>;
break;
case <API key>:
gtype = <API key>;
break;
case <API key>:
gtype = <API key>;
break;
case <API key>:
gtype = <API key>;
break;
case <API key>:
case <API key>: {
if (!<API key>(s)) {
g_debug("audio channel is disabled, not creating it");
return NULL;
}
gtype = type == <API key> ?
<API key> : <API key>;
break;
}
#ifdef USE_SMARTCARD
case <API key>: {
if (!<API key>(s)) {
g_debug("smartcard channel is disabled, not creating it");
return NULL;
}
gtype = <API key>;
break;
}
#endif
#ifdef USE_USBREDIR
case <API key>: {
if (!<API key>(s)) {
g_debug("usbredir channel is disabled, not creating it");
return NULL;
}
gtype = <API key>;
break;
}
#endif
#ifdef USE_PHODAV
case <API key>: {
gtype = <API key>;
break;
}
#endif
case SPICE_CHANNEL_PORT:
gtype = <API key>;
break;
default:
g_debug("unsupported channel kind: %s: %d",
<API key>(type), type);
return NULL;
}
channel = SPICE_CHANNEL(g_object_new(gtype,
"spice-session", s,
"channel-type", type,
"channel-id", id,
NULL));
return channel;
}
/**
* <API key>:
* @channel:
*
* Disconnect and unref the @channel.
*
* Deprecated: 0.27: this function has been deprecated because it is
* misleading, the object is not actually destroyed. Instead, it is
* recommended to call explicitely <API key>() and
* g_object_unref().
**/
void <API key>(SpiceChannel *channel)
{
g_return_if_fail(channel != NULL);
CHANNEL_DEBUG(channel, "channel destroy");
<API key>(channel, SPICE_CHANNEL_NONE);
g_object_unref(channel);
}
/* any context */
static void <API key>(SpiceChannel *channel, gboolean success)
{
SpiceChannelPrivate *c = channel->priv;
GSList *l;
for (l = c->flushing; l != NULL; l = l->next) {
GSimpleAsyncResult *result = <API key>(l->data);
<API key>(result, success);
<API key>(result);
}
g_slist_free_full(c->flushing, g_object_unref);
c->flushing = NULL;
}
/* coroutine context */
static void <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
SpiceMsgOut *out;
do {
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
out = g_queue_pop_head(&c->xmit_queue);
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
if (out)
<API key>(channel, out);
} while (out);
<API key>(channel, TRUE);
}
/* coroutine context */
static void <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
<API key>(&c->coroutine, c->sock, G_IO_IN);
/* treat all incoming data (block on message completion) */
while (!c->has_error &&
c->state != <API key> &&
<API key>(<API key>(c->in))
) { do
<API key>(channel,
(handler_msg_in)<API key>(channel)->handle_msg, NULL);
#if HAVE_SASL
/* flush the sasl buffer too */
while (c->sasl_decoded != NULL);
#else
while (FALSE);
#endif
}
}
static gboolean wait_migration(gpointer data)
{
SpiceChannel *channel = SPICE_CHANNEL(data);
SpiceChannelPrivate *c = channel->priv;
if (c->state != <API key>) {
CHANNEL_DEBUG(channel, "unfreeze channel");
return TRUE;
}
return FALSE;
}
/* coroutine context */
static gboolean <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
if (c->state == <API key> &&
!<API key>(&c->coroutine, wait_migration, channel))
CHANNEL_DEBUG(channel, "migration wait cancelled");
/* flush any pending write and read */
if (!c->has_error)
<API key>(channel)->iterate_write(channel);
if (!c->has_error)
<API key>(channel)->iterate_read(channel);
if (c->has_error) {
GIOCondition ret;
if (!c->sock)
return FALSE;
/* We don't want to report an error if the socket was closed gracefully
* on the other end (VM shutdown) */
ret = <API key>(c->sock, G_IO_IN | G_IO_ERR);
if (ret & G_IO_ERR) {
CHANNEL_DEBUG(channel, "channel got error");
if (c->state > <API key>) {
if (c->state == <API key>)
c->event = <API key>;
else
c->event = <API key>;
}
}
return FALSE;
}
return TRUE;
}
/* we use an idle function to allow the coroutine to exit before we actually
* unref the object since the coroutine's state is part of the object */
static gboolean <API key>(gpointer data)
{
SpiceChannel *channel = SPICE_CHANNEL(data);
SpiceChannelPrivate *c = channel->priv;
gboolean was_ready = c->state == <API key>;
CHANNEL_DEBUG(channel, "Delayed unref channel %p", channel);
<API key>(c->coroutine.coroutine.exited == TRUE, FALSE);
c->state = <API key>;
if (c->event != SPICE_CHANNEL_NONE) {
<API key>(channel, signals[SPICE_CHANNEL_EVENT], 0, c->event);
c->event = SPICE_CHANNEL_NONE;
g_clear_error(&c->error);
}
if (was_ready)
<API key>(channel, signals[SPICE_CHANNEL_EVENT], 0, <API key>);
g_object_unref(G_OBJECT(data));
return FALSE;
}
static X509_LOOKUP_METHOD <API key> = {
"<API key>",
0
};
static int <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
STACK_OF(X509_INFO) *inf;
X509_INFO *itmp;
X509_LOOKUP *lookup;
BIO *in;
int i, count = 0;
guint8 *ca;
guint size;
const gchar *ca_file;
int rc;
<API key>(c->ctx != NULL, 0);
lookup = <API key>(c->ctx->cert_store, &<API key>);
ca_file = <API key>(c->session);
<API key>(c->session, &ca, &size);
CHANNEL_DEBUG(channel, "Load CA, file: %s, data: %p", ca_file, ca);
g_warn_if_fail(ca_file || ca);
if (ca != NULL) {
in = BIO_new_mem_buf(ca, size);
inf = <API key>(in, NULL, NULL, NULL);
BIO_free(in);
for (i = 0; i < sk_X509_INFO_num(inf); i++) {
itmp = sk_X509_INFO_value(inf, i);
if (itmp->x509) {
X509_STORE_add_cert(lookup->store_ctx, itmp->x509);
count++;
}
if (itmp->crl) {
X509_STORE_add_crl(lookup->store_ctx, itmp->crl);
count++;
}
}
<API key>(inf, X509_INFO_free);
}
if (ca_file != NULL) {
rc = <API key>(c->ctx, ca_file, NULL);
if (rc != 1)
g_warning("loading ca certs from %s failed", ca_file);
else
count++;
}
if (count == 0) {
rc = <API key>(c->ctx);
if (rc != 1)
g_warning("loading ca certs from default location failed");
else
count++;
}
return count;
}
/**
* <API key>:
* @channel:
*
* Retrieves the #GError currently set on channel, if the #SpiceChannel
* is in error state and can provide additional error details.
*
* Returns: the pointer to the error, or %NULL
* Since: 0.24
**/
const GError* <API key>(SpiceChannel *self)
{
SpiceChannelPrivate *c;
<API key>(SPICE_IS_CHANNEL(self), NULL);
c = self->priv;
return c->error;
}
/* coroutine context */
static void *<API key>(void *data)
{
SpiceChannel *channel = SPICE_CHANNEL(data);
SpiceChannelPrivate *c = channel->priv;
guint verify;
int rc, delay_val = 1;
/* When some other SSL/TLS version becomes obsolete, add it to this
* variable. */
long ssl_options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
CHANNEL_DEBUG(channel, "Started background coroutine %p", &c->coroutine);
if (<API key>(c->session)) {
if (c->fd < 0) {
g_critical("fd not provided!");
c->event = <API key>;
goto cleanup;
}
if (!(c->sock = <API key>(c->fd, NULL))) {
CHANNEL_DEBUG(channel, "Failed to open socket from fd %d", c->fd);
c->event = <API key>;
goto cleanup;
}
<API key>(c->sock, FALSE);
<API key>(c->sock, TRUE);
c->conn = <API key>(c->sock);
goto connected;
}
reconnect:
c->conn = <API key>(c->session, channel, &c->tls, &c->error);
if (c->conn == NULL) {
if (!c->error && !c->tls) {
CHANNEL_DEBUG(channel, "trying with TLS port");
c->tls = true; /* FIXME: does that really work with provided fd */
goto reconnect;
} else {
CHANNEL_DEBUG(channel, "Connect error");
c->event = <API key>;
goto cleanup;
}
}
c->sock = g_object_ref(<API key>(c->conn));
if (c->tls) {
c->ctx = SSL_CTX_new(SSLv23_method());
if (c->ctx == NULL) {
g_critical("SSL_CTX_new failed");
c->event = <API key>;
goto cleanup;
}
SSL_CTX_set_options(c->ctx, ssl_options);
verify = <API key>(c->session);
if (verify &
(<API key> | <API key>)) {
rc = <API key>(channel);
if (rc == 0) {
g_warning("no cert loaded");
if (verify & <API key>) {
g_warning("only pubkey active");
verify = <API key>;
} else {
c->event = <API key>;
goto cleanup;
}
}
}
{
const gchar *ciphers = <API key>(c->session);
if (ciphers != NULL) {
rc = <API key>(c->ctx, ciphers);
if (rc != 1)
g_warning("loading cipher list %s failed", ciphers);
}
}
c->ssl = SSL_new(c->ctx);
if (c->ssl == NULL) {
g_critical("SSL_new failed");
c->event = <API key>;
goto cleanup;
}
BIO *bio = bio_new_giostream(G_IO_STREAM(c->conn));
SSL_set_bio(c->ssl, bio, bio);
{
guint8 *pubkey;
guint pubkey_len;
<API key>(c->session, &pubkey, &pubkey_len);
c->sslverify = <API key>(c->ssl, verify,
<API key>(c->session),
(char*)pubkey, pubkey_len,
<API key>(c->session));
}
ssl_reconnect:
rc = SSL_connect(c->ssl);
if (rc <= 0) {
rc = SSL_get_error(c->ssl, rc);
if (rc == SSL_ERROR_WANT_READ || rc == <API key>) {
<API key>(&c->coroutine, c->sock, G_IO_OUT|G_IO_ERR|G_IO_HUP);
goto ssl_reconnect;
} else {
g_warning("%s: SSL_connect: %s",
c->name, ERR_error_string(rc, NULL));
c->event = <API key>;
goto cleanup;
}
}
}
connected:
c->has_error = FALSE;
c->in = <API key>(G_IO_STREAM(c->conn));
c->out = <API key>(G_IO_STREAM(c->conn));
rc = setsockopt(g_socket_get_fd(c->sock), IPPROTO_TCP, TCP_NODELAY,
(const char*)&delay_val, sizeof(delay_val));
if ((rc != 0)
#ifdef ENOTSUP
&& (errno != ENOTSUP)
#endif
) {
g_warning("%s: could not set sockopt TCP_NODELAY: %s", c->name,
strerror(errno));
}
<API key>(channel);
if (!<API key>(channel) ||
!<API key>(channel) ||
!<API key>(channel))
goto cleanup;
while (<API key>(channel))
;
cleanup:
CHANNEL_DEBUG(channel, "Coroutine exit %s", c->name);
spice_channel_reset(channel, FALSE);
if (c->state == <API key> ||
c->state == <API key>) {
g_warn_if_fail(c->event == SPICE_CHANNEL_NONE);
channel_connect(channel, c->tls);
g_object_unref(channel);
} else
g_idle_add(<API key>, data);
/* Co-routine exits now - the SpiceChannel object may no longer exist,
so don't do anything else now unless you like SEGVs */
return NULL;
}
static gboolean connect_delayed(gpointer data)
{
SpiceChannel *channel = data;
SpiceChannelPrivate *c = channel->priv;
struct coroutine *co;
CHANNEL_DEBUG(channel, "Open coroutine starting %p", channel);
c->connect_delayed_id = 0;
co = &c->coroutine.coroutine;
co->stack_size = 16 << 20; /* 16Mb */
co->entry = <API key>;
co->release = NULL;
coroutine_init(co);
coroutine_yieldto(co, channel);
return FALSE;
}
/* any context */
static gboolean channel_connect(SpiceChannel *channel, gboolean tls)
{
SpiceChannelPrivate *c = channel->priv;
<API key>(c != NULL, FALSE);
if (c->session == NULL || c->channel_type == -1 || c->channel_id == -1) {
/* unset properties or unknown channel type */
g_warning("%s: channel setup incomplete", __FUNCTION__);
return false;
}
c->state = <API key>;
c->tls = tls;
if (<API key>(c->session)) {
if (c->fd == -1) {
CHANNEL_DEBUG(channel, "requesting fd");
/* FIXME: no way for client to provide fd atm. */
/* It could either chain on parent channel.. */
/* or register migration channel on parent session, or ? */
g_signal_emit(channel, signals[<API key>], 0, c->tls);
return true;
}
}
c->xmit_queue_blocked = FALSE;
<API key>(c->sock == NULL, FALSE);
g_object_ref(G_OBJECT(channel)); /* Unref'd when co-routine exits */
/* we connect in idle, to let previous coroutine exit, if present */
c->connect_delayed_id = g_idle_add(connect_delayed, channel);
return true;
}
/**
* <API key>:
* @channel:
*
* Connect the channel, using #SpiceSession connection informations
*
* Returns: %TRUE on success.
**/
gboolean <API key>(SpiceChannel *channel)
{
<API key>(SPICE_IS_CHANNEL(channel), FALSE);
SpiceChannelPrivate *c = channel->priv;
if (c->state >= <API key>)
return TRUE;
<API key>(channel->priv->fd == -1, FALSE);
return channel_connect(channel, FALSE);
}
/**
* <API key>:
* @channel:
* @fd: a file descriptor (socket) or -1.
* request mechanism
*
* Connect the channel using @fd socket.
*
* If @fd is -1, a valid fd will be requested later via the
* SpiceChannel::open-fd signal.
*
* Returns: %TRUE on success.
**/
gboolean <API key>(SpiceChannel *channel, int fd)
{
SpiceChannelPrivate *c;
<API key>(SPICE_IS_CHANNEL(channel), FALSE);
<API key>(channel->priv != NULL, FALSE);
<API key>(channel->priv->fd == -1, FALSE);
<API key>(fd >= -1, FALSE);
c = channel->priv;
if (c->state > <API key>) {
g_warning("Invalid channel_connect state: %d", c->state);
return true;
}
c->fd = fd;
return channel_connect(channel, FALSE);
}
/* system or coroutine context */
static void channel_reset(SpiceChannel *channel, gboolean migrating)
{
SpiceChannelPrivate *c = channel->priv;
CHANNEL_DEBUG(channel, "channel reset");
if (c->connect_delayed_id) {
g_source_remove(c->connect_delayed_id);
c->connect_delayed_id = 0;
}
#if HAVE_SASL
if (c->sasl_conn) {
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
c->sasl_decoded_offset = c->sasl_decoded_length = 0;
}
#endif
<API key>(c->sslverify);
c->sslverify = NULL;
if (c->ssl) {
SSL_free(c->ssl);
c->ssl = NULL;
}
if (c->ctx) {
SSL_CTX_free(c->ctx);
c->ctx = NULL;
}
if (c->conn) {
g_object_unref(c->conn);
c->conn = NULL;
}
g_clear_object(&c->sock);
c->fd = -1;
c-><API key> = FALSE;
g_free(c->peer_msg);
c->peer_msg = NULL;
c->peer_pos = 0;
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
c->xmit_queue_blocked = TRUE; /* Disallow queuing new messages */
gboolean was_empty = g_queue_is_empty(&c->xmit_queue);
g_queue_foreach(&c->xmit_queue, (GFunc)spice_msg_out_unref, NULL);
g_queue_clear(&c->xmit_queue);
if (c-><API key>) {
g_source_remove(c-><API key>);
c-><API key> = 0;
}
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
<API key>(channel, was_empty);
g_array_set_size(c->remote_common_caps, 0);
g_array_set_size(c->remote_caps, 0);
g_array_set_size(c->common_caps, 0);
/* Restore our default capabilities in case the channel gets re-used */
<API key>(channel, <API key>);
<API key>(channel, <API key>);
<API key>(channel);
if (c->state == <API key>)
<API key>(<API key>(channel),
<API key>);
}
/* system or coroutine context */
G_GNUC_INTERNAL
void spice_channel_reset(SpiceChannel *channel, gboolean migrating)
{
CHANNEL_DEBUG(channel, "reset %s", migrating ? "migrating" : "");
<API key>(channel)->channel_reset(channel, migrating);
}
/**
* <API key>:
* @channel:
* @reason: a channel event emitted on main context (or #SPICE_CHANNEL_NONE)
*
* Close the socket and reset connection specific data. Finally, emit
* @reason #SpiceChannel::channel-event on main context if not
* #SPICE_CHANNEL_NONE.
**/
void <API key>(SpiceChannel *channel, SpiceChannelEvent reason)
{
SpiceChannelPrivate *c;
CHANNEL_DEBUG(channel, "channel disconnect %d", reason);
g_return_if_fail(SPICE_IS_CHANNEL(channel));
g_return_if_fail(channel->priv != NULL);
c = channel->priv;
if (c->state == <API key>)
return;
if (reason == <API key>)
c->state = <API key>;
c->has_error = TRUE; /* break the loop */
if (c->state == <API key>) {
c->state = <API key>;
} else
<API key>(channel, TRUE);
if (reason != SPICE_CHANNEL_NONE)
g_signal_emit(G_OBJECT(channel), signals[SPICE_CHANNEL_EVENT], 0, reason);
}
static gboolean test_capability(GArray *caps, guint32 cap)
{
guint32 c, word_index = cap / 32;
gboolean ret;
if (caps == NULL)
return FALSE;
if (caps->len < word_index + 1)
return FALSE;
c = g_array_index(caps, guint32, word_index);
ret = (c & (1 << (cap % 32))) != 0;
SPICE_DEBUG("test cap %d in 0x%X: %s", cap, c, ret ? "yes" : "no");
return ret;
}
/**
* <API key>:
* @channel:
* @cap:
*
* Test availability of remote "channel kind capability".
*
* Returns: %TRUE if @cap (channel kind capability) is available.
**/
gboolean <API key>(SpiceChannel *self, guint32 cap)
{
SpiceChannelPrivate *c;
<API key>(SPICE_IS_CHANNEL(self), FALSE);
c = self->priv;
return test_capability(c->remote_caps, cap);
}
/**
* <API key>:
* @channel:
* @cap:
*
* Test availability of remote "common channel capability".
*
* Returns: %TRUE if @cap (common channel capability) is available.
**/
gboolean <API key>(SpiceChannel *self, guint32 cap)
{
SpiceChannelPrivate *c;
<API key>(SPICE_IS_CHANNEL(self), FALSE);
c = self->priv;
return test_capability(c->remote_common_caps, cap);
}
static void set_capability(GArray *caps, guint32 cap)
{
guint word_index = cap / 32;
g_return_if_fail(caps != NULL);
if (caps->len <= word_index)
g_array_set_size(caps, word_index + 1);
g_array_index(caps, guint32, word_index) =
g_array_index(caps, guint32, word_index) | (1 << (cap % 32));
}
/**
* <API key>:
* @channel:
* @cap: a capability
*
* Enable specific channel-kind capability.
* Deprecated: 0.13: this function has been removed
**/
#undef <API key>
void <API key>(SpiceChannel *channel, guint32 cap)
{
SpiceChannelPrivate *c;
g_return_if_fail(SPICE_IS_CHANNEL(channel));
c = channel->priv;
set_capability(c->caps, cap);
}
G_GNUC_INTERNAL
void spice_caps_set(GArray *caps, guint32 cap, const gchar *desc)
{
g_return_if_fail(caps != NULL);
g_return_if_fail(desc != NULL);
if (g_strcmp0(g_getenv(desc), "0") == 0)
return;
set_capability(caps, cap);
}
G_GNUC_INTERNAL
SpiceSession* <API key>(SpiceChannel *channel)
{
<API key>(SPICE_IS_CHANNEL(channel), NULL);
return channel->priv->session;
}
G_GNUC_INTERNAL
enum spice_channel_state <API key>(SpiceChannel *channel)
{
<API key>(SPICE_IS_CHANNEL(channel),
<API key>);
return channel->priv->state;
}
G_GNUC_INTERNAL
void spice_channel_swap(SpiceChannel *channel, SpiceChannel *swap, gboolean swap_msgs)
{
SpiceChannelPrivate *c = channel->priv;
SpiceChannelPrivate *s = swap->priv;
g_return_if_fail(c != NULL);
g_return_if_fail(s != NULL);
g_return_if_fail(s->session != NULL);
g_return_if_fail(s->sock != NULL);
#define SWAP(Field) ({ \
typeof (c->Field) Field = c->Field; \
c->Field = s->Field; \
s->Field = Field; \
})
/* TODO: split channel in 2 objects: a controller and a swappable
state object */
SWAP(sock);
SWAP(conn);
SWAP(in);
SWAP(out);
SWAP(ctx);
SWAP(ssl);
SWAP(sslverify);
SWAP(tls);
SWAP(use_mini_header);
if (swap_msgs) {
SWAP(xmit_queue);
SWAP(xmit_queue_blocked);
SWAP(in_serial);
SWAP(out_serial);
}
SWAP(caps);
SWAP(common_caps);
SWAP(remote_caps);
SWAP(remote_common_caps);
#if HAVE_SASL
SWAP(sasl_conn);
SWAP(sasl_decoded);
SWAP(sasl_decoded_length);
SWAP(sasl_decoded_offset);
#endif
}
/* coroutine context */
static void <API key>(SpiceChannel *channel, SpiceMsgIn *msg)
{
SpiceChannelClass *klass = <API key>(channel);
int type = spice_msg_in_type(msg);
spice_msg_handler handler;
g_return_if_fail(type < klass->priv->handlers->len);
if (type > SPICE_MSG_BASE_LAST && channel->priv->disable_channel_msg)
return;
handler = g_array_index(klass->priv->handlers, spice_msg_handler, type);
g_return_if_fail(handler != NULL);
handler(channel, msg);
}
static void <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
g_array_set_size(c->caps, 0);
if (<API key>(channel)-><API key>) {
<API key>(channel)-><API key>(channel);
}
}
static void <API key>(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
if (<API key>(channel)-><API key>) {
<API key>(channel)-><API key>(channel);
} else {
c->state = <API key>;
}
}
/**
* <API key>:
* @channel: a #SpiceChannel
* @cancellable: (allow-none): optional GCancellable object, %NULL to ignore
* @callback: (scope async): callback to call when the request is satisfied
* @user_data: (closure): the data to pass to callback function
*
* Forces an asynchronous write of all user-space buffered data for
* the given channel.
*
* When the operation is finished callback will be called. You can
* then call <API key>() to get the result of the
* operation.
*
* Since: 0.15
**/
void <API key>(SpiceChannel *self, GCancellable *cancellable,
GAsyncReadyCallback callback, gpointer user_data)
{
GSimpleAsyncResult *simple;
SpiceChannelPrivate *c;
gboolean was_empty;
g_return_if_fail(SPICE_IS_CHANNEL(self));
c = self->priv;
if (c->state != <API key>) {
<API key>(G_OBJECT(self), callback, user_data,
SPICE_CLIENT_ERROR, <API key>,
"The channel is not ready yet");
return;
}
simple = <API key>(G_OBJECT(self), callback, user_data,
<API key>);
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
was_empty = g_queue_is_empty(&c->xmit_queue);
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
if (was_empty) {
<API key>(simple, TRUE);
<API key>(simple);
g_object_unref(simple);
return;
}
c->flushing = g_slist_append(c->flushing, simple);
}
/**
* <API key>:
* @channel: a #SpiceChannel
* @result: a #GAsyncResult
* @error: a #GError location to store the error occurring, or %NULL
* to ignore.
*
* Finishes flushing a channel.
*
* Returns: %TRUE if flush operation succeeded, %FALSE otherwise.
* Since: 0.15
**/
gboolean <API key>(SpiceChannel *self, GAsyncResult *result,
GError **error)
{
GSimpleAsyncResult *simple;
<API key>(SPICE_IS_CHANNEL(self), FALSE);
<API key>(result != NULL, FALSE);
simple = (GSimpleAsyncResult *)result;
if (<API key>(simple, error))
return -1;
<API key>(<API key>(result, G_OBJECT(self),
<API key>), FALSE);
CHANNEL_DEBUG(self, "flushed finished!");
return <API key>(simple);
} |
define('<API key>', [
'jquery',
'<API key>'
], function($, Loader) {
'use strict';
var editorId = 'wiki', info = {
type: editorId,
href: '&editor=wiki&force=1',
name: 'Wiki',
compatible: ['wiki', 'wysiwyg']
};
Loader.bootstrap(info).then(keys => {
require(['<API key>'], function (RealtimeWikiEditor) {
if (RealtimeWikiEditor && RealtimeWikiEditor.main) {
keys._update = Loader.updateKeys.bind(Loader, editorId);
var config = Loader.getConfig();
config.rtURL = Loader.getEditorURL(window.location.href, info);
RealtimeWikiEditor.main(config, keys);
} else {
console.error("Couldn't find RealtimeWikiEditor.main, aborting.");
}
});
});
var getWikiLock = function() {
var force = document.querySelectorAll('a[href*="editor=wiki"][href*="force=1"][href*="/edit/"]');
return !!force.length;
};
var displayButtonModal = function() {
// TODO: This JavaScript code is not loaded anymore on the edit lock page so we need to decide what to do with it
// (either drop it or find a clean way to load it on the edit lock page).
var lock = Loader.getDocLock();
var wikiLock = getWikiLock();
var button = $();
if ($('.realtime-button-' + info.type).length) {
button = $('<button class="btn btn-success"></button>').text(
Loader.messages.get('redirectDialog.join', info.name));
$('.realtime-button-' + info.type).prepend(button).prepend('<br/>');
} else if (lock && wikiLock) {
button = $('<button class="btn btn-primary"></button>').text(
Loader.messages.get('redirectDialog.create', info.name));
$('.realtime-buttons').append('<br/>').append(button);
}
button.on('click', function() {
window.location.href = Loader.getEditorURL(window.location.href, info);
});
};
displayButtonModal();
$(document).on('insertButton', displayButtonModal);
}); |
#ifndef <API key>
#define <API key>
#include <gdk/gdkwindow.h>
G_BEGIN_DECLS
#define <API key> (<API key> ())
#define GDK_WINDOW_IMPL(obj) (<API key> ((obj), <API key>, GdkWindowImpl))
#define GDK_IS_WINDOW_IMPL(obj) (<API key> ((obj), <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>, GdkWindowImplIface))
typedef struct _GdkWindowImpl GdkWindowImpl; /* dummy */
typedef struct _GdkWindowImplIface GdkWindowImplIface;
struct _GdkWindowImplIface
{
GTypeInterface g_iface;
void (* show) (GdkWindow *window,
gboolean already_mapped);
void (* hide) (GdkWindow *window);
void (* withdraw) (GdkWindow *window);
void (* raise) (GdkWindow *window);
void (* lower) (GdkWindow *window);
void (* restack_under) (GdkWindow *window,
GList *native_siblings);
void (* move_resize) (GdkWindow *window,
gboolean with_move,
gint x,
gint y,
gint width,
gint height);
void (* set_background) (GdkWindow *window,
const GdkColor *color);
void (* set_back_pixmap) (GdkWindow *window,
GdkPixmap *pixmap);
GdkEventMask (* get_events) (GdkWindow *window);
void (* set_events) (GdkWindow *window,
GdkEventMask event_mask);
gboolean (* reparent) (GdkWindow *window,
GdkWindow *new_parent,
gint x,
gint y);
void (* clear_region) (GdkWindow *window,
GdkRegion *region,
gboolean send_expose);
void (* set_cursor) (GdkWindow *window,
GdkCursor *cursor);
void (* get_geometry) (GdkWindow *window,
gint *x,
gint *y,
gint *width,
gint *height,
gint *depth);
gint (* get_root_coords) (GdkWindow *window,
gint x,
gint y,
gint *root_x,
gint *root_y);
gint (* <API key>) (GdkWindow *window,
gint *x,
gint *y);
gboolean (* get_pointer) (GdkWindow *window,
gint *x,
gint *y,
GdkModifierType *mask);
void (* <API key>) (GdkWindow *window,
const GdkRegion *shape_region,
gint offset_x,
gint offset_y);
void (* <API key>) (GdkWindow *window,
const GdkRegion *shape_region,
gint offset_x,
gint offset_y);
gboolean (* <API key>) (GdkWindow *window,
gboolean use_static);
/* Called before processing updates for a window. This gives the windowing
* layer a chance to save the region for later use in avoiding duplicate
* exposes. The return value indicates whether the function has a saved
* the region; if the result is TRUE, then the windowing layer is responsible
* for destroying the region later.
*/
gboolean (* queue_antiexpose) (GdkWindow *window,
GdkRegion *update_area);
void (* queue_translation) (GdkWindow *window,
GdkGC *gc,
GdkRegion *area,
gint dx,
gint dy);
/* Called to do the windowing system specific part of gdk_window_destroy(),
*
* window: The window being destroyed
* recursing: If TRUE, then this is being called because a parent
* was destroyed. This generally means that the call to the windowing system
* to destroy the window can be omitted, since it will be destroyed as a result
* of the parent being destroyed. Unless @foreign_destroy
*
* foreign_destroy: If TRUE, the window or a parent was destroyed by some external
* agency. The window has already been destroyed and no windowing
* system calls should be made. (This may never happen for some
* windowing systems.)
*/
void (* destroy) (GdkWindow *window,
gboolean recursing,
gboolean foreign_destroy);
void (* <API key>) (GdkWindow *window);
void (* <API key>)(GdkWindow *window,
gboolean enter);
};
/* Interface Functions */
GType <API key> (void) G_GNUC_CONST;
/* private definitions from gdkwindow.h */
struct _GdkWindowRedirect
{
GdkWindowObject *redirected;
GdkDrawable *pixmap;
gint src_x;
gint src_y;
gint dest_x;
gint dest_y;
gint width;
gint height;
GdkRegion *damage;
guint damage_idle;
};
G_END_DECLS
#endif /* <API key> */ |
#ifndef <API key>
#define <API key>
#include <phonon/objectdescription.h>
#include <phonon/backendinterface.h>
#include <QtCore/QList>
#include <QtCore/QPointer>
#include <QtCore/QStringList>
class KUrl;
#ifdef <API key> /* We are building this library */
# define PHONON_FAKE_EXPORT Q_DECL_EXPORT
#else /* We are using this library */
# define PHONON_FAKE_EXPORT Q_DECL_IMPORT
#endif
namespace Phonon
{
namespace Fake
{
class AudioOutput;
class PHONON_FAKE_EXPORT Backend : public QObject, public BackendInterface
{
Q_OBJECT
Q_INTERFACES(Phonon::BackendInterface)
public:
Backend(QObject *parent = 0, const QVariantList & = QVariantList());
virtual ~Backend();
QObject *createObject(BackendInterface::Class, QObject *parent, const QList<QVariant> &args);
bool supportsVideo() const;
bool supportsOSD() const;
bool supportsFourcc(quint32 fourcc) const;
bool supportsSubtitles() const;
QStringList availableMimeTypes() const;
void <API key>();
QList<int> <API key>(<API key> type) const;
QHash<QByteArray, QVariant> <API key>(<API key> type, int index) const;
bool <API key>(QSet<QObject *>);
bool connectNodes(QObject *, QObject *);
bool disconnectNodes(QObject *, QObject *);
bool endConnectionChange(QSet<QObject *>);
Q_SIGNALS:
void <API key>(<API key>);
private:
QStringList <API key>;
QList<QPointer<AudioOutput> > m_audioOutputs;
};
}} // namespace Phonon::Fake
// vim: sw=4 ts=4 tw=80
#endif // <API key> |
# define one name for each executable to be built
NAMES = speck64_96
CPU = -mmcu=msp430f1611
UTILS_PATH = ../utils
# sources files specific to 'first_target'
SRC = speck64_96.c
INCLUDES = -I${UTILS_PATH} -Icommon
-include ${UTILS_PATH}/mspgcc.makefile |
package org.geotools.mbstyle.layer;
import java.awt.Color;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.geotools.mbstyle.MBStyle;
import org.geotools.mbstyle.parse.MBFilter;
import org.geotools.mbstyle.parse.MBFormatException;
import org.geotools.mbstyle.parse.MBObjectParser;
import org.geotools.mbstyle.transform.MBStyleTransformer;
import org.geotools.measure.Units;
import org.geotools.styling.ExternalGraphic;
import org.geotools.styling.FeatureTypeStyle;
import org.geotools.styling.Fill;
import org.geotools.styling.PolygonSymbolizer;
import org.geotools.styling.Rule;
import org.geotools.text.Text;
import org.json.simple.JSONObject;
import org.opengis.filter.expression.Expression;
import org.opengis.style.GraphicFill;
import org.opengis.style.SemanticType;
public class <API key> extends MBLayer {
private final JSONObject paint;
private static final String TYPE = "fill-extrusion";
public enum TranslateAnchor {
/** Translation relative to the map. */
MAP,
/** Translation relative to the viewport. */
VIEWPORT
}
public <API key>(JSONObject json) {
super(json, new MBObjectParser(<API key>.class));
paint = paint();
}
@Override
protected SemanticType defaultSemanticType() {
return SemanticType.POLYGON;
}
/**
* (Optional) Defaults to 1.
*
* <p>The opacity of the entire fill extrusion layer. This is rendered on a per-layer, not
* per-feature, basis, and data-driven styling is not available.
*
* @return The opacity of the fill extrusion layer.
* @throws MBFormatException JSON provided inconsistent with specification
*/
public Number <API key>() throws MBFormatException {
return parse.optional(Double.class, paint, "<API key>", 1.0);
}
/**
* Access <API key> as literal or function expression
*
* @return The opacity of the fill extrusion layer.
* @throws MBFormatException JSON provided inconsistent with specification
*/
public Expression <API key>() throws MBFormatException {
return parse.percentage(paint, "<API key>", 1.0);
}
/**
* (Optional). Defaults to #000000. Disabled by <API key>.
*
* <p>The base color of the extruded fill. The extrusion's surfaces will be shaded differently
* based on this color in combination with the root light settings.
*
* <p>If this color is specified as rgba with an alpha component, the alpha component will be
* ignored; use <API key> to set layer opacity.
*
* @return The color of the extruded fill.
*/
public Color <API key>() throws MBFormatException {
return parse.optional(Color.class, paint, "<API key>", Color.BLACK);
}
/**
* Access <API key> as literal or function expression, defaults to black.
*
* @return The color of the extruded fill.
*/
public Expression fillExtrusionColor() throws MBFormatException {
return parse.color(paint, "<API key>", Color.BLACK);
}
/**
* (Optional) Units in pixels. Defaults to 0,0.
*
* <p>The geometry's offset. Values are [x, y] where negatives indicate left and up (on the flat
* plane), respectively.
*
* @return The geometry's offset, in pixels.
*/
public int[] <API key>() throws MBFormatException {
return parse.array(paint, "<API key>", new int[] {0, 0});
}
/**
* Access <API key> as Point
*
* @return The geometry's offset, in pixels.
*/
public Point <API key>() {
int[] translate = <API key>();
return new Point(translate[0], translate[1]);
}
/**
* (Optional) One of map, viewport. Defaults to map. Requires <API key>.
*
* <p>Controls the translation reference point.
*
* <p>{@link TranslateAnchor#MAP}: The fill extrusion is translated relative to the map.
*
* <p>{@link TranslateAnchor#VIEWPORT}: The fill extrusion is translated relative to the
* viewport.
*
* <p>Defaults to {@link TranslateAnchor#MAP}.
*
* @return The translation reference point
*/
public TranslateAnchor <API key>() {
Object value = paint.get("<API key>");
if (value != null && "viewport".equalsIgnoreCase((String) value)) {
return TranslateAnchor.VIEWPORT;
} else {
return TranslateAnchor.MAP;
}
}
/**
* (Optional) Name of image in sprite to use for drawing images on extruded fills. For seamless
* patterns, image width and height must be a factor of two (2, 4, 8, ..., 512).
*
* @return The name of the image sprite, or null if not defined.
*/
public Expression <API key>() throws MBFormatException {
return parse.string(paint, "<API key>", null);
}
/**
* (Optional) Units in meters. Defaults to 0. The height with which to extrude this layer.
*
* @return The height with which to extrude this layer.
*/
public Number <API key>() throws MBFormatException {
return parse.optional(Double.class, paint, "<API key>", 0.0);
}
/**
* Access <API key> as literal or function expression
*
* @return The height with which to extrude this layer.
* @throws MBFormatException JSON provided inconsistent with specification
*/
public Expression fillExtrusionHeight() throws MBFormatException {
return parse.percentage(paint, "<API key>", 0.0);
}
/**
* (Optional) Units in meters. Defaults to 0. Requires <API key>.
*
* <p>The height with which to extrude the base of this layer. Must be less than or equal to
* <API key>.
*
* @return The height with which to extrude the base of this layer
*/
public Number <API key>() throws MBFormatException {
return parse.optional(Double.class, paint, "fill-extrusion-base", 0.0);
}
/**
* Access fill-extrusion-base as literal or function expression
*
* @return The height with which to extrude the base of this layer
* @throws MBFormatException JSON provided inconsistent with specification
*/
public Expression fillExtrusionBase() throws MBFormatException {
return parse.percentage(paint, "fill-extrusion-base", 0.0);
}
/**
* Transform {@link <API key>} to GeoTools FeatureTypeStyle.
*
* @param styleContext The MBStyle to which this layer belongs, used as a context for things
* like resolving sprite and glyph names to full urls.
*/
@Override
public List<FeatureTypeStyle> transformInternal(MBStyle styleContext) {
List<FeatureTypeStyle> fillExtrusion = new ArrayList<>();
MBStyleTransformer transformer = new MBStyleTransformer(parse);
// from fill pattern or fill color
Fill fill;
// DisplacementImpl displacement = new DisplacementImpl();
// displacement.setDisplacementX(<API key>().doubleValue());
// displacement.setDisplacementY(<API key>().doubleValue());
if (<API key>() != null) {
// Fill graphic (with external graphics)
ExternalGraphic eg =
transformer.<API key>(
<API key>(), styleContext);
GraphicFill gf =
sf.graphicFill(
Arrays.asList(eg), <API key>(), null, null, null, null);
fill = sf.fill(gf, null, null);
} else {
fill = sf.fill(null, fillExtrusionColor(), <API key>());
}
// Create 3 symbolizers one each for shadow, sides, and roof.
PolygonSymbolizer shadowSymbolizer = sf.<API key>();
PolygonSymbolizer sidesSymbolizer = sf.<API key>();
PolygonSymbolizer roofSymbolizer = sf.<API key>();
shadowSymbolizer.setName("shadow");
shadowSymbolizer.setGeometry(
ff.function(
"offset",
ff.property((String) null),
ff.literal(0.005),
ff.literal(-0.005)));
shadowSymbolizer.setDescription(sf.description(Text.text("fill"), null));
shadowSymbolizer.setUnitOfMeasure(Units.PIXEL);
shadowSymbolizer.setStroke(null);
shadowSymbolizer.setFill(fill);
shadowSymbolizer.setDisplacement(null);
shadowSymbolizer.<API key>(ff.literal(0));
sidesSymbolizer.setName("sides");
sidesSymbolizer.setGeometry(
ff.function(
"isometric",
ff.property((String) null),
ff.literal(fillExtrusionHeight())));
sidesSymbolizer.setDescription(sf.description(Text.text("fill"), null));
sidesSymbolizer.setUnitOfMeasure(Units.PIXEL);
sidesSymbolizer.setStroke(null);
sidesSymbolizer.setFill(fill);
sidesSymbolizer.setDisplacement(null);
sidesSymbolizer.<API key>(ff.literal(0));
roofSymbolizer.setName("roof");
roofSymbolizer.setGeometry(
ff.function(
"offset",
ff.property((String) null),
ff.literal(fillExtrusionBase()),
ff.literal(fillExtrusionHeight())));
roofSymbolizer.setDescription(sf.description(Text.text("fill"), null));
roofSymbolizer.setUnitOfMeasure(Units.PIXEL);
roofSymbolizer.setStroke(null);
roofSymbolizer.setFill(fill);
roofSymbolizer.setDisplacement(null);
roofSymbolizer.<API key>(ff.literal(0));
// PolygonSymbolizer shadowSymbolizer = sf.polygonSymbolizer("shadow",
// ff.function("offset", ff.property("the_geom"), ff.literal(0.005),
// ff.literal(-0.005)),
// sf.description(Text.text("fill"),null),
// Units.PIXEL,
// null,
// fill,
// null,
// ff.literal(0));
// PolygonSymbolizer sidesSymbolizer = sf.polygonSymbolizer("sides",
// ff.function("isometric", ff.property("the_geom"),
// ff.literal(fillExtrusionHeight())),
// sf.description(Text.text("fill"),null),
// Units.PIXEL,
// null,
// fill,
// null,
// ff.literal(0));
// PolygonSymbolizer roofSymbolizer = sf.polygonSymbolizer("shadow",
// ff.function("offset", ff.property("the_geom"),
// ff.literal(fillExtrusionBase()), ff.literal(fillExtrusionHeight())),
// sf.description(Text.text("fill"),null),
// Units.PIXEL,
// null,
// fill,
// null,
// ff.literal(0));
MBFilter filter = getFilter();
// Each symbolizer needs a rule.
Rule shadowRule =
sf.rule(
getId(),
null,
null,
0.0,
Double.POSITIVE_INFINITY,
Arrays.asList(shadowSymbolizer),
filter.filter());
Rule sidesRule =
sf.rule(
getId(),
null,
null,
0.0,
Double.POSITIVE_INFINITY,
Arrays.asList(sidesSymbolizer),
filter.filter());
Rule roofRule =
sf.rule(
getId(),
null,
null,
0.0,
Double.POSITIVE_INFINITY,
Arrays.asList(roofSymbolizer),
filter.filter());
// Finally we create the FeatureTypeStyles for the extrusion.
FeatureTypeStyle shadow =
sf.featureTypeStyle(
getId(),
sf.description(
Text.text("MBStyle " + getId()),
Text.text("Generated for " + getSourceLayer())),
null, // (unused)
Collections.emptySet(),
filter.<API key>(),
Arrays.asList(shadowRule));
FeatureTypeStyle sides =
sf.featureTypeStyle(
getId(),
sf.description(
Text.text("MBStyle " + getId()),
Text.text("Generated for " + getSourceLayer())),
null, // (unused)
Collections.emptySet(),
filter.<API key>(),
Arrays.asList(sidesRule));
FeatureTypeStyle roof =
sf.featureTypeStyle(
getId(),
sf.description(
Text.text("MBStyle " + getId()),
Text.text("Generated for " + getSourceLayer())),
null, // (unused)
Collections.emptySet(),
filter.<API key>(),
Arrays.asList(roofRule));
fillExtrusion.add(shadow);
fillExtrusion.add(sides);
fillExtrusion.add(roof);
return fillExtrusion;
}
/**
* Rendering type of this layer.
*
* @return {@link #TYPE}
*/
@Override
public String getType() {
return TYPE;
}
} |
/* <API key> Styles */
.swat-table-view td.<API key> {
padding: 0;
}
.swat-table-view th.<API key> {
padding-left: 36px;
}
td.<API key> a.<API key>:link,
td.<API key> a.<API key>:visited {
display: block;
border: 1px solid transparent;
}
td.<API key> a.<API key>:hover {
background: #f6f2ea url(../images/<API key>.png) top repeat-x;
border: 1px solid #f0eade;
}
td.<API key> a.<API key>:active {
background: #f3efe5;
}
span.<API key> {
display: block;
padding: 0.4em 0.2em 0.4em 36px;
background-image: url(../images/<API key>.png);
background-position: 4px 50%;
background-repeat: no-repeat;
}
a.<API key> span.<API key> {
background-image: url(../images/<API key>.png);
}
a.<API key> span.<API key> {
background-image: url(../images/<API key>.png);
}
a.<API key> span.<API key> {
background-image: url(../images/admin-edit.png);
}
a.<API key> span.<API key> {
background-image: url(../images/<API key>.png);
}
a.<API key> span.<API key> {
background-image: url(../images/admin-folder.png);
}
a.<API key> span.<API key> {
background-image: url(../images/admin-person.png);
}
a.<API key> span.<API key> {
background-image: url(../images/admin-product.png);
} |
#ifndef AUTOTZD_TZDATA_H
#define AUTOTZD_TZDATA_H
#include <string>
#include <set>
class olson ;
namespace tzdata
{
enum zone_type { All_Zones, Main_Zones, Real_Zones } ;
std::string <API key>(const std::string &mcc) ;
int by_country(const std::string &alpha2, enum zone_type type, std::set<olson*> &out) ;
olson* country_default(const std::string &alpha2) ;
olson* device_default() ;
int filter(const std::set<olson*> &in, time_t moment, int offset, int dst, std::set<olson*> &out) ;
bool <API key>(const std::string &alpha2) ;
std::string set_str(const std::set<olson*> &) ;
void init(const std::string &default_tz) ;
}
#endif /* AUTOTZD_TZDATA_H */ |
#if __GNUC__ >= 4 || __GNUC_MINOR__ >=3
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
#include "OSGColladaInstInfo.h"
#ifdef OSG_WITH_COLLADA
OSG_BEGIN_NAMESPACE
ColladaInstInfo::ColladaInstInfo(ColladaElement *colInstParent,
<API key> *colInst )
: Inherited ( )
, _colInstParent(colInstParent)
, _colInst (colInst )
{
}
ColladaInstInfo::~ColladaInstInfo(void)
{
}
OSG_END_NAMESPACE
#endif // OSG_WITH_COLLADA |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_CN" sourcelanguage="en" version="2.1">
<context>
<name>QObject</name>
<message>
<location filename="../src/qtwrapper/callmanager_wrap.h" line="393"/>
<source>Me</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="61"/>
<source>Hold</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="63"/>
<source>Talking</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="65"/>
<source>ERROR</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="67"/>
<source>Incoming</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="69"/>
<source>Calling</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="71"/>
<location filename="../src/chatview.cpp" line="72"/>
<source>Connecting</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="73"/>
<source>Searching</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="75"/>
<source>Inactive</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="77"/>
<location filename="../src/api/call.h" line="83"/>
<location filename="../src/chatview.cpp" line="79"/>
<source>Finished</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="79"/>
<source>Timeout</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="81"/>
<source>Peer busy</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/call.h" line="85"/>
<source>Communication established</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/interaction.h" line="218"/>
<location filename="../src/authority/storagehelper.cpp" line="135"/>
<location filename="../src/authority/storagehelper.cpp" line="935"/>
<source>Invitation received</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/interaction.h" line="222"/>
<source>Contact left conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../src/api/interaction.h" line="216"/>
<location filename="../src/authority/storagehelper.cpp" line="132"/>
<location filename="../src/authority/storagehelper.cpp" line="933"/>
<source>Contact added</source>
<translation></translation>
</message>
<message>
<location filename="../src/authority/storagehelper.cpp" line="109"/>
<location filename="../src/authority/storagehelper.cpp" line="115"/>
<location filename="../src/authority/storagehelper.cpp" line="931"/>
<source>Outgoing call</source>
<translation></translation>
</message>
<message>
<location filename="../src/authority/storagehelper.cpp" line="111"/>
<location filename="../src/authority/storagehelper.cpp" line="121"/>
<source>Incoming call</source>
<translation></translation>
</message>
<message>
<location filename="../src/authority/storagehelper.cpp" line="117"/>
<location filename="../src/authority/storagehelper.cpp" line="929"/>
<source>Missed outgoing call</source>
<translation></translation>
</message>
<message>
<location filename="../src/authority/storagehelper.cpp" line="123"/>
<source>Missed incoming call</source>
<translation></translation>
</message>
<message>
<location filename="../src/api/interaction.h" line="220"/>
<location filename="../src/authority/storagehelper.cpp" line="137"/>
<location filename="../src/authority/storagehelper.cpp" line="937"/>
<source>Invitation accepted</source>
<translation></translation>
</message>
<message>
<location filename="../src/avmodel.cpp" line="339"/>
<location filename="../src/avmodel.cpp" line="358"/>
<source>default</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="55"/>
<source>Null</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="56"/>
<source>Trying</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="57"/>
<source>Ringing</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="58"/>
<source>Being Forwarded</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="59"/>
<source>Queued</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="60"/>
<source>Progress</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="61"/>
<source>OK</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="73"/>
<location filename="../src/newcallmodel.cpp" line="62"/>
<source>Accepted</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="63"/>
<source>Multiple Choices</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="64"/>
<source>Moved Permanently</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="65"/>
<source>Moved Temporarily</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="66"/>
<source>Use Proxy</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="67"/>
<source>Alternative Service</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="68"/>
<source>Bad Request</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="69"/>
<source>Unauthorized</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="70"/>
<source>Payment Required</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="71"/>
<source>Forbidden</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="72"/>
<source>Not Found</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="73"/>
<source>Method Not Allowed</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="74"/>
<location filename="../src/newcallmodel.cpp" line="94"/>
<source>Not Acceptable</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="75"/>
<source>Proxy Authentication Required</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="76"/>
<source>Request Timeout</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="77"/>
<source>Gone</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="78"/>
<source>Request Entity Too Large</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="79"/>
<source>Request URI Too Long</source>
<translation> URI </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="80"/>
<source>Unsupported Media Type</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="81"/>
<source>Unsupported URI Scheme</source>
<translation> URI </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="82"/>
<source>Bad Extension</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="83"/>
<source>Extension Required</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="84"/>
<source>Session Timer Too Small</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="85"/>
<source>Interval Too Brief</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="86"/>
<source>Temporarily Unavailable</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="87"/>
<source>Call TSX Does Not Exist</source>
<translation>Call TSX </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="88"/>
<source>Loop Detected</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="89"/>
<source>Too Many Hops</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="90"/>
<source>Address Incomplete</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="91"/>
<source>Ambiguous</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="92"/>
<source>Busy</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="93"/>
<source>Request Terminated</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="95"/>
<source>Bad Event</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="96"/>
<source>Request Updated</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="97"/>
<source>Request Pending</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="98"/>
<source>Undecipherable</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="99"/>
<source>Internal Server Error</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="100"/>
<source>Not Implemented</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="101"/>
<source>Bad Gateway</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="102"/>
<source>Service Unavailable</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="103"/>
<source>Server Timeout</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="104"/>
<source>Version Not Supported</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="105"/>
<source>Message Too Large</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="106"/>
<source>Precondition Failure</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="107"/>
<source>Busy Everywhere</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="108"/>
<source>Call Refused</source>
<translation></translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="109"/>
<source>Does Not Exist Anywhere</source>
<translation> </translation>
</message>
<message>
<location filename="../src/newcallmodel.cpp" line="110"/>
<source>Not Acceptable Anywhere</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="30"/>
<source>Hide chat view</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="31"/>
<source>Place video call</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="32"/>
<source>Show available plugins</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="33"/>
<source>Place audio call</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="34"/>
<source>Add to conversations</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="35"/>
<source>Unban contact</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="36"/>
<source>Send</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="37"/>
<source>Options</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="38"/>
<source>Jump to latest</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="39"/>
<source>Send file</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="40"/>
<source>Add emoji</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="41"/>
<source>Leave video message</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="42"/>
<source>Leave audio message</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="44"/>
<source>Copy to downloads</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../src/chatview.cpp" line="45"/>
<source>Write to {0}</source>
<translation> {0}</translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="50"/>
<source>has sent you a conversation request.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../src/chatview.cpp" line="52"/>
<source>Hello, do you want to join the conversation?</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../src/chatview.cpp" line="54"/>
<source>You have accepted the conversation request.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../src/chatview.cpp" line="56"/>
<source>We are waiting for another device to synchronize the conversation.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../src/chatview.cpp" line="67"/>
<source>Accept</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="68"/>
<source>Refuse</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="71"/>
<source>Unable to make contact</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="76"/>
<source>Waiting for contact</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="77"/>
<source>Incoming transfer</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="78"/>
<source>Timed out waiting for contact</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="43"/>
<source>Block</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="47"/>
<source>Note: an interaction will create a new contact.</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="48"/>
<source>is not in your contacts</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="58"/>
<source>Note: you can automatically accept this invitation by sending a message.</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="59"/>
<source>{0} days ago</source>
<translation>{0} </translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="60"/>
<source>{0} hours ago</source>
<translation>{0} </translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="62"/>
<source>{0} minutes ago</source>
<translation>{0} </translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="74"/>
<source>Canceled</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="75"/>
<source>Ongoing</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="59"/>
<source>%d days ago</source>
<translation>%d</translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="60"/>
<source>%d hours ago</source>
<translation>%d</translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="62"/>
<source>%d minutes ago</source>
<translation>%d</translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="63"/>
<source>one day ago</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="64"/>
<source>one hour ago</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="65"/>
<source>just now</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="66"/>
<source>Failure</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="69"/>
<source>Delete</source>
<translation></translation>
</message>
<message>
<location filename="../src/chatview.cpp" line="70"/>
<source>Retry</source>
<translation></translation>
</message>
</context>
<context>
<name>lrc::ContactModelPimpl</name>
<message>
<location filename="../src/contactmodel.cpp" line="474"/>
<source>Searching…</source>
<translation>…</translation>
</message>
<message>
<location filename="../src/contactmodel.cpp" line="993"/>
<source>Invalid ID</source>
<translation> ID</translation>
</message>
<message>
<location filename="../src/contactmodel.cpp" line="996"/>
<source>Username not found</source>
<translation></translation>
</message>
<message>
<location filename="../src/contactmodel.cpp" line="999"/>
<source>Couldn't lookup…</source>
<translation>...</translation>
</message>
</context>
<context>
<name>lrc::api::ContactModel</name>
<message>
<location filename="../src/contactmodel.cpp" line="435"/>
<source>Bad URI scheme</source>
<translation> URI </translation>
</message>
</context>
</TS> |
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/csp_error.h>
#include <csp/arch/csp_thread.h>
#include <csp/arch/csp_queue.h>
#include <csp/arch/csp_semaphore.h>
#include <csp/arch/csp_malloc.h>
#include <csp/arch/csp_time.h>
#include "csp_conn.h"
#include "transport/csp_transport.h"
/* Static connection pool */
static csp_conn_t arr_conn[CSP_CONN_MAX];
/* Connection pool lock */
static <API key> conn_lock;
/* Source port */
static uint8_t sport;
/* Source port lock */
static <API key> sport_lock;
void <API key>(void) {
#ifdef CSP_USE_RDP
int i;
for (i = 0; i < CSP_CONN_MAX; i++)
if (arr_conn[i].state == CONN_OPEN)
if (arr_conn[i].idin.flags & CSP_FRDP)
<API key>(&arr_conn[i]);
#endif
}
int csp_conn_get_rxq(int prio) {
#ifdef CSP_USE_QOS
return prio;
#else
return 0;
#endif
}
int csp_conn_lock(csp_conn_t * conn, uint32_t timeout) {
if (csp_mutex_lock(&conn->lock, timeout) != CSP_MUTEX_OK)
return CSP_ERR_TIMEDOUT;
return CSP_ERR_NONE;
}
int csp_conn_unlock(csp_conn_t * conn) {
csp_mutex_unlock(&conn->lock);
return CSP_ERR_NONE;
}
int <API key>(csp_conn_t * conn, csp_packet_t * packet) {
if (!conn)
return CSP_ERR_INVAL;
int rxq;
if (packet != NULL) {
rxq = csp_conn_get_rxq(packet->id.pri);
} else {
rxq = CSP_RX_QUEUES - 1;
}
if (csp_queue_enqueue(conn->rx_queue[rxq], &packet, 0) != CSP_QUEUE_OK) {
csp_log_error("RX queue %p full with %u items", conn->rx_queue[rxq], csp_queue_size(conn->rx_queue[rxq]));
return CSP_ERR_NOMEM;
}
#ifdef CSP_USE_QOS
int event = 0;
if (csp_queue_enqueue(conn->rx_event, &event, 0) != CSP_QUEUE_OK) {
csp_log_error("QOS event queue full");
return CSP_ERR_NOMEM;
}
#endif
return CSP_ERR_NONE;
}
int csp_conn_init(void) {
/* Initialize source port */
srand(csp_get_ms());
sport = (rand() % (CSP_ID_PORT_MAX - CSP_MAX_BIND_PORT)) + (CSP_MAX_BIND_PORT + 1);
if (csp_bin_sem_create(&sport_lock) != CSP_SEMAPHORE_OK) {
csp_log_error("No more memory for sport semaphore");
return CSP_ERR_NOMEM;
}
int i, prio;
for (i = 0; i < CSP_CONN_MAX; i++) {
for (prio = 0; prio < CSP_RX_QUEUES; prio++)
arr_conn[i].rx_queue[prio] = csp_queue_create(CSP_RX_QUEUE_LENGTH, sizeof(csp_packet_t *));
#ifdef CSP_USE_QOS
arr_conn[i].rx_event = csp_queue_create(<API key>, sizeof(int));
#endif
arr_conn[i].state = CONN_CLOSED;
if (csp_mutex_create(&arr_conn[i].lock) != CSP_MUTEX_OK) {
csp_log_error("Failed to create connection lock");
return CSP_ERR_NOMEM;
}
#ifdef CSP_USE_RDP
if (csp_rdp_allocate(&arr_conn[i]) != CSP_ERR_NONE) {
csp_log_error("Failed to create queues for RDP in csp_conn_init");
return CSP_ERR_NOMEM;
}
#endif
}
if (csp_bin_sem_create(&conn_lock) != CSP_SEMAPHORE_OK) {
csp_log_error("No more memory for conn semaphore");
return CSP_ERR_NOMEM;
}
return CSP_ERR_NONE;
}
csp_conn_t * csp_conn_find(uint32_t id, uint32_t mask) {
/* Search for matching connection */
int i;
csp_conn_t * conn;
for (i = 0; i < CSP_CONN_MAX; i++) {
conn = &arr_conn[i];
if ((conn->state != CONN_CLOSED) && (conn->type == CONN_CLIENT) && (conn->idin.ext & mask) == (id & mask))
return conn;
}
return NULL;
}
int <API key>(csp_conn_t * conn) {
csp_packet_t * packet;
int prio;
/* Flush packet queues */
for (prio = 0; prio < CSP_RX_QUEUES; prio++) {
while (csp_queue_dequeue(conn->rx_queue[prio], &packet, 0) == CSP_QUEUE_OK)
if (packet != NULL)
csp_buffer_free(packet);
}
/* Flush event queue */
#ifdef CSP_USE_QOS
int event;
while (csp_queue_dequeue(conn->rx_event, &event, 0) == CSP_QUEUE_OK);
#endif
return CSP_ERR_NONE;
}
csp_conn_t * csp_conn_allocate(csp_conn_type_t type) {
int i, j;
static uint8_t csp_conn_last_given = 0;
csp_conn_t * conn;
if (csp_bin_sem_wait(&conn_lock, 100) != CSP_SEMAPHORE_OK) {
csp_log_error("Failed to lock conn array");
return NULL;
}
/* Search for free connection */
i = csp_conn_last_given;
i = (i + 1) % CSP_CONN_MAX;
for (j = 0; j < CSP_CONN_MAX; j++) {
conn = &arr_conn[i];
if (conn->state == CONN_CLOSED)
break;
i = (i + 1) % CSP_CONN_MAX;
}
if (conn->state == CONN_OPEN) {
csp_log_error("No more free connections");
csp_bin_sem_post(&conn_lock);
return NULL;
}
conn->state = CONN_OPEN;
conn->socket = NULL;
conn->type = type;
csp_conn_last_given = i;
csp_bin_sem_post(&conn_lock);
return conn;
}
csp_conn_t * csp_conn_new(csp_id_t idin, csp_id_t idout) {
/* Allocate connection structure */
csp_conn_t * conn = csp_conn_allocate(CONN_CLIENT);
if (conn) {
/* No lock is needed here, because nobody else *
* has a reference to this connection yet. */
conn->idin.ext = idin.ext;
conn->idout.ext = idout.ext;
conn->timestamp = csp_get_ms();
/* Ensure connection queue is empty */
<API key>(conn);
}
return conn;
}
int csp_close(csp_conn_t * conn) {
if (conn == NULL) {
csp_log_error("NULL Pointer given to csp_close");
return CSP_ERR_INVAL;
}
if (conn->state == CONN_CLOSED) {
csp_log_protocol("Conn already closed");
return CSP_ERR_NONE;
}
#ifdef CSP_USE_RDP
/* Ensure RDP knows this connection is closing */
if (conn->idin.flags & CSP_FRDP || conn->idout.flags & CSP_FRDP)
if (csp_rdp_close(conn) == CSP_ERR_AGAIN)
return CSP_ERR_NONE;
#endif
/* Lock connection array while closing connection */
if (csp_bin_sem_wait(&conn_lock, 100) != CSP_SEMAPHORE_OK) {
csp_log_error("Failed to lock conn array");
return CSP_ERR_TIMEDOUT;
}
/* Set to closed */
conn->state = CONN_CLOSED;
/* Ensure connection queue is empty */
<API key>(conn);
/* Reset RDP state */
#ifdef CSP_USE_RDP
if (conn->idin.flags & CSP_FRDP)
csp_rdp_flush_all(conn);
#endif
/* Unlock connection array */
csp_bin_sem_post(&conn_lock);
return CSP_ERR_NONE;
}
csp_conn_t * csp_connect(uint8_t prio, uint8_t dest, uint8_t dport, uint32_t timeout, uint32_t opts) {
/* Force options on all connections */
opts |= CSP_CONNECTION_SO;
/* Generate identifier */
csp_id_t incoming_id, outgoing_id;
incoming_id.pri = prio;
incoming_id.dst = csp_get_address();
incoming_id.src = dest;
incoming_id.sport = dport;
incoming_id.flags = 0;
outgoing_id.pri = prio;
outgoing_id.dst = dest;
outgoing_id.src = csp_get_address();
outgoing_id.dport = dport;
outgoing_id.flags = 0;
/* Set connection options */
if (opts & CSP_O_RDP) {
#ifdef CSP_USE_RDP
incoming_id.flags |= CSP_FRDP;
outgoing_id.flags |= CSP_FRDP;
#else
csp_log_error("Attempt to create RDP connection, but CSP was compiled without RDP support");
return NULL;
#endif
}
if (opts & CSP_O_HMAC) {
#ifdef CSP_USE_HMAC
outgoing_id.flags |= CSP_FHMAC;
incoming_id.flags |= CSP_FHMAC;
#else
csp_log_error("Attempt to create HMAC authenticated connection, but CSP was compiled without HMAC support");
return NULL;
#endif
}
if (opts & CSP_O_XTEA) {
#ifdef CSP_USE_XTEA
outgoing_id.flags |= CSP_FXTEA;
incoming_id.flags |= CSP_FXTEA;
#else
csp_log_error("Attempt to create XTEA encrypted connection, but CSP was compiled without XTEA support");
return NULL;
#endif
}
if (opts & CSP_O_CRC32) {
#ifdef CSP_USE_CRC32
outgoing_id.flags |= CSP_FCRC32;
incoming_id.flags |= CSP_FCRC32;
#else
csp_log_error("Attempt to create CRC32 validated connection, but CSP was compiled without CRC32 support");
return NULL;
#endif
}
/* Find an unused ephemeral port */
csp_conn_t * conn;
/* Wait for sport lock */
if (csp_bin_sem_wait(&sport_lock, 1000) != CSP_SEMAPHORE_OK)
return NULL;
uint8_t start = sport;
while (++sport != start) {
if (sport > CSP_ID_PORT_MAX)
sport = CSP_MAX_BIND_PORT + 1;
outgoing_id.sport = sport;
incoming_id.dport = sport;
/* Match on destination port of _incoming_ identifier */
conn = csp_conn_find(incoming_id.ext, CSP_ID_DPORT_MASK);
/* Break if we found an unused ephemeral port */
if (conn == NULL)
break;
}
/* Post sport lock */
csp_bin_sem_post(&sport_lock);
/* If no available ephemeral port was found */
if (sport == start)
return NULL;
/* Get storage for new connection */
conn = csp_conn_new(incoming_id, outgoing_id);
if (conn == NULL)
return NULL;
/* Set connection options */
conn->opts = opts;
#ifdef CSP_USE_RDP
/* Call Transport Layer connect */
if (outgoing_id.flags & CSP_FRDP) {
/* If the transport layer has failed to connect
* deallocate connection structure again and return NULL */
if (csp_rdp_connect(conn, timeout) != CSP_ERR_NONE) {
csp_close(conn);
return NULL;
}
}
#endif
/* We have a successful connection */
return conn;
}
inline int csp_conn_dport(csp_conn_t * conn) {
return conn->idin.dport;
}
inline int csp_conn_sport(csp_conn_t * conn) {
return conn->idin.sport;
}
inline int csp_conn_dst(csp_conn_t * conn) {
return conn->idin.dst;
}
inline int csp_conn_src(csp_conn_t * conn) {
return conn->idin.src;
}
inline int csp_conn_flags(csp_conn_t * conn) {
return conn->idin.flags;
}
#ifdef CSP_DEBUG
void <API key>(void) {
int i;
csp_conn_t * conn;
for (i = 0; i < CSP_CONN_MAX; i++) {
conn = &arr_conn[i];
printf("[%02u %p] S:%u, %u -> %u, %u -> %u, sock: %p\n",
i, conn, conn->state, conn->idin.src, conn->idin.dst,
conn->idin.dport, conn->idin.sport, conn->socket);
#ifdef CSP_USE_RDP
if (conn->idin.flags & CSP_FRDP)
csp_rdp_conn_print(conn);
#endif
}
}
int <API key>(char * str_buf, int str_size) {
int i, start = 0;
csp_conn_t * conn;
char buf[100];
/* Display up to 10 connections */
if (CSP_CONN_MAX - 10 > 0)
start = CSP_CONN_MAX - 10;
for (i = start; i < CSP_CONN_MAX; i++) {
conn = &arr_conn[i];
snprintf(buf, sizeof(buf), "[%02u %p] S:%u, %u -> %u, %u -> %u, sock: %p\n",
i, conn, conn->state, conn->idin.src, conn->idin.dst,
conn->idin.dport, conn->idin.sport, conn->socket);
strncat(str_buf, buf, str_size);
if ((str_size -= strlen(buf)) <= 0)
break;
}
return CSP_ERR_NONE;
}
#endif |
#ifndef <API key>
#define <API key>
#include <Gui/<API key>.h>
#include <Gui/<API key>.h>
#include <App/<API key>.h>
#include <App/DynamicProperty.h>
class SoSensor;
class SoDragger;
class SoNode;
namespace Gui {
class SoFCSelection;
class SoFCBoundingBox;
class GuiExport <API key>
{
public:
constructor.
<API key>(<API key>*);
destructor.
~<API key>();
// Returns the icon
QIcon getIcon() const;
std::vector<App::DocumentObject*> claimChildren() const;
std::string getElement(const SoDetail *det) const;
std::vector<Base::Vector3d> getSelectionShape(const char* Element) const;
bool setEdit(int ModNum);
bool unsetEdit(int ModNum);
/** @name Update data methods*/
void attach(App::DocumentObject *pcObject);
void updateData(const App::Property*);
void onChanged(const App::Property* prop);
void startRestoring();
void finishRestoring();
/** @name Display methods */
get the default display mode
const char* <API key>() const;
returns a list of all possible modes
std::vector<std::string> getDisplayModes(void) const;
set the display mode
std::string setDisplayMode(const char* ModeName);
private:
<API key>* object;
};
template <class ViewProviderT>
class <API key> : public ViewProviderT
{
PROPERTY_HEADER(Gui::<API key><ViewProviderT>);
public:
constructor.
<API key>() : _attached(false) {
ADD_PROPERTY(Proxy,(Py::Object()));
imp = new <API key>(this);
props = new App::DynamicProperty(this);
}
destructor.
virtual ~<API key>() {
delete imp;
delete props;
}
// Returns the icon
QIcon getIcon() const {
QIcon icon = imp->getIcon();
if (icon.isNull())
icon = ViewProviderT::getIcon();
return icon;
}
std::vector<App::DocumentObject*> claimChildren() const {
return imp->claimChildren();
}
/** @name Nodes */
virtual SoSeparator* getRoot() {
return ViewProviderT::getRoot();
}
virtual SoSeparator* getFrontRoot() const {
return ViewProviderT::getFrontRoot();
}
// returns the root node of the Provider (3D)
virtual SoSeparator* getBackRoot() const {
return ViewProviderT::getBackRoot();
}
/** @name Selection handling */
virtual bool <API key>() const {
return ViewProviderT::<API key>();
}
virtual std::string getElement(const SoDetail *det) const {
return ViewProviderT::getElement(det);
}
virtual std::vector<Base::Vector3d> getSelectionShape(const char* Element) const {
return ViewProviderT::getSelectionShape(Element);
};
/** @name Update data methods*/
virtual void attach(App::DocumentObject *obj) {
// delay loading of the actual attach() method because the Python
// view provider class is not attached yet
ViewProviderT::pcObject = obj;
}
virtual void updateData(const App::Property* prop) {
imp->updateData(prop);
ViewProviderT::updateData(prop);
}
virtual void getTaskViewContent(std::vector<Gui::TaskView::TaskContent*>& c) const {
ViewProviderT::getTaskViewContent(c);
}
/** @name Restoring view provider from document load */
virtual void startRestoring() {
imp->startRestoring();
}
virtual void finishRestoring() {
imp->finishRestoring();
}
/** @name Display methods */
get the default display mode
virtual const char* <API key>() const {
return imp-><API key>();
}
returns a list of all possible modes
virtual std::vector<std::string> getDisplayModes(void) const {
std::vector<std::string> modes = ViewProviderT::getDisplayModes();
std::vector<std::string> more_modes = imp->getDisplayModes();
modes.insert(modes.end(), more_modes.begin(), more_modes.end());
return modes;
}
set the display mode
virtual void setDisplayMode(const char* ModeName) {
std::string mask = imp->setDisplayMode(ModeName);
ViewProviderT::setDisplayMaskMode(mask.c_str());
ViewProviderT::setDisplayMode(ModeName);
}
/** @name Access properties */
App::Property* addDynamicProperty(
const char* type, const char* name=0,
const char* group=0, const char* doc=0,
short attr=0, bool ro=false, bool hidden=false) {
return props->addDynamicProperty(type, name, group, doc, attr, ro, hidden);
}
std::vector<std::string> <API key>() const {
return props-><API key>();
}
App::Property *<API key>(const char* name) const {
return props-><API key>(name);
}
virtual void <API key>(const App::PropertyContainer* cont) {
return props-><API key>(cont);
}
get all properties of the class (including parent)
virtual void getPropertyMap(std::map<std::string,App::Property*> &Map) const {
return props->getPropertyMap(Map);
}
find a property by its name
virtual App::Property *getPropertyByName(const char* name) const {
return props->getPropertyByName(name);
}
get the name of a property
virtual const char* getName(const App::Property* prop) const {
return props->getName(prop);
}
/** @name Property attributes */
get the Type of a Property
short getPropertyType(const App::Property* prop) const {
return props->getPropertyType(prop);
}
get the Type of a named Property
short getPropertyType(const char *name) const {
return props->getPropertyType(name);
}
get the Group of a Property
const char* getPropertyGroup(const App::Property* prop) const {
return props->getPropertyGroup(prop);
}
get the Group of a named Property
const char* getPropertyGroup(const char *name) const {
return props->getPropertyGroup(name);
}
get the Group of a Property
const char* <API key>(const App::Property* prop) const {
return props-><API key>(prop);
}
get the Group of a named Property
const char* <API key>(const char *name) const {
return props-><API key>(name);
}
check if the property is read-only
bool isReadOnly(const App::Property* prop) const {
return props->isReadOnly(prop);
}
check if the nameed property is read-only
bool isReadOnly(const char *name) const {
return props->isReadOnly(name);
}
check if the property is hidden
bool isHidden(const App::Property* prop) const {
return props->isHidden(prop);
}
check if the named property is hidden
bool isHidden(const char *name) const {
return props->isHidden(name);
}
/** @name Property serialization */
void Save (Base::Writer &writer) const {
props->Save(writer);
}
void Restore(Base::XMLReader &reader) {
props->Restore(reader);
}
PyObject* getPyObject() {
if (!ViewProviderT::pyViewObject)
ViewProviderT::pyViewObject = new <API key>(this);
ViewProviderT::pyViewObject->IncRef();
return ViewProviderT::pyViewObject;
}
protected:
virtual void onChanged(const App::Property* prop) {
if (prop == &Proxy) {
if (ViewProviderT::pcObject && !Proxy.getValue().is(Py::_None())) {
if (!_attached) {
_attached = true;
imp->attach(ViewProviderT::pcObject);
ViewProviderT::attach(ViewProviderT::pcObject);
// needed to load the right display mode after they're known now
ViewProviderT::DisplayMode.touch();
}
ViewProviderT::updateView();
}
}
else {
imp->onChanged(prop);
ViewProviderT::onChanged(prop);
}
}
is called by the document when the provider goes in edit mode
virtual bool setEdit(int ModNum)
{
bool ok = imp->setEdit(ModNum);
if (!ok) ok = ViewProviderT::setEdit(ModNum);
return ok;
}
is called when you loose the edit mode
virtual void unsetEdit(int ModNum)
{
bool ok = imp->unsetEdit(ModNum);
if (!ok) ViewProviderT::unsetEdit(ModNum);
}
private:
<API key>* imp;
App::DynamicProperty *props;
App::<API key> Proxy;
bool _attached;
};
// Special Feature-Python classes
typedef <API key><<API key>> <API key>;
typedef <API key><<API key>> <API key>;
} // namespace Gui
#endif // <API key> |
package org.pentaho.reporting.libraries.resourceloader;
import java.io.InputStream;
/**
* A resource data object encapsulates the raw data of an resource at a given point in the past.
* <p/>
* Any change to the resource increases the version number. Version numbers are not needed to be checked regulary, but
* must be checked on each call to 'getVersion()'.
* <p/>
* This definitly does *not* solve the problem of concurrent modifications; if you need to be sure that the resource has
* not been altered between the last call to 'getVersion' and 'getResource..' external locking mechanism have to be
* implemented.
*
* @author Thomas Morgner
*/
public interface ResourceData {
public static final String CONTENT_LENGTH = "content-length";
public static final String CONTENT_TYPE = "content-type";
public static final String FILENAME = "filename";
public InputStream getResourceAsStream( ResourceManager caller ) throws <API key>;
/**
* This is dangerous, especially if the resource is large.
*
* @param caller
* @return
* @throws <API key>
*/
public byte[] getResource( ResourceManager caller ) throws <API key>;
/**
* Tries to read data into the given byte-array.
*
* @param caller
* @param target
* @param offset
* @param length
* @return the number of bytes read or -1 if no more data can be read.
* @throws <API key>
*/
public int getResource( ResourceManager caller, byte[] target, long offset, int length )
throws <API key>;
public long getLength();
public Object getAttribute( String key );
public ResourceKey getKey();
public long getVersion( ResourceManager caller ) throws <API key>;
} |
package org.opencms.workplace.list;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.tools.A_CmsHtmlIconButton;
import org.opencms.workplace.tools.<API key>;
/**
* Implementation of a list item selection action where to define name and the column with the value.<p>
*
* @since 6.7.2
*/
public class <API key> extends <API key> {
/** The attributes to set at the input field. */
private String m_attributes;
/** The name of the column where to find the value. */
private String m_column;
/** The name of the input field. */
private String m_fieldName;
/**
* Default Constructor.<p>
*
* @param id the unique id
* @param columnValue the name of the column used for the value
*/
public <API key>(String id, String columnValue) {
this(id, columnValue, null);
}
/**
* Default Constructor.<p>
*
* @param id the unique id
* @param name the name of the input field
* @param columnValue the name of the column used for the value
*/
public <API key>(String id, String name, String columnValue) {
super(id, null);
m_fieldName = name;
m_column = columnValue;
}
/**
* @see org.opencms.workplace.tools.I_CmsHtmlIconButton#buttonHtml(CmsWorkplace)
*/
@Override
public String buttonHtml(CmsWorkplace wp) {
if (!isVisible()) {
return "";
}
String value = getItem().getId();
if (CmsStringUtil.<API key>(m_column)) {
value = (String)getItem().get(m_column);
}
String html = "<input type='radio' value='" + value + "' name='" + m_fieldName + "'";
if (!isEnabled()) {
html += " disabled";
}
if (getItem().getId().equals(getSelectedItemId())) {
html += " checked";
}
if (CmsStringUtil.<API key>(m_attributes)) {
html += m_attributes;
}
html += ">\n";
return A_CmsHtmlIconButton.defaultButtonHtml(
<API key>.SMALL_ICON_TEXT,
getId(),
html,
getHelpText().key(wp.getLocale()),
false,
null,
null,
null);
}
/**
* Returns the attributes.<p>
*
* @return the attributes
*/
public String getAttributes() {
return m_attributes;
}
/**
* Returns the column.<p>
*
* @return the column
*/
public String getColumn() {
return m_column;
}
/**
* Returns the fieldName.<p>
*
* @return the fieldName
*/
public String getFieldName() {
return m_fieldName;
}
/**
* Sets the attributes.<p>
*
* @param attributes the attributes to set
*/
public void setAttributes(String attributes) {
m_attributes = attributes;
}
/**
* Sets the column.<p>
*
* @param column the column to set
*/
public void setColumn(String column) {
m_column = column;
}
/**
* Sets the fieldName.<p>
*
* @param fieldName the fieldName to set
*/
public void setFieldName(String fieldName) {
m_fieldName = fieldName;
}
} |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_05) on Sun Jul 13 14:54:41 CEST 2008 -->
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Uses of Class org.accada.epcis.soap.<API key> (epcis 0.3.3-SNAPSHOT API)
</TITLE>
<META NAME="date" CONTENT="2008-07-13">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.accada.epcis.soap.<API key> (epcis 0.3.3-SNAPSHOT API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/accada/epcis/soap/\<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.accada.epcis.soap.<API key></B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.accada.epcis.queryclient"><B>org.accada.epcis.queryclient</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.accada.epcis.repository"><B>org.accada.epcis.repository</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.accada.epcis.repository.query"><B>org.accada.epcis.repository.query</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.accada.epcis.soap"><B>org.accada.epcis.soap</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.accada.epcis.queryclient"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A> in <A HREF="../../../../../org/accada/epcis/queryclient/package-summary.html">org.accada.epcis.queryclient</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/accada/epcis/queryclient/package-summary.html">org.accada.epcis.queryclient</A> that throw <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B>QueryControlClient.</B><B><A HREF="../../../../../org/accada/epcis/queryclient/QueryControlClient.html#poll(java.io.InputStream)">poll</A></B>(java.io.InputStream queryStream)</CODE>
<BR>
Parses the query given in its XML representation and sends it to the
Query Operations Module.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/queryclient/<API key>.html#poll(org.accada.epcis.model.Poll)">poll</A></B>(<A HREF="../../../../../org/accada/epcis/model/Poll.html" title="class in org.accada.epcis.model">Poll</A> poll)</CODE>
<BR>
Performs a poll operation at the repository's Query Controls Module.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B>QueryControlClient.</B><B><A HREF="../../../../../org/accada/epcis/queryclient/QueryControlClient.html#poll(org.accada.epcis.model.Poll)">poll</A></B>(<A HREF="../../../../../org/accada/epcis/model/Poll.html" title="class in org.accada.epcis.model">Poll</A> poll)</CODE>
<BR>
Performs a poll operation at the repository's Query Controls Module.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B>QueryControlClient.</B><B><A HREF="../../../../../org/accada/epcis/queryclient/QueryControlClient.html#poll(java.lang.String)">poll</A></B>(java.lang.String query)</CODE>
<BR>
Parses the query given in its XML representation and sends it to the
Query Operations Module.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>QueryControlClient.</B><B><A HREF="../../../../../org/accada/epcis/queryclient/QueryControlClient.html#subscribe(java.io.InputStream)">subscribe</A></B>(java.io.InputStream query)</CODE>
<BR>
Parses the query given in its XML representation and sends it to the
Query Operations Module.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>QueryControlClient.</B><B><A HREF="../../../../../org/accada/epcis/queryclient/QueryControlClient.html#subscribe(java.lang.String)">subscribe</A></B>(java.lang.String query)</CODE>
<BR>
Parses the query given in its XML representation and sends it to the
Query Operations Module.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/queryclient/<API key>.html#subscribe(java.lang.String, org.accada.epcis.model.QueryParams, java.lang.String, org.accada.epcis.model.<API key>, java.lang.String)">subscribe</A></B>(java.lang.String queryName,
<A HREF="../../../../../org/accada/epcis/model/QueryParams.html" title="class in org.accada.epcis.model">QueryParams</A> params,
java.lang.String dest,
<A HREF="../../../../../org/accada/epcis/model/<API key>.html" title="class in org.accada.epcis.model"><API key></A> controls,
java.lang.String subscriptionId)</CODE>
<BR>
Performs a subscribe operation at the repository's Query Controls Module,
i.e. subscribes a query for later execution.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>QueryControlClient.</B><B><A HREF="../../../../../org/accada/epcis/queryclient/QueryControlClient.html#subscribe(java.lang.String, org.accada.epcis.model.QueryParams, java.lang.String, org.accada.epcis.model.<API key>, java.lang.String)">subscribe</A></B>(java.lang.String queryName,
<A HREF="../../../../../org/accada/epcis/model/QueryParams.html" title="class in org.accada.epcis.model">QueryParams</A> params,
java.lang.String dest,
<A HREF="../../../../../org/accada/epcis/model/<API key>.html" title="class in org.accada.epcis.model"><API key></A> controls,
java.lang.String subscriptionId)</CODE>
<BR>
Performs a subscribe operation at the repository's Query Controls Module,
i.e. subscribes a query for later execution.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.accada.epcis.repository"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A> in <A HREF="../../../../../org/accada/epcis/repository/package-summary.html">org.accada.epcis.repository</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/accada/epcis/repository/package-summary.html">org.accada.epcis.repository</A> that throw <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/repository/<API key>.html#poll(java.lang.String, org.accada.epcis.model.QueryParams)">poll</A></B>(java.lang.String queryName,
<A HREF="../../../../../org/accada/epcis/model/QueryParams.html" title="class in org.accada.epcis.model">QueryParams</A> params)</CODE>
<BR>
Invokes a previously defined query having the specified name, returning
the results.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/repository/<API key>.html#subscribe(java.lang.String, org.accada.epcis.model.QueryParams, java.lang.String, org.accada.epcis.model.<API key>, java.lang.String)">subscribe</A></B>(java.lang.String queryName,
<A HREF="../../../../../org/accada/epcis/model/QueryParams.html" title="class in org.accada.epcis.model">QueryParams</A> params,
java.lang.String dest,
<A HREF="../../../../../org/accada/epcis/model/<API key>.html" title="class in org.accada.epcis.model"><API key></A> controls,
java.lang.String subscriptionID)</CODE>
<BR>
Registers a subscriber for a previously defined query having the
specified name.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.accada.epcis.repository.query"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A> in <A HREF="../../../../../org/accada/epcis/repository/query/package-summary.html">org.accada.epcis.repository.query</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/accada/epcis/repository/query/package-summary.html">org.accada.epcis.repository.query</A> that throw <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B>QuerySubscription.</B><B><A HREF="../../../../../org/accada/epcis/repository/query/QuerySubscription.html#executePoll(org.accada.epcis.model.Poll)">executePoll</A></B>(<A HREF="../../../../../org/accada/epcis/model/Poll.html" title="class in org.accada.epcis.model">Poll</A> poll)</CODE>
<BR>
Poll a query using local transport.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/repository/query/<API key>.html#poll(org.accada.epcis.model.Poll)">poll</A></B>(<A HREF="../../../../../org/accada/epcis/model/Poll.html" title="class in org.accada.epcis.model">Poll</A> poll)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/repository/query/<API key>.html#poll(java.lang.String, org.accada.epcis.model.QueryParams)">poll</A></B>(java.lang.String queryName,
<A HREF="../../../../../org/accada/epcis/model/QueryParams.html" title="class in org.accada.epcis.model">QueryParams</A> queryParams)</CODE>
<BR>
Invokes a previously defined query having the specified name, returning
the results.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/repository/query/<API key>.html#subscribe(java.lang.String, org.accada.epcis.model.QueryParams, java.lang.String, org.accada.epcis.model.<API key>, java.lang.String)">subscribe</A></B>(java.lang.String queryName,
<A HREF="../../../../../org/accada/epcis/model/QueryParams.html" title="class in org.accada.epcis.model">QueryParams</A> params,
java.lang.String dest,
<A HREF="../../../../../org/accada/epcis/model/<API key>.html" title="class in org.accada.epcis.model"><API key></A> controls,
java.lang.String subscriptionID)</CODE>
<BR>
Registers a subscriber for a previously defined query having the
specified name.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/VoidHolder.html" title="class in org.accada.epcis.model">VoidHolder</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/repository/query/<API key>.html#subscribe(org.accada.epcis.model.Subscribe)">subscribe</A></B>(<A HREF="../../../../../org/accada/epcis/model/Subscribe.html" title="class in org.accada.epcis.model">Subscribe</A> subscribe)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="org.accada.epcis.soap"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A> in <A HREF="../../../../../org/accada/epcis/soap/package-summary.html">org.accada.epcis.soap</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/accada/epcis/soap/package-summary.html">org.accada.epcis.soap</A> that throw <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><API key></A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/QueryResults.html" title="class in org.accada.epcis.model">QueryResults</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/soap/<API key>.html#poll(org.accada.epcis.model.Poll)">poll</A></B>(<A HREF="../../../../../org/accada/epcis/model/Poll.html" title="class in org.accada.epcis.model">Poll</A> parms)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/accada/epcis/model/VoidHolder.html" title="class in org.accada.epcis.model">VoidHolder</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/accada/epcis/soap/<API key>.html#subscribe(org.accada.epcis.model.Subscribe)">subscribe</A></B>(<A HREF="../../../../../org/accada/epcis/model/Subscribe.html" title="class in org.accada.epcis.model">Subscribe</A> parms)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/accada/epcis/soap/<API key>.html" title="class in org.accada.epcis.soap"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/accada/epcis/soap/\<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
Copyright &
</BODY>
</HTML> |
<?php
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER['SCRIPT_NAME'], basename(__FILE__)) !== false) {
header('location: index.php');
exit;
}
/**
* @return array
*/
function module_share_info()
{
return [
'name' => tra('Share'),
'description' => tra('Links for sharing, reporting etc.'),
'params' => [
'report' => [
'name' => tra('Report'),
'description' => tra('Report to Webmaster') . ' (y/n)',
'filter' => 'alpha',
],
'share' => [
'name' => tra('Share'),
'description' => tra('Share this page') . ' (y/n)',
'filter' => 'alpha',
],
'email' => [
'name' => tra('Email'),
'description' => tra('Email this page') . ' (y/n)',
'filter' => 'alpha',
],
'icons' => [
'name' => tra('Icons'),
'description' => tra('Use icons for report, share and email links') . ' (n/y)',
'filter' => 'alpha',
],
'facebook' => [
'name' => tra('Facebook'),
'description' => tra('Show Facebook "Like" button on the current page') . ' (n/y)',
'filter' => 'alpha',
],
'facebook_href' => [
'name' => tra('Facebook: URL'),
'description' => tra('URL to "Like" (leave blank for current URL)'),
'filter' => 'url',
],
'facebook_send' => [
'name' => tra('Facebook: Send'),
'description' => tra('Show Facebook "Send" button') . ' (y/n)',
'filter' => 'alpha',
],
'facebook_layout' => [
'name' => tra('Facebook: Layout'),
'description' => tra('Size, layout and amount of social context') . ' (standard/button_count/box_count)',
'filter' => 'text',
],
'facebook_width' => [
'name' => tra('Facebook: Width'),
'description' => tra('Width in pixels') . ' (450)',
'filter' => 'digits',
],
'facebook_height' => [
'name' => tra('Facebook: Height'),
'description' => tra('Container height in CSS units (e.g. "120px" or "2em")'),
'filter' => 'text',
],
'facebook_show_faces' => [
'name' => tra('Facebook: Show Faces'),
'description' => tra('Show pictures of others who like this') . ' (y/n)',
'filter' => 'alpha',
],
'facebook_verb' => [
'name' => tra('Facebook: Verb'),
'description' => tra('Verb to display in button') . ' (like/recommend)',
'filter' => 'word',
],
'<API key>' => [
'name' => tra('Facebook: Colors'),
'description' => tra('Color scheme') . ' (light/dark)',
'filter' => 'word',
],
'facebook_font' => [
'name' => tra('Facebook: Font'),
'description' => tra('Font to display') . ' (lucida grande/arial/segoe ui/tahoma/trebuchet ms/verdana)',
'filter' => 'text',
],
'facebook_locale' => [
'name' => tra('Facebook: Locale'),
'description' => tra('Locale in the format ll_CC (default "en_US")'),
'filter' => 'text',
],
'facebook_ref' => [
'name' => tra('Facebook: Referrals'),
'description' => tra('Label for tracking referrals (optional)'),
'filter' => 'text',
],
'facebook_appId' => [
'name' => tra('Facebook: App Id'),
'description' => tra('ID of your Facebook app (optional)'),
'filter' => 'digits',
],
'twitter' => [
'name' => tra('Twitter'),
'description' => tra('Show Twitter Follow Button on the current page') . ' (n/y)',
'filter' => 'alpha',
],
'twitter_username' => [
'name' => tra('Twitter: User Name'),
'description' => tra('Twitter user name to quote as "via"'),
'filter' => 'text',
],
'twitter_label' => [
'name' => tra('Twitter: Label'),
'description' => tra('Text to display. Default "Tweet"'),
'filter' => 'text',
],
'twitter_url' => [
'name' => tra('Twitter: URL'),
'description' => tra('URL to "Tweet" (leave blank for current URL)'),
'filter' => 'url',
],
'<TwitterConsumerkey>' => [
'name' => tra('Twitter: Show Count'),
'description' => tra('Position of Tweet count') . ' (horizontal/vertical/none)',
'filter' => 'alpha',
],
'twitter_language' => [
'name' => tra('Twitter: Language'),
'description' => tra('Two letter language code') . ' (en/de/es/fr/id/it/ko/ja/nl/pt/re/tr)',
'filter' => 'word',
],
'twitter_width' => [
'name' => tra('Twitter: Width'),
'description' => tra('Width in pixels or percentage (e.g. 300px)'),
'filter' => 'text',
],
'twitter_height' => [
'name' => tra('Twitter: Height'),
'description' => tra('Container height in CSS units (e.g. "120px" or "2em")'),
'filter' => 'text',
],
'twitter_text' => [
'name' => tra('Twitter: Text'),
'description' => tra('Tweet text (leave empty to use page title'),
'filter' => 'word',
],
'linkedin' => [
'name' => tra('LinkedIn'),
'description' => tra('Linked in share button') . ' (n/y)',
'filter' => 'alpha',
],
'linkedin_url' => [
'name' => tra('LinkedIn: URL'),
'description' => tra('URL to share (leave blank for current URL)'),
'filter' => 'url',
],
'linkedin_mode' => [
'name' => tra('LinkedIn: Count Mode'),
'description' => tra('Position of count') . ' (none/top/right)',
'filter' => 'word',
],
'google' => [
'name' => tra('Google +1'),
'description' => tra('Google +1 button') . ' (n/y)',
'filter' => 'alpha',
],
'google_size' => [
'name' => tra('Google: Size'),
'description' => tra('Google button size') . ' (standard|small|medium|tall)',
'filter' => 'word',
],
'google_annotation' => [
'name' => tra('Google: Annotation'),
'description' => tra('Google annotation') . ' (bubble|inline|none)',
'filter' => 'word',
],
'google_language' => [
'name' => tra('Google: Language'),
'description' => tra('Google language') . ' (en-US|fr|ca|de|en-UK|...)',
'filter' => 'text',
],
'google_href' => [
'name' => tra('Google: URL'),
'description' => tra('URL to share (leave blank for current URL)'),
'filter' => 'url',
],
],
];
}
/**
* @param $mod_reference
* @param $module_params
*/
function module_share($mod_reference, $module_params)
{
static $<API key> = 0;
$smarty = TikiLib::lib('smarty');
$smarty->assign('<API key>', ++$<API key>);
$smarty->assign('share_icons', ! empty($module_params['icons']) && $module_params['icons'] === 'y');
// facebook like
$fbData = '';
$fbDivAttr = '';
if (! empty($module_params['facebook_height'])) {
$fbDivAttr .= ' height:' . $module_params['facebook_height'] . ';';
}
if (empty($module_params['facebook_send']) || $module_params['facebook_send'] === 'y') {
$fbData .= ' data-send="true"';
} else {
$fbData .= ' data-send="false"';
}
if (! empty($module_params['facebook_layout']) && $module_params['facebook_layout'] !== 'standard') {
$fbData .= ' data-layout="' . $module_params['facebook_layout'] . '"';
}
if (! empty($module_params['facebook_width'])) {
$fbData .= ' data-width="' . $module_params['facebook_width'] . '"';
$fbDivAttr .= ' width:' . $module_params['facebook_width'] . 'px;';
}
if (empty($module_params['facebook_show_faces']) || $module_params['facebook_layout'] === 'y') {
$fbData .= ' data-show-faces="true"';
} else {
$fbData .= ' data-show-faces="false"';
}
if (! empty($module_params['facebook_verb']) && $module_params['facebook_verb'] !== 'like') {
$fbData .= ' data-action="recommend"';
}
if (! empty($module_params['<API key>']) && $module_params['<API key>'] !== 'light') {
$fbData .= ' data-colorscheme="dark"';
}
if (! empty($module_params['facebook_font']) && $module_params['facebook_font'] !== 'lucida grande') {
$fbData .= ' data-font="' . $module_params['facebook_font'] . '"';
}
if (! empty($module_params['facebook_ref'])) {
$fbData .= ' data-ref="' . htmlspecialchars($module_params['facebook_ref']) . '"';
}
if (! empty($module_params['facebook_href'])) {
$fbData .= ' data-href="' . $module_params['facebook_href'] . '"';
}
$smarty->assign('fb_data_attributes', $fbData);
if (! empty($module_params['facebook_appId'])) {
$smarty->assign('fb_app_id_param', '&appId=' . $module_params['facebook_appId']);
} else {
$smarty->assign('fb_app_id_param', '');
};
if (! empty($fbDivAttr)) {
$fbDivAttr = ' style="' . $fbDivAttr . '"';
}
$smarty->assign('fb_div_attributes', $fbDivAttr);
if (! empty($module_params['facebook_locale'])) {
$smarty->assign('fb_locale', $module_params['facebook_locale']);
} else {
$smarty->assign('fb_locale', 'en_US');
};
// twitter button
$twData = '';
$twDivAttr = '';
if (! empty($module_params['twitter_height'])) {
$twDivAttr .= ' height:' . $module_params['twitter_height'] . ';';
}
if (! empty($module_params['twitter_width'])) {
$twDivAttr .= ' width:' . $module_params['twitter_width'] . ';';
}
if (empty($module_params['<TwitterConsumerkey>']) || $module_params['<TwitterConsumerkey>'] === 'horizontal') {
$twData .= ' data-count="horizontal"';
} else {
$twData .= ' data-count="' . $module_params['<TwitterConsumerkey>'] . '"';
}
if (! empty($module_params['twitter_username'])) {
$twData .= ' data-via="' . $module_params['twitter_username'] . '"';
}
if (! empty($module_params['twitter_language'])) {
$twData .= ' data-lang="' . $module_params['twitter_language'] . '"';
}
if (! empty($module_params['twitter_text'])) {
$twData .= ' data-text="' . htmlspecialchars($module_params['twitter_text']) . '"';
}
if (! empty($module_params['twitter_url'])) {
$twData .= ' data-url="' . $module_params['twitter_url'] . '"';
}
$smarty->assign('tw_data_attributes', $twData);
if (! empty($twDivAttr)) {
$twDivAttr = 'style="' . $twDivAttr . '"';
}
$smarty->assign('tw_div_attributes', $twDivAttr);
// linkedin
$liData = '';
if (! empty($module_params['linkedin_url'])) {
$liData .= ' data-url="' . $module_params['linkedin_url'] . '"';
}
if (! empty($module_params['linkedin_mode'])) {
$liData .= ' data-counter="' . $module_params['linkedin_mode'] . '"';
}
$smarty->assign('li_data_attributes', $liData);
// linkedin
$glData = '';
if (! empty($module_params['google_size']) && $module_params['google_size'] !== 'standard') {
$glData .= ' data-size="' . $module_params['google_size'] . '"';
}
if (! empty($module_params['google_annotation']) && $module_params['google_annotation'] !== 'bubble') {
$glData .= ' data-annotation="' . $module_params['google_annotation'] . '"';
}
if (! empty($module_params['google_href'])) {
$glData .= ' data-href="' . $module_params['google_href'] . '"';
}
$smarty->assign('gl_data_attributes', $glData);
if (! empty($module_params['google_language']) && $module_params['google_language'] !== 'en-US') {
$smarty->assign('gl_script_addition', " window.___gcfg = {lang: '{$module_params['google_language']}'};\n");
}
} |
define( "JBrowse/View/Track/SNPCoverage", ['dojo/_base/declare',
'dojo/_base/array',
'JBrowse/View/Track/Wiggle',
'JBrowse/Util',
'JBrowse/Model/<API key>',
'JBrowse/View/Track/MismatchesMixin'
],
function( declare, array, Wiggle, Util, <API key>, MismatchesMixin ) {
var dojof = Util.dojof;
// feature class for the features we make for the calculated coverage
// values
var CoverageFeature = Util.fastDeclare(
{
get: function(f) { return this[f]; },
tags: function() { return [ 'start', 'end', 'score' ]; },
score: 0,
constructor: function( args ) {
this.start = args.start;
this.end = args.end;
this.score = args.score;
}
});
return declare( [Wiggle, MismatchesMixin],
{
constructor: function() {
// force conf variables that are meaningless for this kind of track, and maybe harmful
delete this.config.bicolor_pivot;
delete this.config.scale;
delete this.config.align;
},
_defaultConfig: function() {
return Util.deepUpdate(
dojo.clone( this.inherited(arguments) ),
{
min_score: 0,
max_score: 100
}
);
},
getGlobalStats: function() {
return {};
},
getFeatures: function( query, featureCallback, finishCallback, errorCallback ) {
var thisB = this;
var leftBase = query.start;
var rightBase = query.end;
var scale = query.scale; // px/bp
var widthBp = rightBase-leftBase;
var widthPx = widthBp * ( query.scale || 1/query.basesPerSpan);
var binWidth = Math.ceil( query.basesPerSpan ); // in bp
var binNumber = function( bp ) {
return Math.floor( (bp-leftBase) / binWidth );
};
// init coverage bins
var maxBin = binNumber( rightBase );
var coverageBins = new Array( maxBin+1 );
for( var i = 0; i <= maxBin; i++ ) {
coverageBins[i] = new <API key>();
}
var binOverlap = function( bp, isRightEnd ) {
var binCoord = (bp-leftBase) / binWidth;
var binNumber = Math.floor( binCoord );
// only calculate the overlap if this lies in this block
if( binNumber >= 0 && binNumber <= maxBin ) {
var overlap =
isRightEnd ? 1 - ( binCoord - binNumber )
: binCoord - binNumber;
return {
bin: binNumber,
overlap: overlap // between 0 and 1: proportion of this bin that the feature overlaps
};
}
// otherwise null, this feature goes outside the block
else {
return isRightEnd ? { bin: maxBin, overlap: 1 }
: { bin: 0, overlap: 1 };
}
};
thisB.store.getFeatures(
query,
function( feature ) {
// calculate total coverage
var startBO = binOverlap( feature.get('start'), false );
var endBO = binOverlap( feature.get('end')-1 , true );
// increment start and end partial-overlap bins by proportion of overlap
if( startBO.bin == endBO.bin ) {
coverageBins[startBO.bin].increment( 'reference', endBO.overlap + startBO.overlap - 1 );
}
else {
coverageBins[startBO.bin].increment( 'reference', startBO.overlap );
coverageBins[endBO.bin].increment( 'reference', endBO.overlap );
}
// increment completely overlapped interior bins by 1
for( var i = startBO.bin+1; i <= endBO.bin-1; i++ ) {
coverageBins[i].increment( 'reference', 1 );
}
// Calculate SNP coverage
if( binWidth == 1 ) {
// mark each bin as having its snps counted
for( var i = startBO.bin; i <= endBO.bin; i++ ) {
coverageBins[i].snpsCounted = 1;
}
// parse the MD
var mdTag = feature.get('MD');
if( mdTag ) {
var SNPs = thisB._mdToMismatches(feature, mdTag);
// loops through mismatches and updates coverage variables accordingly.
for (var i = 0; i<SNPs.length; i++) {
var pos = binNumber( feature.get('start') + SNPs[i].start );
var bin = coverageBins[pos];
if( bin ) {
var strand = { '-1': '-', '1': '+' }[ ''+feature.get('strand') ] || 'unstranded';
// Note: we decrement 'reference' so that total of the score is the total coverage
bin.decrement('reference', 1/binWidth );
var base = SNPs[i].bases;
bin.getNested(base).increment(strand, 1/binWidth);
}
}
}
}
},
function () {
var makeFeatures = function() {
// make fake features from the coverage
for( var i = 0; i <= maxBin; i++ ) {
var bpOffset = leftBase+binWidth*i;
featureCallback( new CoverageFeature({
start: bpOffset,
end: bpOffset+binWidth,
score: coverageBins[i]
}));
}
finishCallback();
};
// if we are zoomed to base level, try to fetch the
// reference sequence for this region and record each
// of the bases in the coverage bins
if( binWidth == 1 ) {
var sequence;
thisB.browser.getStore( 'refseqs', function( refSeqStore ) {
if( refSeqStore ) {
refSeqStore.getFeatures( query,
function(f) {
sequence = f.get('seq');
},
function() {
if( sequence ) {
for( var base = leftBase; base <= rightBase; base++ ) {
var bin = binNumber( base );
coverageBins[bin].refBase = sequence[bin];
}
}
makeFeatures();
},
makeFeatures
);
} else {
makeFeatures();
}
});
} else {
makeFeatures();
}
}
);
},
/*
* Draw a set of features on the canvas.
* @private
*/
_drawFeatures: function( scale, leftBase, rightBase, block, canvas, features, featureRects, dataScale ) {
var thisB = this;
var context = canvas.getContext('2d');
var canvasHeight = canvas.height;
var toY = dojo.hitch( this, function( val ) {
return canvasHeight * ( 1-dataScale.normalize.call(this, val) );
});
var originY = toY( dataScale.origin );
// a canvas element below the histogram that will contain indicators of likely SNPs
var snpCanvasHeight = parseInt( block.parentNode.style.height ) - canvas.height;
var snpCanvas = dojo.create('canvas',
{height: snpCanvasHeight,
width: canvas.width,
style: {
cursor: 'default',
width: "100%",
height: snpCanvasHeight + "px"
},
innerHTML: 'Your web browser cannot display this type of track.',
className: 'SNP-indicator-track'
}, block);
var snpContext = snpCanvas.getContext('2d');
var negColor = this.config.style.neg_color;
var clipColor = this.config.style.clip_marker_color;
var bgColor = this.config.style.bg_color;
var disableClipMarkers = this.config.<API key>;
var drawRectangle = function(ID, yPos, height, fRect) {
// draw the background color if we are configured to do so
if( bgColor && yPos >= 0 ) {
context.fillStyle = bgColor;
context.fillRect( fRect.l, 0, fRect.w, canvasHeight );
}
if( yPos <= canvasHeight ) { // if the rectangle is visible at all
context.fillStyle = thisB.colorForBase(ID);
if( yPos <= originY ) {
// bar goes upward
context.fillRect( fRect.l, yPos, fRect.w, height);
if( !disableClipMarkers && yPos < 0 ) { // draw clip marker if necessary
context.fillStyle = clipColor || negColor;
context.fillRect( fRect.l, 0, fRect.w, 2 );
}
}
else {
// bar goes downward
context.fillRect( fRect.l, originY, fRect.w, height );
if( !disableClipMarkers && yPos >= canvasHeight ) { // draw clip marker if necessary
context.fillStyle = clipColor || thisB.colorForBase(ID);
context.fillRect( fRect.l, canvasHeight-3, fRect.w, 2 );
}
}
}
};
dojo.forEach( features, function(f,i) {
var fRect = featureRects[i];
var score = f.get('score');
var totalHeight = score.total();
// draw indicators of SNPs if base coverage is greater than 50% of total coverage
score.forEach( function( count, category ) {
if ( category != 'reference' && count > 0.5*totalHeight ) {
snpContext.beginPath();
snpContext.arc( fRect.l + 0.5*fRect.w,
0.40*snpCanvas.height,
0.20*snpCanvas.height,
1.75 * Math.PI,
1.25 * Math.PI,
false);
snpContext.lineTo(fRect.l + 0.5*fRect.w, 0);
snpContext.closePath();
snpContext.fillStyle = thisB.colorForBase(category);
snpContext.fill();
snpContext.lineWidth = 1;
snpContext.strokeStyle = 'black';
snpContext.stroke();
}
});
// Note: 'reference' is done first to ensure the grey part of the graph is on top
drawRectangle( 'reference', toY(totalHeight), originY-toY( score.get('reference'))+1, fRect);
totalHeight -= score.get('reference');
score.forEach( function( count, category ) {
if ( category != 'reference' ) {
drawRectangle( category, toY(totalHeight), originY-toY( count )+1, fRect);
totalHeight -= count;
}
});
}, this );
},
/**
* parse a SAM MD tag to find mismatching bases of the template versus the reference
* @returns {Array[Object]} array of mismatches and their positions
*/
_mdToMismatches: function( feature, mdstring ) {
var mismatchRecords = [];
var curr = { start: 0, bases: '' };
var seq = feature.get('seq');
var nextRecord = function() {
mismatchRecords.push( curr );
curr = { start: curr.start + curr.bases.length, bases: ''};
};
array.forEach( mdstring.match(/(\d+|\^[a-z]+|[a-z])/ig), function( token ) {
if( token.match(/^\d/) ) { // matching bases
curr.start += parseInt( token );
}
else if( token.match(/^\^/) ) { // insertion in the template
var i = token.length-1;
while( i
curr.bases = '*';
nextRecord();
}
}
else if( token.match(/^[a-z]/i) ) { // mismatch
curr.bases = seq.substr( curr.start, token.length );
nextRecord();
}
});
return mismatchRecords;
},
/*
* The following method is required to override the equivalent method in "WiggleBase.js"
* It displays more complete data.
*/
_showPixelValue: function( scoreDisplay, score ) {
if( ! score )
return false;
function fmtNum( num ) {
return parseFloat( num ).toPrecision(6).replace(/0+$/,'').replace(/\.$/,'');
}
if( score.snpsCounted ) {
var total = score.total();
var scoreSummary = '<table>';
function pctString( count ) {
return Math.round(count/total*100)+'%';
}
scoreSummary +=
'<tr class="ref"><td>'
+ (score.refBase ? score.refBase+'*' : 'Ref')
+ '</td><td class="count">'
+ fmtNum( score.get('reference') )
+ '</td><td class="pct">'
+ pctString( score.get('reference') )
+ '</td></tr>';
score.forEach( function( count, category ) {
if( category == 'reference' ) return;
// if this count has more nested categories, do counts of those
var subdistribution = '';
if( count.forEach ) {
subdistribution = [];
count.forEach( function( count, category ) {
subdistribution.push( fmtNum(count) + ' '+category );
});
subdistribution = subdistribution.join(', ');
if( subdistribution )
subdistribution = '('+subdistribution+')';
}
category = { '*': 'del' }[category] || category;
scoreSummary += '<tr><td>'+category + '</td><td class="count">' + fmtNum(count) + '</td><td class="pct">'
+pctString(count)+'</td><td class="subdist">'+subdistribution + '</td></tr>';
});
scoreSummary += '<tr class="total"><td>Total</td><td class="count">'+fmtNum(total)+'</td><td class="pct"> </td><td class="subdist"> </td></tr>';
scoreDisplay.innerHTML = scoreSummary+'</table>';
return true;
} else {
scoreDisplay.innerHTML = '<table><tr><td>Total</td><td class="count">'+fmtNum(score)+'</td></tr></table>';
return true;
}
}
});
}); |
package org.xwiki.sheet.internal;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Assert;
import org.jmock.Expectations;
import org.jmock.Sequence;
import org.junit.Before;
import org.junit.Test;
import org.xwiki.bridge.<API key>;
import org.xwiki.bridge.DocumentModelBridge;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.<API key>;
import org.xwiki.sheet.SheetBinder;
import org.xwiki.sheet.SheetManager;
import org.xwiki.test.jmock.<API key>;
import org.xwiki.test.annotation.AllComponents;
import org.xwiki.test.jmock.annotation.MockingRequirement;
/**
* Unit tests for {@link DefaultSheetManager}.
*
* @version $Id$
* @since 4.2M1
*/
@AllComponents
@MockingRequirement(value = DefaultSheetManager.class, exceptions = { <API key>.class })
public class <API key> extends <API key><SheetManager>
{
/**
* The name of the execution context sheet property.
*/
private static final String SHEET_PROPERTY = "sheet";
/**
* The action property of the sheet descriptor class. See {@link #<API key>}.
*/
private static final String ACTION_PROPERTY = "action";
/**
* The name of a wiki.
*/
private static final String WIKI_NAME = "wiki";
/**
* The sheet descriptor class reference.
*/
private static final DocumentReference <API key> = new DocumentReference(WIKI_NAME, "XWiki",
"<API key>");
/**
* The execution context.
*/
private ExecutionContext context = new ExecutionContext();
/**
* The component used to access the documents.
*/
private <API key> <API key>;
/**
* The component used to retrieve the custom document sheets.
*/
private SheetBinder documentSheetBinder;
/**
* The component used to retrieve the class sheets.
*/
private SheetBinder classSheetBinder;
/**
* The component used to access the old model.
*/
private ModelBridge modelBridge;
/**
* The document whose sheets are retrieved.
*/
private DocumentModelBridge document;
@Before
public void configure() throws Exception
{
<API key> = getComponentManager().getInstance(<API key>.class);
documentSheetBinder = getComponentManager().getInstance(SheetBinder.class, "document");
classSheetBinder = getComponentManager().getInstance(SheetBinder.class, "class");
modelBridge = getComponentManager().getInstance(ModelBridge.class);
document = getMockery().mock(DocumentModelBridge.class);
final Execution execution = getComponentManager().getInstance(Execution.class);
getMockery().checking(new Expectations()
{
{
allowing(execution).getContext();
will(returnValue(context));
allowing(document).<API key>();
will(returnValue(new DocumentReference(WIKI_NAME, "Space", "Page")));
}
});
}
/**
* Tests that the sheet specified on the execution context overwrites the document and class sheets.
*
* @throws Exception if the test fails to lookup components
*/
@Test
public void <API key>() throws Exception
{
// (1) The sheet is specified on the execution context and the target document is the current document.
context.setProperty(SHEET_PROPERTY, "Code.Sheet");
final DocumentReference sheetReference = new DocumentReference(WIKI_NAME, "Code", "Sheet");
getMockery().checking(new Expectations()
{
{
oneOf(<API key>).<API key>();
will(returnValue(document.<API key>()));
oneOf(<API key>).exists(sheetReference);
will(returnValue(true));
// The specified sheet matches the current action.
oneOf(<API key>).getProperty(sheetReference, <API key>, ACTION_PROPERTY);
will(returnValue(""));
}
});
Assert.assertEquals(Arrays.asList(sheetReference), getMockedComponent().getSheets(document, "view"));
// (2) The sheet is specified on the execution context but the target document is not the current document.
getMockery().checking(new Expectations()
{
{
oneOf(<API key>).<API key>();
will(returnValue(null));
oneOf(documentSheetBinder).getSheets(document);
will(returnValue(Collections.emptyList()));
oneOf(modelBridge).<API key>(document);
will(returnValue(Collections.emptySet()));
}
});
Assert.assertTrue(getMockedComponent().getSheets(document, "edit").isEmpty());
// (3) The sheet is not specified on the execution context.
context.removeProperty(SHEET_PROPERTY);
getMockery().checking(new Expectations()
{
{
oneOf(documentSheetBinder).getSheets(document);
will(returnValue(Collections.emptyList()));
oneOf(modelBridge).<API key>(document);
will(returnValue(Collections.emptySet()));
}
});
Assert.assertTrue(getMockedComponent().getSheets(document, "get").isEmpty());
}
/**
* Tests the order in which sheets are determined: execution context, document sheets and finally class sheets.
*
* @throws Exception shouldn't happen, but some methods include "throws" in their signature
*/
@Test
public void <API key>() throws Exception
{
final String contextSheetName = "ContextSheet";
context.setProperty(SHEET_PROPERTY, contextSheetName);
final DocumentReference <API key> = new DocumentReference(WIKI_NAME, "ABC", "DocumentSheet");
final DocumentReference classSheetReference = new DocumentReference(WIKI_NAME, "BlogCode", "BlogPostSheet");
final DocumentReference classReference = new DocumentReference(WIKI_NAME, "Blog", "BlogPostClass");
final DocumentModelBridge classDocument = getMockery().mock(DocumentModelBridge.class, "xclass");
final String currentAction = "foo";
final Sequence <API key> = getMockery().sequence("<API key>");
getMockery().checking(new Expectations()
{
{
// (1) Look for the sheet specified in the execution context.
oneOf(<API key>).<API key>();
inSequence(<API key>);
will(returnValue(document.<API key>()));
// The sheet is resolved relative to the target document.
oneOf(<API key>).exists(
new DocumentReference(document.<API key>().getWikiReference().getName(), document
.<API key>().<API key>().getName(), contextSheetName));
inSequence(<API key>);
will(returnValue(false));
// (2) Look for the custom document sheets.
oneOf(documentSheetBinder).getSheets(document);
inSequence(<API key>);
will(returnValue(Collections.singletonList(<API key>)));
oneOf(<API key>).exists(<API key>);
inSequence(<API key>);
will(returnValue(true));
oneOf(<API key>).getProperty(<API key>, <API key>, ACTION_PROPERTY);
inSequence(<API key>);
will(returnValue("bar"));
// (3) Look for the class sheets.
oneOf(modelBridge).<API key>(document);
inSequence(<API key>);
will(returnValue(Collections.singleton(classReference)));
oneOf(<API key>).<API key>(classReference);
inSequence(<API key>);
will(returnValue(classDocument));
oneOf(classSheetBinder).getSheets(classDocument);
inSequence(<API key>);
will(returnValue(Collections.singletonList(classSheetReference)));
oneOf(<API key>).exists(classSheetReference);
inSequence(<API key>);
will(returnValue(true));
oneOf(<API key>).getProperty(classSheetReference, <API key>, ACTION_PROPERTY);
inSequence(<API key>);
will(returnValue(currentAction));
}
});
getMockedComponent().getSheets(document, currentAction);
}
} |
__all__ = ["annotation", "detection", "track"] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.