code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
module Marty
module Promises
module Ruby
end
end
end
| arman000/marty | app/services/marty/promises/ruby.rb | Ruby | mit | 65 |
package org.nem.core.model;
import org.nem.core.utils.ArrayUtils;
import java.util.Comparator;
/**
* A custom comparator for comparing MultisigSignatureTransaction objects.
* <br>
* This comparator only looks at the transaction signer and other hash.
*/
public class MultisigSignatureTransactionComparator implements Comparator<MultisigSignatureTransaction> {
@Override
public int compare(final MultisigSignatureTransaction lhs, final MultisigSignatureTransaction rhs) {
final Address lhsAddress = lhs.getSigner().getAddress();
final Address rhsAddress = rhs.getSigner().getAddress();
final int addressCompareResult = lhsAddress.compareTo(rhsAddress);
if (addressCompareResult != 0) {
return addressCompareResult;
}
return ArrayUtils.compare(lhs.getOtherTransactionHash().getRaw(), rhs.getOtherTransactionHash().getRaw());
}
}
| NewEconomyMovement/nem.core | src/main/java/org/nem/core/model/MultisigSignatureTransactionComparator.java | Java | mit | 854 |
<?php
namespace app\controllers;
use Yii;
use app\models\{Freight, FreightSearch};
use yii\web\{Controller, NotFoundHttpException};
/**
* FreightController implements the CRUD actions for Freight model.
*/
class FreightController extends Controller
{
/**
* Lists all Freight models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new FreightSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Freight model.
* @param string $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Freight model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Freight();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Freight model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param string $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Finds the Freight model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param string $id
* @return Freight the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Freight::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| lmihaylov2512/logistic-app | controllers/FreightController.php | PHP | mit | 2,382 |
// ReplProbe.js (c) 2010-2013 Loren West and other contributors
// May be freely distributed under the MIT license.
// For further details and documentation:
// http://lorenwest.github.com/monitor-min
(function(root){
// Module loading - this runs server-side only
var Monitor = root.Monitor || require('../Monitor'),
_ = Monitor._,
Probe = Monitor.Probe,
REPL = require('repl'),
Stream = require('stream'),
util = require('util'),
events = require('events'),
ChildProcess = require('child_process');
// Statics
var CONSOLE_PROMPT = '> ';
var NEW_REPL = (typeof REPL.disableColors === 'undefined');
/**
* A probe based Read-Execute-Print-Loop console for node.js processes
*
* @class ReplProbe
* @extends Probe
* @constructor
* @param initParams {Object} Probe initialization parameters
* @param initParams.uniqueInstance - Usually specified to obtain a unique REPL probe instance
* @param model {Object} Monitor data model elements
* @param model.output {String} Last (current) REPL output line
* @param model.sequence {Integer} Increasing sequence number - to enforce unique line output
*/
var ReplProbe = Monitor.ReplProbe = Probe.extend({
probeClass: 'Repl',
description: 'A socket.io based Read-Execute-Print-Loop console for node.js processes.',
defaults: {
// This assures output events are sent, even if the
// data is the same as the prior output.
sequence: 0,
output: ''
},
initialize: function(attributes, options){
var t = this;
Probe.prototype.initialize.apply(t, arguments);
// Don't send change events before connected
process.nextTick(function(){
t.stream = new ReplStream(t);
if (NEW_REPL) {
t.repl = require('repl').start({
prompt: CONSOLE_PROMPT,
input: t.stream,
output: t.stream
});
} else {
t.repl = REPL.start(CONSOLE_PROMPT, t.stream);
}
t.htmlConsole = new HtmlConsole(t);
t.shellCmd = null;
t.repl.context.console = t.htmlConsole;
});
},
/**
* Send output to the terminal
*
* This forces the change event even if the last output is the same
* as this output.
*
* @protected
* @method output
* @param str {String} String to output to the repl console
*/
_output: function(str) {
var t = this;
t.set({
output: str,
sequence: t.get('sequence') + 1
});
},
/**
* Release any resources consumed by this probe.
*
* Stop the REPL console. Consoles live 1-1 with a UI counterpart, so stop
* requests exit the underlying repl console. If the probe is re-started it
* will get a new repl stream and console.
*
* @method release
*/
release: function(){
var t = this;
t.stream = null;
t.repl = null;
},
/**
* Process an autocomplete request from the client
*
* @method autocomplete
* @param {Object} params Named parameters
* @param {Function(error, returnParams)} callback Callback function
*/
autocomplete_control: function(params, callback) {
var t = this;
if (typeof(params) !== 'string' || params.length < 1) {
callback("Autocomplete paramter must be a nonzero string");
}
// Forward to the completion mechanism if it can be completed
if (params.substr(-1).match(/([0-9])|([a-z])|([A-Z])|([_])/)) {
t.repl.complete(params, callback);
} else {
// Return a no-op autocomplete
callback(null, [[],'']);
}
},
/**
* Handle user input from the console line
*
* @method input
* @param {Object} params Named parameters
* @param {Function(error, returnParams)} callback Callback function
*/
input_control: function(params, callback) {
var t = this;
if (params === '.break' && t.shellCmd) {
t.shellCmd.kill();
}
if (NEW_REPL) {
t.stream.emit('data', params + "\n");
} else {
t.stream.emit('data', params);
}
return callback(null);
},
/**
* Execute a shell command
*
* @method sh
* @param {Object} params Named parameters
* @param {Function(error, returnParams)} callback Callback function
*/
sh_control: function(params, callback) {
var t = this;
return callback(null, t._runShellCmd(params));
},
/**
* Run a shell command and emit the output to the browser.
*
* @private
* @method _runShellCmd
* @param {String} command - The shell command to invoke
*/
_runShellCmd: function(command) {
var t = this;
t.shellCmd = ChildProcess.exec(command, function(err, stdout, stderr) {
if (err) {
var outstr = 'exit';
if (err.code) {
outstr += ' (' + err.code + ')';
}
if (err.signal) {
outstr += ' ' + err.signal;
}
t._output(outstr);
return null;
}
if (stdout.length) {
t._output(stdout);
}
if (stderr.length) {
t._output(stderr);
}
t.shellCmd = null;
t._output(CONSOLE_PROMPT);
});
return null;
}
});
// Define an internal stream class for the probe
var ReplStream = function(probe){
var t = this;
t.probe = probe;
events.EventEmitter.call(t);
if (t.setEncoding) {
t.setEncoding('utf8');
}
};
util.inherits(ReplStream, events.EventEmitter);
// util.inherits(ReplStream, require('stream'));
ReplStream.prototype.readable = true;
ReplStream.prototype.writable = true;
['pause','resume','destroySoon','pipe', 'end']
.forEach(function(fnName){
ReplStream.prototype[fnName] = function(){
console.log("REPL Stream function unexpected: " + fnName);
};
});
['resume']
.forEach(function(fnName){
ReplStream.prototype[fnName] = function(){
// Handled
};
});
ReplStream.prototype.write = function(data) {
var t = this;
t.probe._output(data);
};
ReplStream.prototype.destroy = function(data) {
var t = this;
console.log("REPL stream destroy " + t.probe.get('id'));
t.probe.stop();
};
// Define format if it's not in util.
var formatRegExp = /%[sdj]/g;
var format = util.format || function (f) {
if (typeof f !== 'string') {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(util.inspect(arguments[i]));
}
return objects.join(' ');
}
var j = 1;
var args = arguments;
var str = String(f).replace(formatRegExp, function(x) {
switch (x) {
case '%s': return String(args[j++]);
case '%d': return Number(args[j++]);
case '%j': return JSON.stringify(args[j++]);
default:
return x;
}
});
for (var len = args.length, x = args[j]; j < len; x = args[++j]) {
if (x === null || typeof x !== 'object') {
str += ' ' + x;
} else {
str += ' ' + util.inspect(x);
}
}
return str;
};
// Re-define the console so it goes to the HTML window
var HtmlConsole = function(probe){
this.probe = probe;
};
HtmlConsole.prototype.log = function(msg) {
this.probe._output(format.apply(this, arguments));
};
HtmlConsole.prototype.info = HtmlConsole.prototype.log;
HtmlConsole.prototype.warn = HtmlConsole.prototype.log;
HtmlConsole.prototype.error = HtmlConsole.prototype.log;
HtmlConsole.prototype.dir = function(object) {
this.probe._output(util.inspect(object));
};
var times = {};
HtmlConsole.prototype.time = function(label) {
times[label] = Date.now();
};
HtmlConsole.prototype.timeEnd = function(label) {
var duration = Date.now() - times[label];
this.log('%s: %dms', label, duration);
};
}(this));
| lorenwest/monitor-min | lib/probes/ReplProbe.js | JavaScript | mit | 7,982 |
package model.dataModels;
/**
* Class ManufacturingData.
* @author Daniel
*
*/
public class ManufacturingData {
private String customerNumber;
private String materialNumber;
private String orderNumber;
private String timeStamp;
private MachineData[] machineData;
private SpectralAnalysisData analysisData;
/**
* Constructor.
*/
public ManufacturingData() {}
/**
* Creates a string representation
* of this object.
* @return
*/
@Override
public String toString() {
return customerNumber + " " + materialNumber + " "
+ orderNumber + " " + timeStamp + " "
+ machineData + " " + analysisData;
}
/*
* Getters and Setters.
*/
/**
* Adds erp data.
* @param data
*/
public void setErpData(ErpData data) {
this.customerNumber = data.getCustomerNumber();
this.materialNumber = data.getMaterialNumber();
this.orderNumber = data.getOrderNumber();
this.timeStamp = data.getTimeStamp();
}
/**
* Appends machine data to the array.
* @param data
*/
public void appendMachineData(MachineData data) {
if(this.machineData == null) {
this.machineData = new MachineData[1];
machineData[0] = data;
} else {
int length = this.machineData.length;
MachineData[] temp = new MachineData[length + 1];
for(int i = 0; i < length; i++) {
temp[i] = this.machineData[i];
}
temp[length] = data;
this.machineData = temp;
}
}
/**
* Adds spectral analysis data.
* @param analysisData
*/
public void setAnalysisData(SpectralAnalysisData analysisData) {
this.analysisData = analysisData;
}
public String getCustomerNumber() {
return customerNumber;
}
public String getMaterialNumber() {
return materialNumber;
}
public String getOrderNumber() {
return orderNumber;
}
public String getTimeStamp() {
return timeStamp;
}
public MachineData[] getMachineData() {
return machineData;
}
public SpectralAnalysisData getAnalysisData() {
return analysisData;
}
} | 4lexBaum/projekt-5s-dhbw | Backend/src/main/java/model/dataModels/ManufacturingData.java | Java | mit | 1,974 |
using System;
using System.Collections.Generic;
using Roguelike.Core.Elements.Inventory;
using Roguelike.Entities;
using RLNET;
namespace Roguelike.Systems {
public class InventorySystem {
private Player player;
public InventorySystem() {
player = Game.Player;
}
void SelectEquipment(Equipment pressedOn) {
if (pressedOn.GetType() == typeof(HeadEquipment)) {
SelectHeadEquipment((HeadEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(BodyEquipment)) {
SelectBodyEquipment((BodyEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(ArmEquipment)) {
SelectArmEquipment((ArmEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(LegEquipment)) {
SelectLegEquipment((LegEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(HandEquipment)) {
SelectHandEquipment((HandEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(FeetEquipment)) {
SelectFeetEquipment((FeetEquipment)pressedOn);
}
Game.Render();
}
void DiscardEquipment(Equipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
Game.Render();
}
void SelectHeadEquipment(HeadEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if(player.Head != null && player.Head != HeadEquipment.None()) {
player.AddEquipment(player.Head);
}
player.Head = pressedOn;
}
void SelectBodyEquipment(BodyEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Body != null && player.Body != BodyEquipment.None()) {
player.AddEquipment(player.Body);
}
player.Body = pressedOn;
}
void SelectArmEquipment(ArmEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Arms != null && player.Arms != ArmEquipment.None()) {
player.AddEquipment(player.Arms);
}
player.Arms = pressedOn;
}
void SelectLegEquipment(LegEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Legs != null && player.Legs != LegEquipment.None()) {
player.AddEquipment(player.Legs);
}
player.Legs = pressedOn;
}
void SelectHandEquipment(HandEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Hands != null && player.Hands != HandEquipment.None()) {
player.AddEquipment(player.Hands);
}
player.Hands = pressedOn;
}
void SelectFeetEquipment(FeetEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Feet != null && player.Feet != FeetEquipment.None()) {
player.AddEquipment(player.Feet);
}
player.Feet = pressedOn;
}
public Equipment EquipArmourFromInventory(int x, int y) {
for (int i = 0; i < player.equipmentInInventory.Count; i++) {
int lengthOfString = player.equipmentInInventory[i].Name.Length;
int numberOfLines = 0;
if(lengthOfString >= 20) {
numberOfLines = 2;
} else {
numberOfLines = 1;
}
int xStartPosition = 0;
int yPosition = (3 * i) + 3;
if(i < 6) {
xStartPosition = 22;
} else {
yPosition = (3 * i) - 15;
xStartPosition = 44;
}
if(numberOfLines == 1) {
if(x >= xStartPosition && x < xStartPosition + lengthOfString && y == yPosition) {
SelectEquipment(player.equipmentInInventory[i]);
}
}else if(numberOfLines == 2) {
string topString = TopLine(player.equipmentInInventory[i].Name);
string bottomString = BottomLine(player.equipmentInInventory[i].Name, topString);
if(y == yPosition) {
if(x >= xStartPosition && x < xStartPosition + topString.Length - 1) {
SelectEquipment(player.equipmentInInventory[i]);
}
} else if(y == yPosition + 1) {
if (x >= xStartPosition && x < xStartPosition + bottomString.Length) {
SelectEquipment(player.equipmentInInventory[i]);
}
}
}
}
return null;
}
public void DiscardArmourFromInventory(int x, int y) {
for (int i = 0; i < player.equipmentInInventory.Count; i++) {
int lengthOfString = player.equipmentInInventory[i].Name.Length;
int numberOfLines = 0;
if (lengthOfString >= 20) {
numberOfLines = 2;
} else {
numberOfLines = 1;
}
int xStartPosition = 0;
int yPosition = (3 * i) + 3;
if (i < 6) {
xStartPosition = 22;
} else {
yPosition = (3 * i) - 15;
xStartPosition = 44;
}
if (numberOfLines == 1) {
if (x >= xStartPosition && x < xStartPosition + lengthOfString && y == yPosition) {
DiscardEquipment(player.equipmentInInventory[i]);
}
} else if (numberOfLines == 2) {
string topString = TopLine(player.equipmentInInventory[i].Name);
string bottomString = BottomLine(player.equipmentInInventory[i].Name, topString);
if (y == yPosition) {
if (x >= xStartPosition && x < xStartPosition + topString.Length - 1) {
DiscardEquipment(player.equipmentInInventory[i]);
}
} else if (y == yPosition + 1) {
if (x >= xStartPosition && x < xStartPosition + bottomString.Length) {
DiscardEquipment(player.equipmentInInventory[i]);
}
}
}
}
}
public void RemoveEquipment(int x, int y) {
if (y == 3) {
if (x >= 1 && x <= 14) {
HeadEquipment toRemove = player.Head;
player.Head = HeadEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
LegEquipment toRemove = player.Legs;
player.Legs = LegEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
} else if (y == 5) {
if (x >= 1 && x <= 14) {
BodyEquipment toRemove = player.Body;
player.Body = BodyEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
HandEquipment toRemove = player.Hands;
player.Hands = HandEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
} else if (y == 7) {
if (x >= 1 && x <= 14) {
ArmEquipment toRemove = player.Arms;
player.Arms = ArmEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
FeetEquipment toRemove = player.Feet;
player.Feet = FeetEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
}
Game.Render();
}
public Equipment RemoveCurrentArmour(int x, int y) {
if(y == 3 || y == 4) {
ClickedOnHead(x, y);
} else if(y == 6 || y == 7) {
ClickedOnBody(x, y);
} else if (y == 9 || y == 10) {
ClickedOnArms(x, y);
} else if (y == 12 || y == 13) {
ClickedOnLegs(x, y);
} else if (y == 15 || y == 16) {
ClickedOnHands(x, y);
} else if (y == 18 || y == 19) {
ClickedOnFeet(x, y);
}
return null;
}
private void ClickedOnHead(int x, int y) {
string topLine = TopLine("Head: " + player.Head.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Head: " + player.Head.Name, topLine);
} catch {
}
if (y == 4) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Head);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Head);
}
}
}
public void ClickedOnBody(int x, int y) {
string topLine = TopLine("Body: " + player.Body.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Body: " + player.Body.Name, topLine);
} catch {
}
if (y == 7) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Body);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Body);
}
}
}
public void ClickedOnArms(int x, int y) {
string topLine = TopLine("Arms: " + player.Arms.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Arms: " + player.Arms.Name, topLine);
} catch {
}
if (y == 10) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Arms);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Arms);
}
}
}
public void ClickedOnLegs(int x, int y) {
string topLine = TopLine("Legs: " + player.Legs.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Legs: " + player.Legs.Name, topLine);
} catch {
}
if (y == 13) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Legs);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Legs);
}
}
}
public void ClickedOnHands(int x, int y) {
string topLine = TopLine("Hands: " + player.Hands.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Hands: " + player.Hands.Name, topLine);
} catch {
}
if (y == 16) {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Hands);
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Hands);
}
}
}
private void ClickedOnFeet(int x, int y) {
string topLine = TopLine("Feet: " + player.Feet.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Feet: " + player.Feet.Name, topLine);
} catch {
}
if (y == 19) {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Feet);
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Feet);
}
}
}
public bool DidClickOnString(int x, int y, bool secondLine,string topLine, string bottomLine = "") {
int xStartPosition = 1;
int topXEndPosition = xStartPosition + topLine.Length;
int bottomXEndPosition = xStartPosition + bottomLine.Length;
if (bottomLine != "") {
if (secondLine) {
if (x >= xStartPosition && x <= bottomXEndPosition) {
return true;
} else {
return false;
}
} else {
if (x >= xStartPosition && x <= topXEndPosition) {
return true;
} else {
return false;
}
}
} else {
if(x >= xStartPosition && x <= topXEndPosition) {
return true;
} else {
return false;
}
}
}
private void UnequipArmour(Equipment toUnequip) {
if (toUnequip.GetType() == typeof(HeadEquipment) && toUnequip != HeadEquipment.None()) {
UnSelectHeadEquipment((HeadEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(BodyEquipment) && toUnequip != BodyEquipment.None()) {
UnSelectBodyEquipment((BodyEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(ArmEquipment) && toUnequip != ArmEquipment.None()) {
UnSelectArmEquipment((ArmEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(LegEquipment) && toUnequip != LegEquipment.None()) {
UnSelectLegEquipment((LegEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(HandEquipment) && toUnequip != HandEquipment.None()) {
UnSelectHandEquipment((HandEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(FeetEquipment) && toUnequip != FeetEquipment.None()) {
UnSelectFeetEquipment((FeetEquipment)toUnequip);
}
Game.Render();
}
private void UnSelectHeadEquipment(HeadEquipment toUnequip) {
if(player.equipmentInInventory.Count < 12) {
player.Head = HeadEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectBodyEquipment(BodyEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Body = BodyEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectArmEquipment(ArmEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Arms = ArmEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectLegEquipment(LegEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Legs = LegEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectHandEquipment(HandEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Hands = HandEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectFeetEquipment(FeetEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Feet = FeetEquipment.None();
player.AddEquipment(toUnequip);
}
}
private string TopLine(string totalString, int wrapLength = 18) {
List<string> wordsInString = new List<string>();
string currentString = "";
for (int i = 0; i < totalString.Length; i++) {
char character = totalString[i];
if (character == ' ') {
wordsInString.Add(currentString);
currentString = "";
}else if(i == totalString.Length - 1) {
currentString += character;
wordsInString.Add(currentString);
currentString = "";
} else {
currentString += character;
}
}
int lengthSoFar = 0;
string topLine = "";
for (int i = 0; i < wordsInString.Count; i++) {
if (lengthSoFar + wordsInString[i].Length >= wrapLength) {
break;
}
lengthSoFar += wordsInString[i].Length;
topLine += wordsInString[i];
topLine += " ";
}
return topLine;
}
private string BottomLine(string totalString, string topLine) {
string bottom = totalString;
bottom = bottom.Substring(topLine.Length);
return bottom;
}
}
}
| SamFergie/Roguelike | Roguelike/Systems/InventorySystem.cs | C# | mit | 18,045 |
# frozen_string_literal: true
require "dry/core/equalizer"
require "rom/initializer"
require "rom/relation/loaded"
require "rom/relation/composite"
require "rom/relation/materializable"
require "rom/pipeline"
require "rom/support/memoizable"
module ROM
class Relation
# Abstract relation graph class
#
# @api public
class Graph
extend Initializer
include Memoizable
# @!attribute [r] root
# @return [Relation] The root relation
param :root
# @!attribute [r] nodes
# @return [Array<Relation>] An array with relation nodes
param :nodes
include Dry::Equalizer(:root, :nodes)
include Materializable
include Pipeline
include Pipeline::Proxy
# for compatibility with the pipeline
alias_method :left, :root
alias_method :right, :nodes
# Rebuild a graph with new nodes
#
# @param [Array<Relation>] nodes
#
# @return [Graph]
#
# @api public
def with_nodes(nodes)
self.class.new(root, nodes)
end
# Return if this is a graph relation
#
# @return [true]
#
# @api private
def graph?
true
end
# Map graph tuples via custom mappers
#
# @see Relation#map_with
#
# @return [Relation::Composite]
#
# @api public
def map_with(*names, **opts)
names.reduce(self.class.new(root.with(opts), nodes)) { |a, e| a >> mappers[e] }
end
# Map graph tuples to custom objects
#
# @see Relation#map_to
#
# @return [Graph]
#
# @api public
def map_to(klass)
self.class.new(root.map_to(klass), nodes)
end
# @see Relation#mapper
#
# @api private
def mapper
mappers[to_ast]
end
# @api private
memoize def to_ast
[:relation, [name.relation, attr_ast + nodes.map(&:to_ast), meta_ast]]
end
private
# @api private
def decorate?(other)
super || other.is_a?(Composite) || other.is_a?(Curried)
end
# @api private
def composite_class
Relation::Composite
end
end
end
end
| rom-rb/rom | lib/rom/relation/graph.rb | Ruby | mit | 2,218 |
version https://git-lfs.github.com/spec/v1
oid sha256:b51623fcae1419d2bb29084e11d56fc9aafae7b0e35bd2a7fd30633a133bef40
size 24229
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.0/slider-base/slider-base-debug.js | JavaScript | mit | 130 |
module Librr::Displayer
class << self
attr_accessor :save_output, :output
def clear_output
@output = []
end
def save(text)
@output ||= []
@output << text
end
end
def show text
if Librr::Displayer.save_output
Librr::Displayer.save(text)
return
end
puts text
end
end
| halida/librr | lib/librr/displayer.rb | Ruby | mit | 342 |
var gif_bgs = [];
var gif_center = [];
var length_bgs = 0;
var length_center = 0;
var timer;
var duration = 4000;
var loaded = 0;
var next_bg;
var next_center;
var audio = document.getElementById("sound");
var muted = false;
function next(e){
clearInterval(timer);
timer = setInterval(next, duration);
$("#background").css("background-image","url("+gif_bgs[next_bg]+")");
$("#center").css("background-image","url("+gif_center[next_center]+")");
next_bg = Math.floor( Math.random()*length_bgs );
next_center = Math.floor( Math.random()*length_center );
$("#load_bg").attr("src",gif_bgs[next_bg]);
$("#load_center").attr("src",gif_center[next_center]);
}
function toggleInfo(){
$("#info-overlay").toggleClass("show");
$("#info-btn").toggleClass("show");
}
function check(){
if (loaded > 1) {
next_bg = Math.floor( Math.random()*length_bgs );
next_center = Math.floor( Math.random()*length_center );
next();
$("#wrapper").click(next);
}
}
function toggleSound(){
if (muted) {
muted = false;
audio.muted = muted;
$("#sound-btn").removeClass('muted');
}else{
muted = true;
audio.muted = muted;
$("#sound-btn").addClass('muted');
}
}
function init() {
$("#info-btn").click(toggleInfo);
$("#sound-btn").click(toggleSound);
$.ajax({
url: "json/bg.json",
cache: false,
dataType: "json",
success: function(d){
gif_bgs = d;
length_bgs = gif_bgs.length;
loaded++;
check();
}
});
$.ajax({
url: "json/center.json",
cache: false,
dataType: "json",
success: function(d){
gif_center = d;
length_center = gif_center.length;
loaded++;
check();
}
});
}
Meteor.startup(function(){init();});
| paralin/1148WTF | client/js/gif.js | JavaScript | mit | 1,679 |
package com.tbp.safemaps;
import the.safemaps.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MarkUnsafe extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marksafe);
//Button back = (Button)findViewById(R.id.mbuttonBack);
Button done = (Button)findViewById(R.id.done);
done.setOnClickListener(onClickListener);
// back.setOnClickListener(onClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
// case R.id.go:
// Intent go= new Intent(Markunsafe.this,mapdirections.class);
//startActivity(go);
//break;
}
}
};
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.action_bar:
//Toast.makeText(getBaseContext(), "back", Toast.LENGTH_SHORT).show();
Intent back= new Intent(MarkUnsafe.this,MainActivity.class);
startActivity(back);
break;
}
return true;
}
}
| thebachchaoproject/safemaps | safemaps_android/src/com/tbp/safemaps/MarkUnsafe.java | Java | mit | 1,557 |
#include "protagonist.h"
#include "SerializeResult.h"
#include "v8_wrapper.h"
#include "snowcrash.h"
using namespace v8;
using namespace protagonist;
Result::Result()
{
}
Result::~Result()
{
}
Nan::Persistent<Function> Result::constructor;
void Result::Init(Handle<Object> exports)
{
Nan::HandleScope scope;
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
t->SetClassName(Nan::New<String>("Result").ToLocalChecked());
t->InstanceTemplate()->SetInternalFieldCount(1);
constructor.Reset(t->GetFunction());
exports->Set(Nan::New<String>("Result").ToLocalChecked(), t->GetFunction());
}
NAN_METHOD(Result::New)
{
Nan::HandleScope scope;
Result* result = ::new Result();
result->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
v8::Local<v8::Object> Result::WrapResult(snowcrash::ParseResult<snowcrash::Blueprint>& parseResult,
const snowcrash::BlueprintParserOptions& options,
const drafter::ASTType& astType)
{
static const char* AstKey = "ast";
static const char* ErrorKey = "error";
static const char* SourcemapKey = "sourcemap";
sos::Object result;
try {
result = drafter::WrapResult(parseResult, options, astType);
}
catch (snowcrash::Error& error) {
parseResult.report.error = error;
}
if (astType == drafter::NormalASTType && parseResult.report.error.code != snowcrash::Error::OK) {
result.set(AstKey, sos::Null());
if ((options & snowcrash::ExportSourcemapOption) != 0) {
result.set(SourcemapKey, sos::Null());
}
}
result.unset(ErrorKey);
return v8_wrap(result)->ToObject();
}
| cold-brew-coding/protagonist | src/result.cc | C++ | mit | 1,745 |
require "importu/backends"
class DummyBackend
def self.supported_by_definition?(definition)
false
end
def initialize(finder_fields:, **)
@finder_fields = finder_fields
@objects = []
@max_id = 0
end
def find(record)
@finder_fields.detect do |field_group|
if field_group.respond_to?(:call) # proc
raise "proc-based finder scopes not supported for dummy backend"
else
values = record.values_at(*Array(field_group))
object = @objects.detect {|o| values == o.values_at(*Array(field_group)) }
break object if object
end
end
end
def unique_id(object)
object[:id]
end
def create(record)
object = { id: @max_id += 1 }.merge(record.to_hash)
@objects << object
[:created, object]
end
def update(record, object)
new_object = object.merge(record.to_hash)
if new_object == object
[:unchanged, new_object]
else
@objects[object[:id]-1] = new_object
[:updated, new_object]
end
end
end
Importu::Backends.registry.register(:dummy, DummyBackend)
| dhedlund/importu | spec/support/dummy_backend.rb | Ruby | mit | 1,083 |
#!/usr/bin/env python3
"""
My radio server application
For my eyes only
"""
#CREATE TABLE Radio(id integer primary key autoincrement, radio text, genre text, url text);
uuid='56ty66ba-6kld-9opb-ak29-0t7f5d294686'
# Import CherryPy global namespace
import os
import sys
import time
import socket
import cherrypy
import sqlite3 as lite
import re
import subprocess
from random import shuffle
# Globals
version = "4.2.1"
database = "database.db"
player = 'omxplayer'
header = '''<!DOCTYPE html>
<html lang="en">
<head>
<title>My Radio Web Server</title>
<meta name="generator" content="Vim">
<meta charset="UTF-8">
<link rel="icon" type="image/png" href="/static/css/icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/static/js/jquery-2.0.3.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<!-- Custom styles for this template -->
<link href="/static/css/sticky-footer.css" rel="stylesheet">
<style media="screen" type="text/css">
#radio-playing { display: none; }
#radio-table { display: none; }
#radio-volume { display: none; }
.jumbotron { padding: 10px 10px; }
</style>
<script type="text/javascript">
function fmodradio(rid) {
$.post('/m/', {id: rid},
function(data){
$("#radio-table").html(data);
$("#radio-table").show();
},
"html"
);
}
function fdelradio(rid) {
var r = confirm("DELETING " + rid);
if (r != true) { return; }
$.post('/d/', {id: rid},
function(data){
$("#radio-table").html(data);
$("#radio-table").show();
},
"html"
);
}
function fplayradio(rid) {
$.post('/p/', {id: rid},
function(data){
$("#radio-playing").html(data);
$("#radio-playing").show();
$("#radio-volume").hide();
},
"html"
);
}
function faddfav(i, g) {
$.post('/haddfav/', {id: i},
function(data){
$("#radio-playing").html(data);
$("#radio-playing").show();
$("#radio-volume").hide();
},
"html"
);
}
function fvolradio(updown) {
$.post('/v/', {vol: updown},
function(data){
$("#radio-volume").html(data);
$("#radio-volume").show();
},
"html"
);
}
function fkilradio() {
$.post('/k/',
function(data){
$("#radio-volume").html(data);
$("#radio-volume").show();
},
"html"
);
}
function fsearch(nam, gen) {
$.post('/g/', {name: nam, genre: gen},
function(data) {
$("#radio-table").html(data);
$("#radio-table").show();
},
"html"
);
}
function frandom(n, g) {
$.post('/g/', {name: n, genre: g, randomlist:'true'},
function(data){
$("#radio-table").html(data);
$("#radio-table").show();
},
"html"
);
}
// ----------------------------------------------------------
$(document).ready(function() {
$('body').on('click', '#button-modify', function(e) {
i = $("#idm").val()
n = $("#namem").val()
g = $("#genrem").val()
u = $("#urlm").val()
$.post("/f/", {id: i, name: n, genre: g, url: u})
.done(function(data) {
$("#radio-table").html(data);
$("#radio-table").show();
});
e.preventDefault();
});
$('#namem').keyup(function(e){
if(e.keyCode == 13) {
$('#button-modify').click();
}
});
$('#genrem').keyup(function(e){
if(e.keyCode == 13) {
$('#button-modify').click();
}
});
$('#urlm').keyup(function(e){
if(e.keyCode == 13) {
$('#button-modify').click();
}
});
$('#button-search').click(function(e) {
n = $("#name").val()
g = $("#genre").val()
$.post("/g/", {name: n, genre: g})
.done(function(data) {
$("#radio-table").html(data);
$("#radio-table").show();
});
e.preventDefault();
});
$('#name').keyup(function(e){
if(e.keyCode == 13) {
$('#button-search').click();
}
});
$('#genre').keyup(function(e){
if(e.keyCode == 13) {
$('#button-search').click();
}
});
$("#button-insert").click(function(e) {
n = $("#namei").val()
g = $("#genrei").val()
u = $("#urli").val()
$.post("/i/", {name: n, genre: g, url: u})
.done(function(data) {
$("#radio-table").html(data);
$("#radio-table").show();
});
e.preventDefault();
});
$("#play-radio").click(function(e) {
i = $("#idp").val()
$.post("/p/", {id: i})
.done(function(data) {
$("#radio-playing").html(data);
$("#radio-playing").show();
});
e.preventDefault();
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class='jumbotron'>
<h2><a href="/">Radio</a>
<a href="#" onClick="fvolradio('down')"><span class="glyphicon glyphicon-volume-down"></span></a>
<a href="#" onClick="fvolradio('up')"><span class="glyphicon glyphicon-volume-up"></span></a>
<a href="#" onClick="fkilradio('up')"> <span class="glyphicon glyphicon-record"></span></a>
</h2>
<p>
<div class="form-group">
<input type="text" id="name" name="name" placeholder="radio to search">
<input type="text" id="genre" name="genre" placeholder="genre" >
<button id="button-search">Search</button>
</div>
</p>
<p>
<div class="form-group">
<input type="text" id="namei" name="name" placeholder="Radio Name">
<input type="text" id="genrei" name="genre" placeholder="genre">
<input type="text" id="urli" name="url" placeholder="http://radio.com/stream.mp3">
<button id="button-insert">Insert</button>
<p>
[
<a href="#" onClick="fsearch('', 'rai')"> rai </a>|
<a href="#" onClick="fsearch('','fav')"> fav </a> |
<a href="#" onClick="fsearch('','rmc')"> rmc </a> |
<a href="#" onClick="fsearch('','class')"> class </a> |
<a href="#" onClick="fsearch('','jazz')"> jazz </a> |
<a href="#" onClick="fsearch('','chill')"> chill </a> |
<a href="#" onClick="fsearch('','nl')"> nl </a> |
<a href="#" onClick="fsearch('','bbc')"> bbc </a> |
<a href="#" onClick="fsearch('','uk')"> uk </a> |
<a href="#" onClick="fsearch('','italy')"> italy </a>
]
</p>
</div>
<small><div id="radio-playing"> </div></small>
</br>
</div> <!-- Jumbotron END -->
<div id="radio-volume"> </div>
<div id="radio-table"> </div>
'''
footer = '''<p></div></body></html>'''
def isplayfile(pathname) :
if os.path.isfile(pathname) == False:
return False
ext = os.path.splitext(pathname)[1]
ext = ext.lower()
if (ext == '.mp2') : return True;
if (ext == '.mp3') : return True;
if (ext == '.ogg') : return True;
return False
# ------------------------ AUTHENTICATION --------------------------------
from cherrypy.lib import auth_basic
# Password is: webradio
users = {'admin':'29778a9bdb2253dd8650a13b8e685159'}
def validate_password(self, login, password):
if login in users :
if encrypt(password) == users[login] :
cherrypy.session['username'] = login
cherrypy.session['database'] = userdatabase(login)
return True
return False
def encrypt(pw):
from hashlib import md5
return md5(pw).hexdigest()
# ------------------------ CLASS --------------------------------
class Root:
@cherrypy.expose
def index(self):
html = header
(_1, _2, id) = getradio('0')
(radio, genre, url) = getradio(id)
if id != 0:
html += '''<h3><a href="#" onClick="fplayradio('%s')"> ''' % id
html += '''Play Last Radio %s <span class="glyphicon glyphicon-play"></span></a></h3>''' % radio
html += getfooter()
return html
@cherrypy.expose
def music(self, directory='/mnt/Media/Music/'):
html = header
count = 0
html += '''<table class="table table-condensed">'''
filelist = os.listdir(directory)
filelist.sort()
for f in filelist:
file = os.path.join(directory, f)
html += '''<tr>'''
if isplayfile(file):
html += '''<td ><a href="#" onClick="fplayradio('%s')">''' % file
html += '''Play %s<span class="glyphicon glyphicon-play"></span></a></td>''' % (file)
if os.path.isdir(file):
html += '''<td ><a href="/music?directory=%s">%s</a> </td>''' % (file, f)
html += '''</tr>'''
count += 1
html += '''</table>'''
html += '''</div> </div>'''
html += getfooter()
return html
@cherrypy.expose
def g(self, name="", genre="", randomlist='false'):
list = searchradio(name.decode('utf8'), genre)
count = 0
# Randomlist
if randomlist == 'true' : shuffle(list)
listhtml = '''<table class="table table-condensed">'''
for id,radio,gen,url in list:
listhtml += '''<tr>'''
listhtml += '''<td width="200px"><a href="#" onClick="fmodradio('%s')" alt="%s">%s</a></td>''' % (id, url, radio)
listhtml += '''<td width="100px">%s</td>''' % gen
listhtml += '''<td ><a href="#" onClick="fplayradio('%s')">Play <span class="glyphicon glyphicon-play"></span></a></td>''' % (id)
listhtml += '''</tr>'''
count += 1
listhtml += '''</table>'''
listhtml += '''</div> </div>'''
html = ''
html += '''<div class="row"> <div class="col-md-8"> '''
if randomlist == 'false':
html += '''<h2><a href="#" onClick="frandom(name='%s', genre='%s', randomlist='true')">%d Results for '%s' + '%s'</a></h2>''' % (name, genre, count, name, genre)
else:
html += '''<h2><a href="#" onClick="fsearch(name='%s', genre='%s')">%d Random for '%s' + '%s'</a></h2>''' % (name, genre, count, name, genre)
html += listhtml
return html
@cherrypy.expose
def i(self, name="", genre="", url=""):
html = "<h2>Insert</h2>"
if name == "" or name == None :
html += "Error no name"
return html
if insert(name, genre, url) == False:
html += "Error db "
return html
html += '''<h3>This radio has been inserted</h3>'''
html += '''<p><table class="table table-condensed">'''
html += ''' <tr> '''
html += ''' <td>radio: <strong>%s</strong></td> ''' % name
html += ''' <td>genre: <strong>%s</strong></td> ''' % genre
html += ''' <td>url: <strong><a href="%s" target="_blank">%s</a></strong></td> ''' % (url, url)
html += ''' <td width="300px"><a href="#" onClick="fplayradio('%s')"> Play ''' % url
html += '''<span class="glyphicon glyphicon-play"></span></a></td>'''
html += ''' </tr> '''
html += '''</table>'''
return html
@cherrypy.expose
def d(self, id=""):
html = "<h2>Delete</h2>"
if id == "" or id == None :
html += "Error"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
#if delete(id) == False:
if nonexist(id) == False:
html += "Delete error in id" % id
html += getfooter()
return html
html += "Item %s set as non existent" % id
return html
@cherrypy.expose
def p(self, id):
html = ""
if id == "" or id == None :
html += "Error no radio id"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
(radio, genre, url) = playradio(id)
if url == '':
html += "Error in parameter %s" % url
return html
cherrypy.session['playing'] = id
html += '''<h3>Now Playing: '''
html += '''<a href="%s">%s</a>''' % (url, radio)
html += '''<a href="#" onClick="fplayradio('%s')">''' % id
html += '''<span class="glyphicon glyphicon-play"></span></a>'''
html += ''' <a href="#" onClick="fmodradio('%s')"><span class="glyphicon glyphicon-pencil"></span></a></small> ''' % id
html += '''<a href="#" onClick="fdelradio('%s')"><span class="glyphicon glyphicon-trash"></span></a> ''' % id
html += '''<a href="#" onClick="faddfav('%s')"><span class="glyphicon glyphicon-star"></span></a>''' % id
html += '''</h3>'''
return html
@cherrypy.expose
def v(self, vol=""):
html = ""
if vol == "" or vol == None :
html += "Error"
v = volume(vol)
html += "<h6>%s (%s) </h6>" % (v, vol)
return html
@cherrypy.expose
def m(self, id):
html = '''<h2>Modify</h2>'''
if id == "" or id == None :
html += "Error"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
(name, genre, url) = getradio(id)
html += '<h3>%s | %s | %s</h3>' % (name, genre, url)
html += '''<input type="hidden" id="idm" name="id" value="%s">''' % id
html += '''<input type="text" id="namem" name="name" value="%s">''' % name
html += '''genre: <input type="text" id="genrem" name="genre" value="%s"> ''' % genre
html += '''url: <input type="text" style="min-width: 280px" id="urlm" name="url" value="%s"> ''' % url
html += '''<button id="button-modify">Change</button>'''
html += '''<h3><a href="#" onClick="fdelradio('%s')">Delete? <span class="glyphicon glyphicon-trash"></span></a></h3>''' % id
html += '''<h3><a href="%s" target="_blank">Play in browser <span class="glyphicon glyphicon-music"></span></a>''' % url
return html
@cherrypy.expose
def f(self, id="", name="", genre="", url=""):
html = '''<h2>Modified</h2>'''
if id == "" or id == None :
html += "Error missing id"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
if modify(id, name, url, genre) == False:
html += "Error in DB"
return html
(name, genre, url) = getradio(id)
html += '''<p><table class="table table-condensed">'''
html += '''<tr>'''
html += '''<td width="100px"><a href="#" onClick="fmodradio('%s')">''' % id
html += '''Mod <span class="glyphicon glyphicon-pencil"></span></a></td>'''
html += '''<td width="200px">%s</td>''' % name
html += '''<td width="200px">%s</td>''' % genre
html += '''<td><a href="%s" target="_blank">%s</a></td>''' % (url, url)
html += '''<td width="300px"><a href="#" onClick="fplayradio('%s')">'''% url
html += '''Play <span class="glyphicon glyphicon-play"></span></a></td>'''
html += '''</tr>'''
html += '''</table>'''
return html
@cherrypy.expose
def haddfav(self, id=""):
if id == "" or id == None :
html += "Error missing id"
return html
if id == "0" :
html += "0 is reserved, sorry"
return html
(name, genre, url) = getradio(id)
if 'Fav' in genre:
genre = genre.replace(', Fav', '')
star = False
else:
genre += ', Fav'
star = True
if addgen(id, genre) == False:
return ''
(name, genre, url) = getradio(id)
cherrypy.session['playing'] = id
html = '<h3>Now Playing: '
html += '''<a href="%s">%s</a>''' % (url, name)
html += '''<a href="#" onClick="fplayradio('%s')">''' % url
html += '''<span class="glyphicon glyphicon-play"></span></a>'''
html += ''' <a href="#" onClick="fmodradio('%s')"><span class="glyphicon glyphicon-pencil"></span></a></small> ''' % id
html += '''<a href="#" onClick="fdelradio('%s')"><span class="glyphicon glyphicon-trash"></span></a> ''' % id
html += '''<a href="#" onClick="faddfav('%s')"><span class="glyphicon glyphicon-star"></span></a>''' % id
if star:
html += '''Starred'''
html += '''</h3>'''
return html
@cherrypy.expose
def k(self):
html = "<h2>Stopping</h2>"
killall()
return html
# ------------------------ DATABASE --------------------------------
def getfooter() :
global footer, version
db = cherrypy.session['database']
try:
con = lite.connect( db )
cur = con.cursor()
sql = "select radio, genre, url from Radio where id=0"
cur.execute(sql)
(radio, genre, url) = cur.fetchone()
except:
(radio, genre, url) = ('ERROR', sql, '')
con.close()
hostname = socket.gethostname()
f = '''<footer class="footer"> <div class="container">'''
f += '''<p class="text-muted">'''
f += '''Session id: %s - Session Database %s<br>''' % (cherrypy.session.id, cherrypy.session['database'])
f += '''Host: %s - Version: %s - Updated: %s // Last: %s''' % (hostname, version, genre, url)
f += '''</p>'''
f += '''</div></footer>'''
return f + footer
def updateversiondb(cur) :
db = cherrypy.session['database']
username = cherrypy.session['username']
dt = time.strftime("%Y-%m-%d %H:%M:%S")
try:
sql = "UPDATE Radio SET radio='%s', genre='%s' WHERE id = 0" % (hostname, dt)
cur.execute(sql)
except:
return
def delete(id) :
db = cherrypy.session['database']
try:
con = lite.connect( db )
cur = con.cursor()
sql = "DELETE from Radio WHERE id = '%s'" % (id)
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def nonexist(id) :
db = cherrypy.session['database']
sql = "UPDATE Radio set exist = 0 WHERE id = '%s'" % (id)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def insert(radio, genre, url) :
db = cherrypy.session['database']
sql = "INSERT INTO Radio (radio, genre, url, exist) VALUES('%s', '%s', '%s', 1)" % (radio, genre, url)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def modify(id, radio, url, genre) :
db = cherrypy.session['database']
sql = "UPDATE Radio SET radio='%s', url='%s', genre='%s', exist=1 WHERE id = %s" % (radio, url, genre, id)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def addgen(id, genre) :
db = cherrypy.session['database']
sql = "UPDATE Radio SET genre='%s' WHERE id = %s" % (genre, id)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
ret = True
except:
ret = False
updateversiondb(cur)
con.commit()
con.close()
return ret
def getradio(id) :
db = cherrypy.session['database']
if id.isdigit() :
sql = "select radio, genre, url from Radio where id=%s" % id
else:
sql = "select radio, genre, url from Radio where url=%s" % id
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
except:
rows = [('Not Found', '', '')]
rows = cur.fetchone()
if rows == None:
rows = ('Not Found', '', '')
con.close()
return rows
def searchradio(radio, genre) :
db = cherrypy.session['database']
#o = 'order by radio'
o = ''
sql = "select id, radio, genre, url from Radio where exist > 0 and radio like '%%%s%%' and genre like '%%%s%%' and id > 0 %s" % (radio, genre, o)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
except:
return [(0, sql, o, genre)]
rows = cur.fetchall()
con.close()
return rows
def updatelastradio(url) :
db = cherrypy.session['database']
sql = "UPDATE Radio SET url='%s' WHERE id=0" % (url)
try:
con = lite.connect( db )
cur = con.cursor()
cur.execute(sql)
con.commit()
con.close()
except:
return
def userdatabase(user) :
db = database
if not os.path.isfile(db):
return None
return db
def getshort(code) :
maxl = 5
newcode = code.replace('http://', '')
if len(newcode) > maxl :
newcode = newcode[0:maxl]
return str(newcode)
def setplayer(p):
global player
player = p
def playradio(urlid):
global player
(radio, genre, url) = getradio(urlid)
status = 0
killall()
if player == 'mpg123':
command = "/usr/bin/mpg123 -q %s" % url
pidplayer = subprocess.Popen(command, shell=True).pid
if player == 'mplayer':
command = "/usr/bin/mplayer -really-quiet %s" % url
pidplayer = subprocess.Popen(command, shell=True).pid
if player == 'omxplayer':
# Process is in background
p = 'omxplayer'
subprocess.Popen([p, url])
updatelastradio(urlid)
return (radio, genre, urlid)
def killall():
global player
status = 0
if player == 'omxplayer':
control = "/usr/local/bin/omxcontrol"
status = subprocess.call([control, "stop"])
status = subprocess.call(["pkill", player])
return status
def volume(vol) :
global player
if player == 'omxplayer':
return volume_omxplayer(vol)
else:
return volume_alsa(vol)
def volume_alsa(vol):
# With ALSA on CHIP
if vol == 'up':
db = subprocess.check_output(["amixer set 'Power Amplifier' 5%+"], shell=True)
#db = os.system("amixer set 'Power Amplifier' 5%+")
if vol == 'down':
db = subprocess.check_output(["amixer set 'Power Amplifier' 5%-"], shell=True)
#db = os.system("amixer set 'Power Amplifier' 5%-")
i = db.rfind(':')
return db[i+1:]
def volume_omxplayer(vol) :
import math
control = "/usr/local/bin/omxcontrol"
if vol == 'up' :
db = subprocess.check_output([control, "volumeup"])
else :
db = subprocess.check_output([control, "volumedown"])
v = subprocess.check_output([control, "volume"])
i = v.rfind(':')
db = 10.0 * math.log(float(v[i+1:]), 10)
volstring = "%-2.2f dB" % db
return volstring
# ------------------------ SYSTEM --------------------------------
def writemypid(pidfile):
pid = str(os.getpid())
with open(pidfile, 'w') as f:
f.write(pid)
f.close
# Cherrypy Management
def error_page_404(status, message, traceback, version):
html = header
html += "%s<br>" % (status)
html += "%s" % (traceback)
html += getfooter()
return html
def error_page_401(status, message, traceback, version):
html = '''<!DOCTYPE html>
<html lang="en">
<head>
<title>My Radio Web Server</title>
<meta name="generator" content="Vim">
<meta charset="UTF-8">
</head>
<body>
'''
html += "<h1>%s</h1>" % (status)
html += "%s<br>" % (message)
return html
# Secure headers!
def secureheaders():
headers = cherrypy.response.headers
headers['X-Frame-Options'] = 'DENY'
headers['X-XSS-Protection'] = '1; mode=block'
headers['Content-Security-Policy'] = "default-src='self'"
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--player', action="store", dest="player", default="mplayer")
parser.add_argument('--stage', action="store", dest="stage", default="production")
parser.add_argument('--database', action="store", dest="database", default="database.db")
parser.add_argument('--root', action="store", dest="root", default=".")
parser.add_argument('--pid', action="store", dest="pid", default="/tmp/8804.pid")
parser.add_argument('--port', action="store", dest="port", type=int, default=8804)
# get args
args = parser.parse_args()
# Where to start, what to get
root = os.path.abspath(args.root)
database = os.path.join(root, args.database)
os.chdir(root)
current_dir = os.path.dirname(os.path.abspath(__file__))
setplayer(args.player)
writemypid(args.pid)
settings = {'global': {'server.socket_host': "0.0.0.0",
'server.socket_port' : args.port,
'log.screen': True,
},
}
conf = {'/static': {'tools.staticdir.on': True,
'tools.staticdir.root': current_dir,
'tools.staticfile.filename': 'icon.png',
'tools.staticdir.dir': 'static'
},
'/': {
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'localhost',
'tools.auth_basic.checkpassword': validate_password,
'tools.secureheaders.on' : True,
'tools.sessions.on': True,
},
}
cherrypy.config.update(settings)
cherrypy.config.update({'error_page.404': error_page_404})
cherrypy.config.update({'error_page.401': error_page_401})
cherrypy.tools.secureheaders = cherrypy.Tool('before_finalize', secureheaders, priority=60)
# To make it ZERO CPU usage
#cherrypy.engine.timeout_monitor.unsubscribe()
#cherrypy.engine.autoreload.unsubscribe()
# Cherry insert pages
serverroot = Root()
# Start the CherryPy server.
cherrypy.quickstart(serverroot, config=conf)
| ernitron/radio-server | radio-server/server.py | Python | mit | 26,943 |
require 'spec_helper'
describe 'Git LFS File Locking API' do
include WorkhorseHelpers
let(:project) { create(:project) }
let(:maintainer) { create(:user) }
let(:developer) { create(:user) }
let(:guest) { create(:user) }
let(:path) { 'README.md' }
let(:headers) do
{
'Authorization' => authorization
}.compact
end
shared_examples 'unauthorized request' do
context 'when user is not authorized' do
let(:authorization) { authorize_user(guest) }
it 'returns a forbidden 403 response' do
post_lfs_json url, body, headers
expect(response).to have_gitlab_http_status(403)
end
end
end
before do
allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
project.add_developer(maintainer)
project.add_developer(developer)
project.add_guest(guest)
end
describe 'Create File Lock endpoint' do
let(:url) { "#{project.http_url_to_repo}/info/lfs/locks" }
let(:authorization) { authorize_user(developer) }
let(:body) { { path: path } }
include_examples 'unauthorized request'
context 'with an existent lock' do
before do
lock_file('README.md', developer)
end
it 'return an error message' do
post_lfs_json url, body, headers
expect(response).to have_gitlab_http_status(409)
expect(json_response.keys).to match_array(%w(lock message documentation_url))
expect(json_response['message']).to match(/already locked/)
end
it 'returns the existen lock' do
post_lfs_json url, body, headers
expect(json_response['lock']['path']).to eq('README.md')
end
end
context 'without an existent lock' do
it 'creates the lock' do
post_lfs_json url, body, headers
expect(response).to have_gitlab_http_status(201)
expect(json_response['lock'].keys).to match_array(%w(id path locked_at owner))
end
end
end
describe 'Listing File Locks endpoint' do
let(:url) { "#{project.http_url_to_repo}/info/lfs/locks" }
let(:authorization) { authorize_user(developer) }
include_examples 'unauthorized request'
it 'returns the list of locked files' do
lock_file('README.md', developer)
lock_file('README', developer)
do_get url, nil, headers
expect(response).to have_gitlab_http_status(200)
expect(json_response['locks'].size).to eq(2)
expect(json_response['locks'].first.keys).to match_array(%w(id path locked_at owner))
end
end
describe 'List File Locks for verification endpoint' do
let(:url) { "#{project.http_url_to_repo}/info/lfs/locks/verify" }
let(:authorization) { authorize_user(developer) }
include_examples 'unauthorized request'
it 'returns the list of locked files grouped by owner' do
lock_file('README.md', maintainer)
lock_file('README', developer)
post_lfs_json url, nil, headers
expect(response).to have_gitlab_http_status(200)
expect(json_response['ours'].size).to eq(1)
expect(json_response['ours'].first['path']).to eq('README')
expect(json_response['theirs'].size).to eq(1)
expect(json_response['theirs'].first['path']).to eq('README.md')
end
end
describe 'Delete File Lock endpoint' do
let!(:lock) { lock_file('README.md', developer) }
let(:url) { "#{project.http_url_to_repo}/info/lfs/locks/#{lock[:id]}/unlock" }
let(:authorization) { authorize_user(developer) }
include_examples 'unauthorized request'
context 'with an existent lock' do
it 'deletes the lock' do
post_lfs_json url, nil, headers
expect(response).to have_gitlab_http_status(200)
end
it 'returns the deleted lock' do
post_lfs_json url, nil, headers
expect(json_response['lock'].keys).to match_array(%w(id path locked_at owner))
end
end
end
def lock_file(path, author)
result = Lfs::LockFileService.new(project, author, { path: path }).execute
result[:lock]
end
def authorize_user(user)
ActionController::HttpAuthentication::Basic.encode_credentials(user.username, user.password)
end
def post_lfs_json(url, body = nil, headers = nil)
post(url, params: body.try(:to_json), headers: (headers || {}).merge('Content-Type' => LfsRequest::CONTENT_TYPE))
end
def do_get(url, params = nil, headers = nil)
get(url, params: (params || {}), headers: (headers || {}).merge('Content-Type' => LfsRequest::CONTENT_TYPE))
end
def json_response
@json_response ||= JSON.parse(response.body)
end
end
| dreampet/gitlab | spec/requests/lfs_locks_api_spec.rb | Ruby | mit | 4,652 |
// -------------------------------------------------------------
// WARNING: this file is used by both the client and the server.
// Do not use any browser or node-specific API!
// -------------------------------------------------------------
/* eslint hammerhead/proto-methods: 2 */
import reEscape from '../utils/regexp-escape';
import INTERNAL_ATTRS from '../processing/dom/internal-attributes';
import { isSpecialPage } from '../utils/url';
const SOURCE_MAP_RE = /#\s*sourceMappingURL\s*=\s*[^\s]+(\s|\*\/)/i;
const CSS_URL_PROPERTY_VALUE_PATTERN = /(url\s*\(\s*)(?:(')([^\s']*)(')|(")([^\s"]*)(")|([^\s\)]*))(\s*\))|(@import\s+)(?:(')([^\s']*)(')|(")([^\s"]*)("))/g;
const STYLESHEET_PROCESSING_START_COMMENT = '/*hammerhead|stylesheet|start*/';
const STYLESHEET_PROCESSING_END_COMMENT = '/*hammerhead|stylesheet|end*/';
const HOVER_PSEUDO_CLASS_RE = /\s*:\s*hover(\W)/gi;
const PSEUDO_CLASS_RE = new RegExp(`\\[${ INTERNAL_ATTRS.hoverPseudoClass }\\](\\W)`, 'ig');
const IS_STYLE_SHEET_PROCESSED_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }`, 'gi');
const STYLESHEET_PROCESSING_COMMENTS_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }\n?|` +
`\n?${ reEscape(STYLESHEET_PROCESSING_END_COMMENT) }\\s*$`, 'gi');
class StyleProcessor {
constructor () {
this.STYLESHEET_PROCESSING_START_COMMENT = STYLESHEET_PROCESSING_START_COMMENT;
this.STYLESHEET_PROCESSING_END_COMMENT = STYLESHEET_PROCESSING_END_COMMENT;
}
process (css, urlReplacer, isStylesheetTable) {
if (!css || typeof css !== 'string' || IS_STYLE_SHEET_PROCESSED_RE.test(css))
return css;
var prefix = isStylesheetTable ? STYLESHEET_PROCESSING_START_COMMENT + '\n' : '';
var postfix = isStylesheetTable ? '\n' + STYLESHEET_PROCESSING_END_COMMENT : '';
// NOTE: Replace the :hover pseudo-class.
css = css.replace(HOVER_PSEUDO_CLASS_RE, '[' + INTERNAL_ATTRS.hoverPseudoClass + ']$1');
// NOTE: Remove the ‘source map’ directive.
css = css.replace(SOURCE_MAP_RE, '$1');
// NOTE: Replace URLs in CSS rules with proxy URLs.
return prefix + this._replaceStylsheetUrls(css, urlReplacer) + postfix;
}
cleanUp (css, parseProxyUrl) {
if (typeof css !== 'string')
return css;
css = css
.replace(PSEUDO_CLASS_RE, ':hover$1')
.replace(STYLESHEET_PROCESSING_COMMENTS_RE, '');
return this._replaceStylsheetUrls(css, url => {
var parsedProxyUrl = parseProxyUrl(url);
return parsedProxyUrl ? parsedProxyUrl.destUrl : url;
});
}
_replaceStylsheetUrls (css, processor) {
return css.replace(
CSS_URL_PROPERTY_VALUE_PATTERN,
(match, prefix1, openQuote1, url1, closeQuote1, openQuote2, url2, closeQuote2, url3, postfix,
prefix2, openQuote3, url4, closeQuote3, openQuote4, url5, closeQuote4) => {
var prefix = prefix1 || prefix2;
var openQuote = openQuote1 || openQuote2 || openQuote3 || openQuote4 || '';
var url = url1 || url2 || url3 || url4 || url5;
var closeQuote = closeQuote1 || closeQuote2 || closeQuote3 || closeQuote4 || '';
postfix = postfix || '';
var processedUrl = isSpecialPage(url) ? url : processor(url);
return url ? prefix + openQuote + processedUrl + closeQuote + postfix : match;
}
);
}
}
export default new StyleProcessor();
| AlexanderMoskovkin/testcafe-hammerhead | src/processing/style.js | JavaScript | mit | 3,704 |
import announcements from './announcements'
import delegates from './delegates'
import fees from './fees'
import ledger from './ledger'
import market from './market'
import peer from './peer'
import wallets from './wallets'
export {
announcements,
delegates,
fees,
ledger,
market,
peer,
wallets
}
| ArkEcosystem/ark-desktop | src/renderer/services/synchronizer/index.js | JavaScript | mit | 312 |
/**
* @flow
* @module ProductPropertyInput
* @extends React.PureComponent
*
* @author Oleg Nosov <olegnosov1@gmail.com>
* @license MIT
*
* @description
* React form for product property(options select only).
*
*/
import React, { PureComponent } from "react";
import { isObject } from "../../../helpers";
import type {
GetLocalization,
InputEvent,
ProductPropertyOption,
Prices,
} from "../../../types";
/**
* @typedef {Object.<string, number>} OptionIndex
*/
export type OptionIndex = {
[propertyName: string]: number,
};
/**
* @typedef {Object} OptionObject
*/
export type OptionObject = {|
onSelect?: (option: OptionObject) => void,
additionalCost?: Prices,
value: ProductPropertyOption,
|};
/** @ */
export type PropertyOption = ProductPropertyOption | OptionObject;
/** @ */
export type PropertyOptions = Array<PropertyOption>;
/** @ */
export type OnChange = (obj: { value: OptionIndex }) => void;
export type Props = {|
name: string,
options: PropertyOptions,
selectedOptionIndex: number,
currency: string,
onChange: OnChange,
getLocalization: GetLocalization,
|};
const defaultProps = {
selectedOptionIndex: 0,
};
export default class ProductPropertyInput extends PureComponent<Props, void> {
props: Props;
static defaultProps = defaultProps;
static displayName = "ProductPropertyInput";
/*
* If option value is an object, we need to extract primitive value
*/
static getOptionValue = (value: PropertyOption): ProductPropertyOption =>
isObject(value) ? ProductPropertyInput.getOptionValue(value.value) : value;
/*
* Generate select input options based on options values
*/
static generateOptionsSelectionList = (
options: PropertyOptions,
getLocalization: GetLocalization,
currency: string,
localizationScope: Object = {},
): Array<React$Element<*>> =>
options
.map(ProductPropertyInput.getOptionValue)
.map((optionValue, index) => (
<option key={optionValue} value={optionValue}>
{typeof optionValue === "string"
? getLocalization(optionValue, {
...localizationScope,
...(isObject(options[index])
? {
cost:
(isObject(options[index].additionalCost) &&
options[index].additionalCost[currency]) ||
0,
}
: {}),
})
: optionValue}
</option>
));
handleSelectInputValueChange = ({ currentTarget }: InputEvent) => {
const { value: optionValue } = currentTarget;
const { name, options, onChange } = this.props;
const { getOptionValue } = ProductPropertyInput;
const selectedOptionIndex = options
.map(getOptionValue)
.indexOf(optionValue);
const selectedOption = options[selectedOptionIndex];
if (
isObject(selectedOption) &&
typeof selectedOption.onSelect === "function"
)
selectedOption.onSelect(selectedOption);
onChange({
value: { [name]: selectedOptionIndex },
});
};
render() {
const {
name,
options,
selectedOptionIndex,
currency,
getLocalization,
} = this.props;
const { handleSelectInputValueChange } = this;
const {
generateOptionsSelectionList,
getOptionValue,
} = ProductPropertyInput;
const localizationScope = {
name,
currency,
get localizedName() {
return getLocalization(name, localizationScope);
},
get localizedCurrency() {
return getLocalization(currency, localizationScope);
},
};
return (
<div className="form-group row">
<label
htmlFor={name}
className="col-xs-3 col-sm-3 col-md-3 col-lg-3 col-form-label"
>
{getLocalization("propertyLabel", localizationScope)}
</label>
<div className="col-xs-9 col-sm-9 col-md-9 col-lg-9">
<select
onChange={handleSelectInputValueChange}
className="form-control"
value={getOptionValue(options[selectedOptionIndex | 0])}
>
{generateOptionsSelectionList(
options,
getLocalization,
currency,
localizationScope,
)}
</select>
</div>
</div>
);
}
}
| olegnn/react-shopping-cart | src/components/Product/ProductPropertyInput/ProductPropertyInput.js | JavaScript | mit | 4,423 |
let BASE_DIR = '/masn01-archive/';
const TAG_OPTIONS = ['meteor', 'cloud', 'bug', 'misc'];
let CURR_DIR = null;
let CURR_FILES = null;
let INIT_CMAP = null;
let CURR_IDX = 0;
let PREV_IDX = null;
$(async function() {
let cameras = JSON.parse(await $.get('cameras.php'));
cameras.forEach((camera) => {
$('#masn-switch').append(`<option value='${camera}/'>${camera}</option>`);
});
BASE_DIR = $('#masn-switch').val();
JS9.ResizeDisplay(750, 750);
TAG_OPTIONS.forEach(tag => $('#tag-select').append(`<option value='${tag}'>${tag}</option>`));
$('#datepicker').prop('disabled', true);
let result = await $.get(BASE_DIR);
let years = getDirectories(result, /\d{4}/);
console.log(years);
new Pikaday({
field: document.getElementById('datepicker'),
format: 'YYYY-MM-DD',
minDate: moment(`${years[0]}-01-01`, 'YYYY-MM-DD').toDate(),
maxDate: moment(`${years[years.length-1]}-12-31`, 'YYYY-MM-DD').toDate(),
defaultDate: moment(`2018-11-20`).toDate(),
onSelect: renderDate,
onDraw: async function(evt) {
let { year, month } = evt.calendars[0];
let { tabs, days } = await $.get(`stats.php?y=${year}&m=${String(month + 1).padStart(2, '0')}`);
let renderedDays = $('.pika-lendar tbody td').filter('[data-day]');
renderedDays.each((_, elem) => {
let dateStr = moment({
day: $(elem).data('day'),
month: month,
year: year
}).format('YYYY-MM-DD');
if (days.indexOf(dateStr) !== -1) {
let dateTab = tabs[days.indexOf(dateStr)];
$(elem).attr('data-tab', dateTab);
if (0 <= dateTab && dateTab < POOR_LIM) $(elem).addClass('day-poor');
else if (POOR_LIM <= dateTab && dateTab < MEDIUM_LIM) $(elem).addClass('day-medium');
else if (MEDIUM_LIM <= dateTab && dateTab < GOOD_LIM) $(elem).addClass('day-good');
}
});
}
});
$('#datepicker').prop('disabled', false);
$('#fileprev').click(function() {
if (CURR_FILES == null) return;
CURR_IDX = CURR_IDX - 1 < 0 ? CURR_FILES.length - 1 : CURR_IDX - 1;
$('#slider').slider('value', CURR_IDX + 1);
renderCurrentFile();
});
$('#filenext').click(function() {
if (CURR_FILES == null) return;
CURR_IDX = CURR_IDX + 1 >= CURR_FILES.length - 1 ? 0 : CURR_IDX + 1;
$('#slider').slider('value', CURR_IDX + 1);
renderCurrentFile();
});
$('#action-tag').click(function() {
let selectedRegions = JS9.GetRegions('selected');
if (selectedRegions.length === 1) {
$('#tag-select')[0].selectedIndex = 0;
$('#tag-modal').show();
} else if (selectedRegions.length > 1) {
alert('Please select only one region.');
} else {
alert('Please select a region.');
}
});
$('#tag-select').change(function(evt) {
let tag = $(this).val();
if (tag.trim() != '') {
JS9.ChangeRegions('selected', { text: tag, data: { tag: tag } });
saveCurrentRegions();
}
$('#tag-modal').hide();
});
$('#action-reset').click(function() {
if (INIT_CMAP == null) return;
JS9.SetColormap(INIT_CMAP.colormap, INIT_CMAP.contrast, INIT_CMAP.bias);
});
$('#action-save').click(function() {
saveCurrentRegions();
alert('All changes saved.');
});
$('#action-info').click(function() {
$('#info-modal').show();
});
$('.modal-close').click(function() {
$('.modal').hide();
});
$(window).keydown(function(evt) {
if (evt.which === 8 && JS9.GetImageData(true)) saveCurrentRegions();
if (evt.which === 27) $('.modal').hide();
});
});
function createSlider() {
let handle = $('#fits-handle');
handle.text(1);
$('#slider').slider({
value: 1,
min: 1,
max: CURR_FILES.length,
change: function(evt, ui) {
handle.text(ui.value);
CURR_IDX = ui.value - 1;
renderCurrentFile();
},
slide: function(evt, ui) {
handle.text(ui.value);
}
});
}
function getDirectories(html, regex) {
let parser = new DOMParser();
let root = parser.parseFromString(html, 'text/html');
let links = [].slice.call(root.getElementsByTagName('a'));
let hrefs = links.map(link => {
let directory = link.href.endsWith('/');
let dest = (directory ? link.href.slice(0, -1) : link.href).split('/').pop();
return dest.match(regex) ? dest : null;
}).filter(e => e != null);
return hrefs;
}
function renderCurrentFile() {
if (PREV_IDX == CURR_IDX) return;
if (CURR_FILES == null) return;
PREV_IDX = CURR_IDX;
let currentFile = CURR_FILES[CURR_IDX];
let currPath = `${CURR_DIR}/${currentFile}`;
JS9.CloseImage();
PREV_ZOOM = null;
PREV_PAN = null;
$('.JS9PluginContainer').each((idx, elem) => {
if($(elem).find('.tag-toggle, #tag-overlay').length === 0) {
$(elem).append(`<div class='tag-toggle'></div>`);
}
});
JS9.globalOpts.menuBar = ['scale'];
JS9.globalOpts.toolBar = ['box', 'circle', 'ellipse', 'zoom+', 'zoom-', 'zoomtofit'];
JS9.SetToolbar('init');
JS9.Load(currPath, {
zoom: 'ToFit',
onload: async function() {
let fileData = JSON.parse(await $.get({
url: 'regions.php',
cache: false
}, {
action: 'list',
path: currentFile
}));
if (Object.keys(fileData).length > 0) {
fileData.params = JSON.parse(fileData.params);
fileData.params.map(region => {
if (region.data.tag) region.text = region.data.tag;
return region;
});
JS9.AddRegions(fileData.params);
}
JS9.SetZoom('ToFit');
if (JS9.GetFlip() === 'none') JS9.SetFlip('x');
CENTER_PAN = JS9.GetPan();
INIT_CMAP = JS9.GetColormap();
console.log(CENTER_PAN);
$('#viewer-container').show();
$('#actions').show();
$('#filename').text(`${currentFile} (${CURR_IDX + 1}/${CURR_FILES.length})`);
$('#filetime').show();
updateSkymap(currentFile);
}
});
}
async function renderDate(date) {
$('#filename').text('Loading...');
let dateStr = moment(date).format('YYYY-MM-DD');
let yearDir = dateStr.substring(0, 4);
let monthDir = dateStr.substring(0, 7);
let parentDir = `${BASE_DIR}${yearDir}/${monthDir}/${dateStr}`
let list;
try {
list = await $.get(parentDir);
} catch (error) {
list = null;
}
let entries = getDirectories(list, /\.fits?/);
console.log(entries);
PREV_IDX = null;
CURR_IDX = 0;
CURR_DIR = parentDir;
CURR_FILES = entries;
if (list) {
$('#skytab').show().attr('src', `${parentDir}/sky.tab.thumb.png`);
createSlider();
renderCurrentFile();
} else {
$('#skytab').hide();
$('#filename').text('No data.');
$('#filetime').hide();
$('#viewer-container').hide();
$('#actions').hide();
}
}
function saveCurrentRegions() {
let regions = JS9.GetRegions('all');
let tags = JS9.GetRegions('all').map(region => region.data ? region.data.tag : null).filter(tag => tag != null);
$.get({
url: 'regions.php',
cache: false
}, {
action: 'update',
path: CURR_FILES[CURR_IDX],
tags: tags.join(','),
params: JSON.stringify(regions)
}).then(response => {
if (response.trim() !== '') {
alert(`Error saving regions: ${response}`);
}
});
}
| warnerem/pyASC | www/js/tagger.js | JavaScript | mit | 8,131 |
import React, { Component, PropTypes } from 'react'
import { Search, Grid } from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import Tag from './Tag'
import { search, setQuery, clearSearch } from '../actions/entities'
import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search'
const propTypes = {
dispatch: PropTypes.func.isRequired,
search: PropTypes.object.isRequired
}
const resultRenderer = ({ name, type, screenshots }) => {
return (
<Grid>
<Grid.Column floated="left" width={12}>
<Tag name={name} type={type} />
</Grid.Column>
<Grid.Column floated="right" width={4} textAlign="right">
<small className="text grey">{screenshots.length}</small>
</Grid.Column>
</Grid>
)
}
class GlobalSearch extends Component {
state = {
typingTimer: null
}
handleSearchChange = (e, value) => {
clearTimeout(this.state.typingTimer)
this.setState({
typingTimer: setTimeout(
() => this.handleDoneTyping(value.trim()),
DONE_TYPING_INTERVAL
)
})
const { dispatch } = this.props
dispatch(setQuery(value))
}
handleDoneTyping = value => {
if (value.length < MIN_CHARACTERS) return
const { dispatch } = this.props
dispatch(search({ query: value }))
}
handleResultSelect = (e, item) => {
const { dispatch } = this.props
const { name } = item
dispatch(clearSearch())
browserHistory.push(`/tag/${name}`)
}
render() {
const { search } = this.props
const { query, results } = search
return (
<Search
minCharacters={MIN_CHARACTERS}
onSearchChange={this.handleSearchChange}
onResultSelect={this.handleResultSelect}
resultRenderer={resultRenderer}
results={results}
value={query}
/>
)
}
}
GlobalSearch.propTypes = propTypes
export default GlobalSearch
| kingdido999/atogatari | client/src/components/GlobalSearch.js | JavaScript | mit | 1,903 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PollSystem")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PollSystem")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ee67169c-26f5-4dbd-8229-9f8ada329a77")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| vladislav-karamfilov/TelerikAcademy | ASP.NET WebForms Projects/ExamPreparation/PollSystem/PollSystem/Properties/AssemblyInfo.cs | C# | mit | 1,356 |
<<<<<<< HEAD
var xmlDoc;
var xmlloaded = false;
var _finalUrl;
/*
* input: none
* output: none
* gets zipcode from the zipcode text field
*/
function createURL() {
var zip = document.getElementById("zipcode").value;
var format = "&format=xml"
var _clientId = "&client_id=API KEY";
var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code=";
_finalUrl = _url + zip + _clientId + format;
// document.getElementById("displayURL").innerHTML = _finalUrl; // debugging
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// ready states 1-4 & status 200 = okay
// 0: uninitialized
// 1: loading
// 2: loaded
// 3: interactive
// 4: complete
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
var zip = document.getElementById("zipcode").value;
var format = "&format=xml"
var _clientId = "&client_id=API KEY";
var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code=";
_finalUrl = _url + zip + _clientId + format;
xhttp.open("GET", _finalUrl, true);
xhttp.send();
}
function myFunction(xml) {
var i, buyTickets;
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("recommendations");
for (i = 0; i < x.length; i++) {
buyTickets = x[i].getElementsByTagName("url")[2].childNodes[0].nodeValue;
}
document.getElementById("demo").innerHTML = window.open(buyTickets);
}
| pas1411/layzsunday | Lazysunday.com/XMLHandler.js | JavaScript | mit | 1,581 |
<div class="col-md-12 remove_padding">
<div class="col-md-4 right_padding ttt_pack" id="rmpd_calculate">
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock">Location</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<hr />
<div class="form-group">
<label class="form-input col-md-3">LOCATION: </label>
<div class="input-group col-md-8">
<select class="selectlocation">
<?php foreach ($locations as $location) {
?>
<option <?php if ($location_id == $location['location_id']) {
echo 'selected="selected"';
} ?> value="<?php echo $location['location_id'] ?>"><?php echo $location['location'] ?></option>
<?php
} ?>
</select>
<hr />
</div>
<div class="col-md-12">
<table class="table ">
<tr class="color_green">
<td class="add_text_tran">Expense to reach <?php echo $current_location['location'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($expenses_price_travel);?></td>
</tr>
<tr class="color-red">
<td class="add_text_tran">Expense at <?php echo $current_location['location'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($expenses_price_des);?></td>
</tr>
<tr class="color-gre">
<td class="add_text_tran">Revenue at <?php echo $current_location['location'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($income_price);?></td>
</tr>
<tr class="<?php if (($income_price - $expenses_price_des) > 0) {
echo 'color-gre';
} else {
echo 'color-red';
}?>">
<td class="add_text_tran">Current <?php if (($income_price - $expenses_price_des) > 0) {
echo 'Profit';
} else {
echo 'losses';
}?> at <?php echo $current_location['location'];?></td>
<td class="text_alginrigt">
<?php
$money = $income_price - $expenses_price_des;
$this->M_tour->convertmoney($money);?>
</td>
</tr>
</table>
</div>
<div class="col-md-12">
<div class="col-md-12 searchform_new searchform">
Tax in location:
<a onclick="addtaxmodal('create','location',0,'name','price');" class="btn">Add tax this location</a>
</div>
<div class="col-md-12 remove_padding">
<?php $taxs = $this->M_tour->getTax('location', $current_location['location_id']);
$total_after_tax = 0;
if ($taxs != false) {
echo '<hr />';
foreach ($taxs as $tax) {
?>
<div class="col-md-12 remove_padding">
<label class="col-md-4"><?php echo $tax['name']; ?> :</label>
<div class="col-md-2 remove_padding searchform_new">
<input class="bnt new_style_tax" readonly="true" type="text" value="<?php echo $tax['tax']; ?>" />
</div>
<div class="col-md-4">
<?php $show_tax = $money * $tax['tax'] / 100;
$total_after_tax = $total_after_tax + $show_tax;
$this->M_tour->convertmoney($show_tax); ?>
</div>
<div class="col-md-2 remove_padding">
<a href="javascript:void(0)" onclick="addtaxmodal('edit','location',<?php echo $tax['id'] ?>,'<?php echo $tax['name']; ?>','<?php echo $tax['tax']; ?>');">Edit</a>
<a onclick="return confirm('Are you sure you want to delete this item?');" href="<?php echo base_url('') ?>the_total_tour/delete_tax/<?php echo $tour['tour_id']; ?>/<?php echo $current_location['location_id']; ?>/<?php echo $tax['id'] ?>">Delete</a>
</div>
</div>
<?php
}
}
?>
</div>
<div class="col-md-12">
<table class="table ">
<tr class="<?php if (($income_price - $expenses_price_des) > 0) {
echo 'color-gre';
} else {
echo 'color-red';
}?>">
<td class="add_text_tran">Current <?php if (($income_price - $expenses_price_des) > 0) {
echo 'Profit';
} else {
echo 'losses';
}?> at <?php echo $current_location['location'];?></td>
<td class="text_alginrigt">
<?php
$this->M_tour->convertmoney($money - $total_after_tax);?>
</td>
</tr>
</table>
</div>
</div>
</div>
<hr />
</div>
</div>
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock">All location of tour</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<table class="table">
<?php
$total = 0;
foreach ($location_caculates as $location_caculate) {
$total = $total + $location_caculate['tax_location_result']; ?>
<tr class="color_green">
<td class="add_text_tran">Total at <?php echo $location_caculate['location']; ?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($location_caculate['tax_location_result']); ?></td>
</tr>
<?php
} ?>
<tr class="color-gre">
<td class="add_text_tran">Total before tax in tour <?php echo $tour['tour'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($total);?></td>
</tr>
<?php
$taxs = $this->M_tour->getTax('tour', $tour['tour_id']);
$total_money_tax = 0;
if ($taxs != false) {
foreach ($taxs as $tax) {
$total_money_tax = $total_money_tax + $total * $tax['tax'] / 100;
}
$total_money = $total - $total_money_tax;
} else {
$total_money = $total;
}
?>
</table>
</div>
<div class="col-md-12 ">
<div class="col-md-12 searchform_new searchform">
Tax in tour:
<a onclick="addtaxmodal('create','tour',0,'name','price');" class="btn">Add tax this tour</a>
</div>
<div class="col-md-12 remove_padding">
<?php $taxs = $this->M_tour->getTax('tour', $tour['tour_id']);
if ($taxs != false) {
echo '<hr />';
foreach ($taxs as $tax) {
?>
<div class="col-md-12 remove_padding">
<label class="col-md-4"><?php echo $tax['name']; ?> :</label>
<div class="col-md-2 remove_padding searchform_new">
<input class="bnt new_style_tax" readonly="true" type="text" value="<?php echo $tax['tax']; ?>" />
</div>
<div class="col-md-4">
<?php $this->M_tour->convertmoney($total_money_tax); ?>
</div>
<div class="col-md-2 remove_padding">
<a href="javascript:void(0)" onclick="addtaxmodal('edit','tour',<?php echo $tax['id'] ?>,'<?php echo $tax['name']; ?>','<?php echo $tax['tax']; ?>');">Edit</a>
<a onclick="return confirm('Are you sure you want to delete this item?');" href="<?php echo base_url('') ?>the_total_tour/delete_tax/<?php echo $tour['tour_id']; ?>/<?php echo $current_location['location_id']; ?>/<?php echo $tax['id'] ?>">Delete</a>
</div>
</div>
<?php
}
}
?>
</div>
</div>
<div class="col-md-12 remove_padding">
<table class="table">
<tr class="color-gre">
<td class="add_text_tran">Total after tax in tour <?php echo $tour['tour'];?></td>
<td class="text_alginrigt"><?php $this->M_tour->convertmoney($total_money);?></td>
</tr>
</table>
</div>
</div>
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock">LIST MEMBER</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<ul>
<li><a href="<?php echo base_url('the_total_tour/caculate').'/'.$check_member['tour_id'].'/'.$location_id;?>">All member</a></li>
<?php foreach ($members as $member) {
if ($member['tm_active'] == 1) {
?>
<li><a href="<?php echo base_url('the_total_tour/caculate').'/'.$check_member['tour_id'].'/'.$location_id.'/'.$member['user_id']; ?>"><?php echo $member['firstname'].' '.$member['lastname']; ?></a></li>
<?php
} else {
?>
<li><?php echo $member['name']; ?></li>
<?php
}
} ?>
<li></li>
</ul>
</div>
</div>
</div>
<div class="col-md-8 left_padding ttt_pack">
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock target2">Expense at <?php echo $current_location['location']; ?>
<?php if ($this->uri->segment(5)) {
echo 'for '.$user_data_select['firstname'].' '.$user_data_select['lastname'];
} ?>
</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<?php if ($check_member['manager_cacula']) {
?>
<div class="col-md-12 remove_padding searchform_new">
<a onclick="addcaculate('expenses','at destination');" class="btn">Add Expense</a>
</div>
<?php
}?>
<table class="table">
<tr>
<th>Name</th>
<th>Amount</th>
<th>Price</th>
<th>Add for</th>
<th>Date</th>
<th>Receipt</th>
<?php if ($check_member['manager_cacula']) {
?><th>Action</th><?php
}?>
</tr>
<?php
$total = 0;
foreach ($expenses as $expense) {
if ($expense['expense_type'] == 'at destination') {
$total = $total + $expense['expense_price'] * $expense['amount']; ?>
<tr style="color: <?php echo $expense['color_front']; ?>; <?php if ($check_member['id'] == $expense['user_m_id']) {
echo 'background: #ccc;';
} ?> ">
<td><?php echo $expense['expense_name']; ?></td>
<td><?php echo $expense['amount']; ?></td>
<td><?php $this->M_tour->convertmoney($expense['expense_price']); ?></td>
<td><?php echo $expense['firstname'].' '.$expense['lastname']; ?></td>
<td><?php echo date('m-d-Y', strtotime($expense['date'])); ?></td>
<td><img src="<?php echo base_url()."/uploads/".$expense['user_id']."/photo/banner_events/".$expense['receipt']; ?>"width="60" height="60"></td>
<?php if ($check_member['manager_cacula']) {
?>
<td class="searchform formintable">
<input type="hidden" class="save_id" value="<?php echo $expense['expense_id']; ?>" />
<input type="hidden" class="save_name" value="<?php echo $expense['expense_name']; ?>" />
<input type="hidden" class="expense_type" value="at destination" />
<input type="hidden" class="expense_amount" value="<?php echo $expense['amount']; ?>" />
<input type="hidden" class="expense_date" value="<?php echo $expense['date']; ?>" />
<input type="hidden" class="save_price" value="<?php echo $expense['expense_price']; ?>" />
<input type="hidden" class="receipt" value="<?php echo $expense['receipt']; ?>" />
<input type="hidden" class="userId" value="<?php echo $expense['user_id']; ?>" />
<a class="bnt" onclick="show_edit_member($(this),'expenses')" >Edit</a>
<a class="bnt" onclick="delete_price($(this),'<?php echo $expense['expense_name']; ?>','expenses')">Delete</a>
</td>
<?php
} ?>
</tr>
<?php
}
}
?>
<tr>
<td colspan="5"><span class="total-value color-red">Total: <?php $this->M_tour->convertmoney($total);?></span></td>
</tr>
</table>
</div>
</div>
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock target3">Revenue at <?php echo $current_location['location']; ?>
<?php if ($this->uri->segment(5)) {
echo 'for '.$user_data_select['firstname'].' '.$user_data_select['lastname'];
} ?>
</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<?php if ($check_member['manager_cacula']) {
?>
<div class="col-md-12 remove_padding searchform_new">
<a onclick="addcaculate('income','none');" class="btn">Add Revenue</a>
</div>
<?php
}?>
<table class="table">
<tr>
<th>Name</th>
<th>Amount</th>
<th>Price</th>
<th>Add for</th>
<th>Date</th>
<?php if ($check_member['manager_cacula']) {
?><th>Action</th><?php
}?>
</tr>
<?php
$total = 0;
foreach ($incomes as $income) {
$total = $total + $income['income_price'] * $income['amount']; ?>
<tr style="color: <?php echo $income['color_front']; ?>; <?php if ($check_member['id'] == $income['user_m_id']) {
echo 'background: #ccc;';
} ?> ">
<td><?php echo $income['income_name']; ?></td>
<td><?php echo $income['amount']; ?></td>
<td><?php $this->M_tour->convertmoney($income['income_price']); ?></td>
<td><?php echo $income['firstname'].' '.$income['lastname']; ?></td>
<td><?php echo date('m-d-Y', strtotime($income['date'])); ?></td>
<?php if ($check_member['manager_cacula']) {
?>
<td class="searchform formintable">
<input type="hidden" class="expense_amount" value="<?php echo $income['amount']; ?>" />
<input type="hidden" class="expense_date" value="<?php echo $income['date']; ?>" />
<input type="hidden" class="save_id" value="<?php echo $income['income_id']; ?>" />
<input type="hidden" class="save_name" value="<?php echo $income['income_name']; ?>" />
<input type="hidden" class="save_price" value="<?php echo $income['income_price']; ?>" />
<a class="bnt" onclick="show_edit_member($(this),'income')" >Edit</a>
<a class="bnt" onclick="delete_price($(this),'<?php echo $income['income_name']; ?>','income')">Delete</a>
</td>
<?php
} ?>
</tr>
<?php
}
?>
<tr>
<td colspan="5"><span class="total-value color-gre">Total: <?php $this->M_tour->convertmoney($total);?></span></td>
</tr>
</table>
</div>
</div>
<div class="row col-md-12 header_new_style">
<h2 class="tt text_caplock target1">Expense to reach <?php echo $current_location['location']; ?>
<?php if ($this->uri->segment(5)) {
echo 'for '.$user_data_select['firstname'].' '.$user_data_select['lastname'];
} ?>
</h2>
<span class="liner_landing"></span>
<div class="col-md-12 remove_padding">
<?php if ($check_member['manager_cacula']) {
?>
<div class="col-md-12 remove_padding searchform_new">
<a onclick="addcaculate('expenses','travel');" class="btn">Add Expense to reach</a>
</div>
<?php
}?>
<table class="table">
<tr>
<th>Name</th>
<th>Amount</th>
<th>Price</th>
<th>Add for</th>
<th>Date</th>
<?php if ($check_member['manager_cacula']) {
?><th>Action</th><?php
}?>
</tr>
<?php
$total = 0;
foreach ($expenses as $expense) {
if ($expense['expense_type'] == 'travel') {
$total = $total + $expense['expense_price'] * $expense['amount']; ?>
<tr style="color: <?php echo $expense['color_front']; ?>; <?php if ($check_member['id'] == $expense['user_m_id']) {
echo 'background: #ccc;';
} ?> ">
<td><?php echo $expense['expense_name']; ?></td>
<td><?php echo $expense['amount']; ?></td>
<td><?php $this->M_tour->convertmoney($expense['expense_price']); ?></td>
<td><?php echo $expense['firstname'].' '.$expense['lastname']; ?></td>
<td><?php echo date('m-d-Y', strtotime($expense['date'])); ?></td>
<?php if ($check_member['manager_cacula']) {
?>
<td class="searchform formintable">
<input type="hidden" class="expense_amount" value="<?php echo $expense['amount']; ?>" />
<input type="hidden" class="expense_date" value="<?php echo $expense['date']; ?>" />
<input type="hidden" class="save_id" value="<?php echo $expense['expense_id']; ?>" />
<input type="hidden" class="save_name" value="<?php echo $expense['expense_name']; ?>" />
<input type="hidden" class="save_price" value="<?php echo $expense['expense_price']; ?>" />
<input type="hidden" class="expense_type" value="travel" />
<a class="bnt" onclick="show_edit_member($(this),'expenses')" >Edit</a>
<a class="bnt" onclick="delete_price($(this),'<?php echo $expense['expense_name']; ?>','expenses')">Delete</a>
</td>
<?php
} ?>
</tr>
<?php
}
}
?>
<tr>
<td colspan="5"><span class="total-value">Total: <?php $this->M_tour->convertmoney($total);?></span></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade new_modal_style" id="edit-member-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="tt edit_text">Edit</h4>
<span class="liner"></span>
</div>
<form class="avatar-form" action="<?php echo base_url(); ?>members/update_price" enctype="multipart/form-data" method="post">
<div class="modal-body">
<div class="col-md-12 remove_padding">
<input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>" />
<input type="hidden" name="price_id" class="price_id_data" value="price_id" />
<input type="hidden" name="tour_id" class="tour_id_data" value="<?php echo $tour_id;?>"/>
<input type="hidden" name="type" class="type_data" value="expenses"/>
<input type="hidden" name="expense_type" class="expense_type_edit" value="travel"/>
<input type="hidden" name="location" class="location" value="<?php echo $current_location['location_id'];?>"/>
<div class="form-group">
<label class="form-input col-md-3">Name</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_name" name="change_name" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Price</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_price" name="change_price" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Amount</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_amount_edit" value="1" name="change_amount" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Date</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_date_edit" value="<?php echo date('m/d/Y');?>" id="change_date" name="change_date" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Receipt</label>
<div class="input-group col-md-8">
<div class="zoom_img">
<img src="<?php echo base_url()."/uploads/"; ?>" class="receiptImg col-md-8" id="thumb">
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer searchform">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default avatar-save">Save</button>
</div>
</form>
</div>
</div>
</div><!-- /.modal -->
<div class="modal fade new_modal_style" id="add-caculate-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="tt edit_text_model">Add </h4>
<span class="liner"></span>
</div>
<?php if(count($expensePer) > 0 && $expensePer['add_expense'] == 1): ?>
<form class="avatar-form" action="<?php echo base_url(); ?>members/addcaculate" enctype="multipart/form-data" method="post">
<div class="modal-body">
<div class="col-md-12 remove_padding">
<input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>" />
<input type="hidden" name="type" class="type_data_add" value="expenses"/>
<input type="hidden" name="expense_type" class="expense_type_add" value="travel"/>
<input type="hidden" name="tour_id" value="<?php echo $tour['tour_id']; ?>"/>
<input type="hidden" name="location" class="location_add" value="<?php echo $current_location['location_id'];?>"/>
<div class="form-group">
<label class="form-input col-md-3">Name</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_name1" name="change_name" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Price</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_price1" name="change_price" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Amount</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_amount" value="1" name="change_amount" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Date</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_date" value="<?php echo date('m/d/Y');?>" id="change_date1" name="change_date" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Upload Receipt</label>
<div class="input-group col-md-8">
<input type="file" name="receipt" id="receiptUp">
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer searchform">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default avatar-save">Save</button>
</div>
</form>
<?php else: ?>
<p style="text-align:center">You don't have persmission to add expense.</p>
<?php endif; ?>
</div>
</div>
</div><!-- /.modal -->
<div class="modal fade new_modal_style" id="add-tax-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="tt edit_text_model">Add tax</h4>
<span class="liner"></span>
</div>
<form class="avatar-form" action="<?php echo base_url(); ?>more_ttt/addtaxcaculate" enctype="multipart/form-data" method="post">
<div class="modal-body">
<div class="col-md-12 remove_padding">
<input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>" />
<input type="hidden" name="tour_id" value="<?php echo $tour['tour_id']; ?>"/>
<input type="hidden" name="location" class="location_add" value="<?php echo $current_location['location_id'];?>"/>
<input type="hidden" name="type" class="type_tax" value="location"/>
<input type="hidden" name="type_data" class="type_data" value="create" />
<input type="hidden" name="tax_id" class="tax_id" value="0" />
<div class="form-group">
<label class="form-input col-md-3">Name tax</label>
<div class="input-group col-md-8">
<input type="text" class="form-control change_name_tax" name="change_name" />
</div>
</div>
<div class="form-group disable_div">
<label class="form-input col-md-3">Tax</label>
<div class="input-group col-md-8">
<input type="number" min="0.01" step="0.01" max="2500" value="00.00" class="form-control change_price_tax" name="change_price" />
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer searchform">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default avatar-save">Save</button>
</div>
</form>
</div>
</div>
</div><!-- /.modal -->
<script type="text/javascript">
var value = $(".<?php echo $this->session->userdata('target'); ?>").offset().top - 100;
var domain = "<?php echo base_url(); ?>";
$(".selectlocation").change(function(){
location_id = $(this).val();
<?php
if ($this->uri->segment(5)) {
?>
location.href = "<?php echo base_url('the_total_tour/caculate/').'/'.$tour_id.'/'; ?>"+location_id+'/'+<?php echo $this->uri->segment(5); ?>;
<?php
} else {
?>
location.href = "<?php echo base_url('the_total_tour/caculate/').'/'.$tour_id.'/'; ?>"+location_id;
<?php
}
?>
});
var delete_price_url = '<?php echo base_url('members/delete_price') ?>';
var base_url = '<?php echo base_url() ?>';
var records_per_page = '<?php echo $this->security->get_csrf_hash(); ?>';
var tour_id ='<?php echo $tour_id;?>';
</script>
<script src="<?php echo base_url();?>assets/js/detail_pages/ttt/caculate.js"></script>
<link href='<?php echo base_url() ?>assets/dist/css/alertify.default.css' rel='stylesheet' />
<link href='<?php echo base_url() ?>assets/dist/css/alertify.core.css' rel='stylesheet' />
<link href='<?php echo base_url() ?>assets/css/ttt_styles.css' rel='stylesheet' />
<link href="<?php echo base_url(); ?>assets/map/css/bootstrap-colorpicker.min.css" rel="stylesheet"/>
<script src="<?php echo base_url('assets/dist/js/alertify.min.js');?>"></script>
<script src="<?php echo base_url('assets/dist/js/bootstrap-datepicker.min.js');?>"></script>
<script src="<?php echo base_url(); ?>assets/map/js/bootstrap-colorpicker.min.js"></script>
| akashbachhania/jeet99 | application/views/ttt/caculate.php | PHP | mit | 37,369 |
import { createElement } from 'react'
import omit from 'lodash/omit'
import { useSpring, animated } from '@react-spring/web'
import { useTheme, useMotionConfig } from '@nivo/core'
import { NoteSvg } from './types'
export const AnnotationNote = <Datum,>({
datum,
x,
y,
note,
}: {
datum: Datum
x: number
y: number
note: NoteSvg<Datum>
}) => {
const theme = useTheme()
const { animate, config: springConfig } = useMotionConfig()
const animatedProps = useSpring({
x,
y,
config: springConfig,
immediate: !animate,
})
if (typeof note === 'function') {
return createElement(note, { x, y, datum })
}
return (
<>
{theme.annotations.text.outlineWidth > 0 && (
<animated.text
x={animatedProps.x}
y={animatedProps.y}
style={{
...theme.annotations.text,
strokeLinejoin: 'round',
strokeWidth: theme.annotations.text.outlineWidth * 2,
stroke: theme.annotations.text.outlineColor,
}}
>
{note}
</animated.text>
)}
<animated.text
x={animatedProps.x}
y={animatedProps.y}
style={omit(theme.annotations.text, ['outlineWidth', 'outlineColor'])}
>
{note}
</animated.text>
</>
)
}
| plouc/nivo | packages/annotations/src/AnnotationNote.tsx | TypeScript | mit | 1,549 |
package pl.mmorpg.prototype.client.exceptions;
public class UnknownSpellException extends GameException
{
public UnknownSpellException(String identifier)
{
super(identifier);
}
public UnknownSpellException(Class<?> type)
{
super(type.getName());
}
}
| Pankiev/MMORPG_Prototype | Client/core/src/pl/mmorpg/prototype/client/exceptions/UnknownSpellException.java | Java | mit | 262 |
import { ILogger, getLogger } from './loggers';
import { CancellationToken, ICancellationToken } from '../util/CancellationToken';
import { Step } from './Step';
import { ModuleLoader } from './ModuleLoader';
import * as _ from 'underscore';
import { Guid } from '../util/Guid';
import { InjectorLookup, Module, ModuleRepository } from './Modules';
import { IScope, Scope } from './Scope';
import validateScriptDefinition from './scriptDefinitionValidator';
import * as helpers from '../util/helpers';
import './modules/assert';
import './modules/async';
import './modules/conditional';
import './modules/http';
import './modules/json';
import './modules/loop';
import './modules/math';
import './modules/misc';
import './modules/stats';
import './modules/timer';
import './modules/wait';
const YAML = require('pumlhorse-yamljs');
class ScriptOptions {
logger: ILogger;
}
export interface IScript {
run(context: any, cancellationToken?: ICancellationToken): Promise<any>;
addFunction(name: string, func: Function): void;
addModule(moduleDescriptor: string | Object): void;
id: string;
name: string;
}
export interface IScriptDefinition {
name: string;
description?: string;
modules?: any[];
functions?: Object;
expects?: string[];
steps: any[];
cleanup?: any[];
}
export class Script implements IScript {
id: string;
name: string;
private internalScript: IScriptInternal;
private static readonly DefaultModules = ['assert', 'async', 'conditional', 'json', 'loop', 'math', 'misc', 'timer', 'wait', 'http = http'];
public static readonly StandardModules = Script.DefaultModules.concat(['stats']);
constructor(private scriptDefinition: IScriptDefinition, private scriptOptions?: ScriptOptions) {
validateScriptDefinition(this.scriptDefinition);
this.id = new Guid().value;
this.name = scriptDefinition.name;
if (this.scriptOptions == null) {
this.scriptOptions = new ScriptOptions();
}
if (this.scriptOptions.logger == null) {
this.scriptOptions.logger = getLogger();
}
this.internalScript = new InternalScript(this.id, this.scriptOptions);
}
static create(scriptText: string, scriptOptions?: ScriptOptions): Script {
const scriptDefinition = YAML.parse(scriptText);
return new Script(scriptDefinition, scriptOptions);
}
async run(context?: any, cancellationToken?: ICancellationToken): Promise<any> {
if (cancellationToken == null) cancellationToken = CancellationToken.None;
this.evaluateExpectations(context);
this.loadModules();
this.loadFunctions();
this.loadCleanupSteps();
const scope = new Scope(this.internalScript, context);
try {
await this.internalScript.runSteps(this.scriptDefinition.steps, scope, cancellationToken);
return scope;
}
finally {
await this.runCleanupTasks(scope, cancellationToken);
}
}
addFunction(name: string, func: Function): void {
this.internalScript.functions[name] = func;
}
addModule(moduleDescriptor: string | Object) {
const moduleLocator = ModuleLoader.getModuleLocator(moduleDescriptor);
const mod = ModuleRepository.lookup[moduleLocator.name];
if (mod == null) throw new Error(`Module "${moduleLocator.name}" does not exist`);
if (moduleLocator.hasNamespace) {
helpers.assignObjectByString(this.internalScript.modules, moduleLocator.namespace, mod.getFunctions());
}
else {
_.extend(this.internalScript.modules, mod.getFunctions());
}
_.extend(this.internalScript.injectors, mod.getInjectors())
}
private evaluateExpectations(context: any) {
if (this.scriptDefinition.expects == null) return;
const missingValues = _.difference(this.scriptDefinition.expects.map(m => m.toString()), _.keys(context));
if (missingValues.length > 0) {
throw new Error(missingValues.length > 1
? `Expected values "${missingValues.join(', ')}", but they were not passed`
: `Expected value "${missingValues[0]}", but it was not passed`)
}
}
private loadModules() {
const modules = Script.DefaultModules.concat(this.scriptDefinition.modules == null
? []
: this.scriptDefinition.modules)
for (let i = 0; i < modules.length; i++) {
this.addModule(modules[i]);
}
}
private loadFunctions() {
this.addFunction('debug', (msg) => this.scriptOptions.logger.debug(msg));
this.addFunction('log', (msg) => this.scriptOptions.logger.log(msg));
this.addFunction('warn', (msg) => this.scriptOptions.logger.warn(msg));
this.addFunction('error', (msg) => this.scriptOptions.logger.error(msg));
const functions = this.scriptDefinition.functions;
if (functions == null) {
return;
}
for(let name in functions) {
this.addFunction(name, this.createFunction(functions[name]));
}
}
private createFunction(val) {
if (_.isString(val)) return new Function(val)
function construct(args) {
function DeclaredFunction(): void {
return Function.apply(this, args);
}
DeclaredFunction.prototype = Function.prototype;
return new DeclaredFunction();
}
return construct(val)
}
private loadCleanupSteps() {
if (this.scriptDefinition.cleanup == null) {
return;
}
for (let i = 0; i < this.scriptDefinition.cleanup.length; i++) {
this.internalScript.cleanup.push(this.scriptDefinition.cleanup[i]);
}
}
private async runCleanupTasks(scope: Scope, cancellationToken: ICancellationToken): Promise<any> {
if (this.internalScript.cleanup == null) {
return;
}
for (let i = 0; i < this.internalScript.cleanup.length; i++) {
const task = this.internalScript.cleanup[i];
try {
await this.internalScript.runSteps([task], scope, cancellationToken);
}
catch (e) {
this.scriptOptions.logger.error(`Error in cleanup task: ${e.message}`);
}
}
}
}
export interface IScriptInternal {
modules: Module[];
functions: {[name: string]: Function};
injectors: InjectorLookup;
steps: any[];
cleanup: any[];
emit(eventName: string, eventInfo: any);
addCleanupTask(task: any, atEnd?: boolean);
getModule(moduleName: string): any;
id: string;
runSteps(steps: any[], scope: IScope, cancellationToken?: ICancellationToken): Promise<any>;
}
class InternalScript implements IScriptInternal {
id: string;
modules: Module[];
injectors: InjectorLookup;
functions: {[name: string]: Function};
steps: any[];
cleanup: any[];
private cancellationToken: ICancellationToken;
private isEnded: boolean = false;
constructor(id: string, private scriptOptions: ScriptOptions) {
this.id = id;
this.modules = [];
this.injectors = {
'$scope': (scope: IScope) => scope,
'$logger': () => this.scriptOptions.logger
};
this.functions = {
'end': () => { this.isEnded = true; }
};
this.steps = [];
this.cleanup = [];
}
emit(): void {
}
addCleanupTask(task: any, atEnd?: boolean): void {
if (atEnd) this.cleanup.push(task);
else this.cleanup.splice(0, 0, task);
}
getModule(moduleName: string): any {
return this.modules[moduleName];
}
async runSteps(steps: any[], scope: IScope, cancellationToken: ICancellationToken): Promise<any> {
if (cancellationToken != null) {
this.cancellationToken = cancellationToken;
}
if (steps == null || steps.length == 0) {
this.scriptOptions.logger.warn('Script does not contain any steps');
return;
}
_.extend(scope, this.modules, this.functions);
for (let i = 0; i < steps.length; i++) {
if (this.cancellationToken.isCancellationRequested || this.isEnded) {
return;
}
await this.runStep(steps[i], scope);
}
}
private async runStep(stepDefinition: any, scope: IScope) {
if (_.isFunction(stepDefinition)) {
// If we programatically added a function as a step, just shortcut and run it
return stepDefinition.call(scope);
}
let step: Step;
const lineNumber = stepDefinition.getLineNumber == null ? null : stepDefinition.getLineNumber();
if (_.isString(stepDefinition)) {
step = new Step(stepDefinition, null, scope, this.injectors, lineNumber);
}
else {
const functionName = _.keys(stepDefinition)[0];
step = new Step(functionName, stepDefinition[functionName], scope, this.injectors, lineNumber);
}
await step.run(this.cancellationToken);
}
} | pumlhorse/pumlhorse | src/script/Script.ts | TypeScript | mit | 9,364 |
from django.db import models
from django.core.urlresolvers import reverse
class Software(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
def get_absolute_url(self):
return reverse('software_edit', kwargs={'pk': self.pk})
| htlcnn/pyrevitscripts | HTL.tab/Test.panel/Test.pushbutton/keyman/keyman/keys/models.py | Python | mit | 300 |
#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
| wikimedia/pywikibot-core | scripts/djvutext.py | Python | mit | 6,822 |
// Copyright 2015 LastLeaf, LICENSE: github.lastleaf.me/MIT
'use strict';
var fs = require('fs');
var fse = require('fs-extra');
var async = require('async');
var User = fw.module('/db_model').User;
var exports = module.exports = function(conn, res, args){
User.checkPermission(conn, 'admin', function(perm){
if(!perm) return res.err('noPermission');
res.next();
});
};
exports.list = function(conn, res){
// read site list
var sitesDir = conn.app.config.app.siteRoot + '/xbackup/';
fs.readdir(sitesDir, function(err, files){
if(err) return res.err('system');
var sites = files.sort();
// list available backup files
var details = [];
var local = null;
async.eachSeries(sites, function(site, cb){
var siteDir = sitesDir + site;
if(site !== 'local' && site.slice(-5) !== '.site') return cb();
fs.readdir(siteDir, function(err, files){
if(err) return cb('system');
var zips = [];
for(var i=0; i<files.length; i++) {
var match = files[i].match(/^(.*?)\.xbackup\.zip(\.enc|)$/);
if(match) {
var ft = match[1].replace(/^([0-9]+)-([0-9]+)-([0-9]+)_([0-9]+)-([0-9]+)-([0-9]+)/, function(m, m1, m2, m3, m4, m5, m6){
return m1 + '-' + m2 + '-' + m3 + ' ' + m4 + ':' + m5 + ':' + m6;
});
zips.push({
file: files[i],
timeString: ft
});
}
}
if(site === 'local') {
local = zips;
} else details.push({
domain: site.slice(0, -5),
files: zips
});
cb();
});
}, function(err){
if(err) return res.err('system');
res({
local: local,
sites: details
});
});
});
};
exports.modify = function(conn, res, args){
var addSites = String(args.add).match(/\S+/g) || [];
var removeSites = String(args.remove).match(/\S+/g) || [];
async.eachSeries(removeSites, function(site, cb){
var dir = conn.app.config.app.siteRoot + '/xbackup/' + site + '.site';
fse.remove(dir, function(){
cb();
});
}, function(){
async.eachSeries(addSites, function(site, cb){
var dir = conn.app.config.app.siteRoot + '/xbackup/' + site + '.site';
fs.mkdir(dir, function(){
cb();
});
}, function(){
res();
});
});
};
| LastLeaf/LightPalette | plugins/xbackup/rpc/sites.js | JavaScript | mit | 2,163 |
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.jonasrottmann.realmbrowser.helper;
import android.content.Context;
import android.support.annotation.RestrictTo;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
// This is mandatory if we're assigning the behavior straight from XML
super();
}
@Override
public boolean onStartNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child, final View directTargetChild, final View target, final int nestedScrollAxes) {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child, final View target, final int dxConsumed, final int dyConsumed, final int dxUnconsumed,
final int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
// User scrolled down and the FAB is currently visible -> hide the FAB
child.hide(new FloatingActionButton.OnVisibilityChangedListener() {
@Override
public void onHidden(FloatingActionButton fab) {
// Workaround for bug in support libs (http://stackoverflow.com/a/41641841/2192848)
super.onHidden(fab);
fab.setVisibility(View.INVISIBLE);
}
});
} else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
// User scrolled up and the FAB is currently not visible -> show the FAB
child.show();
}
}
} | jonasrottmann/realm-browser | realm-browser/src/main/java/de/jonasrottmann/realmbrowser/helper/ScrollAwareFABBehavior.java | Java | mit | 2,812 |
package edu.brown.cs.pianoHeroFiles;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class PianoHeroFileHandler {
public void doFileHandling() {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
File dir = new File("pianoHeroFiles/songImages/");
File actualFile = new File(dir, "hey");
File f = new File("C:\\pianoHeroFiles\\songImages\\kiwiCover.png");
System.out.println(f.getName().toString());
File newDir = new File("pianoHeroFiles/songImages/new/");
File newFile = new File(f, "kiwi2.png");
// System.out.println(actualFile);
writer.write("something");
writeFile("pianoHeroFiles/test.txt", "something, brah.");
Set<File> allMp3s = new HashSet<File>();
File mp3Dir = new File("pianoHeroFiles/songs/");
getAllFilesAndFolder(mp3Dir, allMp3s);
for (File fm : allMp3s) {
System.out.println("song:");
System.out.println(fm);
if (!fm.isDirectory()) {
File dest = new File(fm.getParentFile().toString(), "new"
+ fm.getName());
copyFile(fm, dest);
}
}
} catch (IOException e) {
System.err.println("ERROR: error saving the file");
e.printStackTrace();
}
}
/**
* Saves an image to file directory and returns its saved path as a string
*
* @param image
* file
* @return path saved
*/
public static String saveImage(String imageName) {
try {
File image = new File("Images/" + imageName);
// File imageDir = new File("pianoHeroFiles/songImages/");
File imageDir = new File("src/main/resources/static/img/");
File saveDir = new File("../img/");
File dest = new File(imageDir, ""
+ image.getName());
File savedDir = new File(saveDir, ""
+ image.getName());
copyFile(image, dest);
return savedDir.getPath();
} catch (IOException e) {
System.err.println("ERROR: error saving image");
}
return null;
}
/**
* Saves an mp3 file directory and returns its saved path as a string
*
* @param mp3
* file
* @return path saved
*/
public static String saveMp3(String mp3Name) {
try {
File mp3 = new File("Songs/" + mp3Name);
// File songsDir = new File("pianoHeroFiles/songs/");
File songsDir = new File("src/main/resources/static/songs/");
File saveDir = new File("../songs/");
File dest = new File(songsDir, ""
+ mp3.getName());
File saveDest = new File(saveDir, ""
+ mp3.getName());
copyFile(mp3, dest);
return saveDest.getPath();
} catch (IOException e) {
System.err.println("ERROR: error saving image");
}
return null;
}
/**
* Saves the 1d-array boolean of keystrokes for a given song id.
*
* @param keyStrokes
* : 1d-array of booleans
* @param songId
* : int, the song id
* @return String of the path where the keystrokes file was saved.
*/
public static String saveSongKeystrokes(boolean[] keyStrokes, int songId) {
String path = "pianoHeroFiles/songKeyStrokes/";
String keyStrokesID = songId + "_keyStrokes.txt";
String keyStrokesPath = path + keyStrokesID;
try (PrintWriter writer = new PrintWriter(keyStrokesPath, "UTF-8")) {
String line = "";
// this is for the fake, testing songs.
if (keyStrokes == null) {
System.out.println("FAKEEEEE");
line += "1000100100010100010101";
}
for (int i = 0; i < keyStrokes.length; i++) {
String add = keyStrokes[i] ? "1" : "0";
line += add;
}
writer.println(line);
writer.close();
} catch (IOException e) {
System.err
.println("ERROR: error saving keystrokes for songId: " + songId);
}
return keyStrokesPath;
}
/**
* Saves a 2d-array boolean of keystrokes for a given song id.
*
* @param keyStrokes
* : 2d-array of booleans
* @param songId
* : int, the song id
* @return String of the path where the keystrokes file was saved.
*/
public static String save2DSongKeystrokes(boolean[][] keyStrokes, int songId) {
String path = "pianoHeroFiles/songKeyStrokes/";
String keyStrokesID = songId + "_keyStrokes.txt";
String keyStrokesPath = path + keyStrokesID;
try (PrintWriter writer = new PrintWriter(keyStrokesPath, "UTF-8")) {
for (int i = 0; i < keyStrokes.length; i++) {
String line = "";
for (int j = 0; j < keyStrokes[i].length; j++) {
String add = keyStrokes[i][j] ? "1" : "0";
line += add;
}
writer.println(line);
}
writer.close();
} catch (IOException e) {
System.err
.println("ERROR: error saving keystrokes for songId: " + songId);
}
return keyStrokesPath;
}
/**
* Converts a 1d array of booleans to a 2d array of booleans.
*
* @param array
* : the initial 1d array
* @param length
* : the length of the partitions.
* @return the converted 2d array.
*/
public static boolean[][] convert1DBooleansTo2D(boolean[] array, int length) {
boolean[][] boolean2d = new boolean[length][array.length / length];
for (int i = 0; i < length; i++) {
for (int j = 0; j < array.length / length; j++) {
boolean2d[i][j] = array[j + i * length];
}
}
return boolean2d;
}
/**
* Converts a 2d array of booleans to a 1d array of booleans.
*
* @param array
* : the initial 2d array
* @return the converted 1d array.
*/
public static boolean[] convert2DBooleansTo1D(boolean[][] boolean2D) {
boolean[] boolean1D = new boolean[boolean2D.length * boolean2D[0].length];
for (int i = 0; i < boolean2D.length; i++) {
for (int j = 0; j < boolean2D[i].length; j++) {
assert (boolean2D[i].length == boolean2D[0].length);
boolean1D[j + i * boolean2D.length] = boolean2D[i][j];
}
}
return boolean1D;
}
/**
* Returns a file from a given string path
*
* @param path
* string representing the file path
* @return the File in the path
*/
public static File getFileFromPath(String path) {
File file = new File(path);
return file;
}
/**
* Saves all the files and folders in a set, for a given initial folder.
*
* @param folder
* the initial folder to look all files for.
* @param all
* the set of files to save on
*/
public static void getAllFilesAndFolder(File folder, Set<File> all) {
all.add(folder);
if (folder.isFile()) {
return;
}
for (File file : folder.listFiles()) {
if (file.isFile()) {
all.add(file);
}
if (file.isDirectory()) {
getAllFilesAndFolder(file, all);
}
}
}
/**
* Gets the file of the strokes and converts it to a 1d boolean array to
* return
*
* @param fileName
* the file name of the keystrokes
* @return the 1d array of the strokes
*/
public static boolean[] getStrokesArray(String fileName) {
// This will reference one line at a time
String line = null;
// FileReader reads text files in the default encoding.
try (FileReader fileReader =
new FileReader(fileName)) {
// It's good to always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
int length = 0;
ArrayList<Boolean> results = new ArrayList<Boolean>();
while ((line = bufferedReader.readLine()) != null) {
if (line != null) {
length = line.length();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '0') {
results.add(false);
} else if (line.charAt(i) == '1') {
results.add(true);
}
}
}
}
boolean[] results1D = new boolean[results.size()];
for (int i = 0; i < results.size(); i++) {
results1D[i] = results.get(i);
}
bufferedReader.close();
return results1D;
// convert1DBooleansTo2D(results1D, length);
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
} catch (IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
return null;
}
/**
* Copies a file from an initial source path file to a destination
*
* @param src
* - the initial source file
* @param dst
* - the destination path file
* @throws IOException
* exception with file handling
*/
public static void copyFile(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
System.err.println("ERROR: couldn't copy file in directory");
} finally {
in.close();
out.close();
}
}
/**
* Save the given text to the given filename.
*
* @param canonicalFilename
* Like /Users/al/foo/bar.txt
* @param text
* All the text you want to save to the file as one String.
* @throws IOException
*/
public static void writeFile(String canonicalFilename, String text)
throws IOException
{
File file = new File(canonicalFilename);
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(text);
out.close();
}
/**
* Write an array of bytes to a file. Presumably this is binary data; for
* plain text use the writeFile method.
*/
public static void writeFileAsBytes(String fullPath, byte[] bytes)
throws IOException
{
OutputStream bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream(fullPath));
InputStream inputStream = new ByteArrayInputStream(bytes);
int token = -1;
while ((token = inputStream.read()) != -1) {
bufferedOutputStream.write(token);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
inputStream.close();
}
/**
* Convert a byte array to a boolean array. Bit 0 is represented with false,
* Bit 1 is represented with 1
*
* @param bytes
* byte[]
* @return boolean[]
*/
public static boolean[] byteArray2BitArray(byte[] bytes) {
boolean[] bits = new boolean[bytes.length * 8];
for (int i = 0; i < bytes.length * 8; i++) {
if ((bytes[i / 8] & (1 << (7 - (i % 8)))) > 0) {
bits[i] = true;
}
}
return bits;
}
}
| valentin7/pianoHero | src/main/java/edu/brown/cs/pianoHeroFiles/PianoHeroFileHandler.java | Java | mit | 11,443 |
$( document ).ready( function () {
$( "#form" ).validate( {
rules: {
company: { required: true },
truckType: { required: true },
materialType: { required: true },
fromSite: { required: true },
toSite: { required: true },
hourIn: { required: true },
hourOut: { required: true },
payment: { required: true },
plate: { minlength: 3, maxlength:15 }
},
errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );
error.insertAfter( element );
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
},
unhighlight: function (element, errorClass, validClass) {
$( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
},
submitHandler: function (form) {
return true;
}
});
$("#btnClose").click(function(){
if(window.confirm('Are you sure you want to close this Hauling Report?'))
{
$.ajax({
type: "POST",
url: base_url + "hauling/update_hauling_state",
data: $("#form").serialize(),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
cache: false,
success: function(data){
if( data.result == "error" )
{
//alert(data.mensaje);
$("#div_cargando").css("display", "none");
$('#btnSubmit').removeAttr('disabled');
$("#span_msj").html(data.mensaje);
$("#div_msj").css("display", "inline");
return false;
}
if( data.result )//true
{
$("#div_cargando").css("display", "none");
$("#div_guardado").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
var url = base_url + "hauling/add_hauling/" + data.idHauling;
$(location).attr("href", url);
}
else
{
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
}
},
error: function(result) {
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
}
});
}
});
$("#btnSubmit").click(function(){
if ($("#form").valid() == true){
//Activa icono guardando
$('#btnSubmit').attr('disabled','-1');
$("#div_guardado").css("display", "none");
$("#div_error").css("display", "none");
$("#div_msj").css("display", "none");
$("#div_cargando").css("display", "inline");
$.ajax({
type: "POST",
url: base_url + "hauling/save_hauling",
data: $("#form").serialize(),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
cache: false,
success: function(data){
if( data.result == "error" )
{
//alert(data.mensaje);
$("#div_cargando").css("display", "none");
$('#btnSubmit').removeAttr('disabled');
$("#div_error").css("display", "inline");
$("#span_msj").html(data.mensaje);
return false;
}
if( data.result )//true
{
$("#div_cargando").css("display", "none");
$("#div_guardado").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
var url = base_url + "hauling/add_hauling/" + data.idHauling;
$(location).attr("href", url);
}
else
{
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
}
},
error: function(result) {
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
}
});
}//if
});
$("#btnEmail").click(function(){
if ($("#form").valid() == true){
//Activa icono guardando
$('#btnSubmit').attr('disabled','-1');
$('#btnEmail').attr('disabled','-1');
$("#div_guardado").css("display", "none");
$("#div_error").css("display", "none");
$("#div_msj").css("display", "none");
$("#div_cargando").css("display", "inline");
$.ajax({
type: "POST",
url: base_url + "hauling/save_hauling_and_send_email",
data: $("#form").serialize(),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
cache: false,
success: function(data){
if( data.result == "error" )
{
//alert(data.mensaje);
$("#div_cargando").css("display", "none");
$('#btnSubmit').removeAttr('disabled');
$('#btnEmail').removeAttr('disabled');
$("#div_error").css("display", "inline");
$("#span_msj").html(data.mensaje);
return false;
}
if( data.result )//true
{
$("#div_cargando").css("display", "none");
$("#div_guardado").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
$('#btnEmail').removeAttr('disabled');
var url = base_url + "hauling/add_hauling/" + data.idHauling;
$(location).attr("href", url);
}
else
{
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
$('#btnEmail').removeAttr('disabled');
}
},
error: function(result) {
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
$('#btnEmail').removeAttr('disabled');
}
});
}//if
});
}); | bmottag/vci_app | assets/js/validate/hauling/hauling_v2.js | JavaScript | mit | 6,397 |
var axios = require("axios");
var expect = require("chai").expect;
var MockAdapter = require("../src");
describe("MockAdapter asymmetric matchers", function () {
var instance;
var mock;
beforeEach(function () {
instance = axios.create();
mock = new MockAdapter(instance);
});
it("mocks a post request with a body matching the matcher", function () {
mock
.onPost("/anyWithBody", {
asymmetricMatch: function (actual) {
return actual.params === "1";
},
})
.reply(200);
return instance
.post("/anyWithBody", { params: "1" })
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it("mocks a post request with a body not matching the matcher", function () {
mock
.onPost("/anyWithBody", {
asymmetricMatch: function (actual) {
return actual.params === "1";
},
})
.reply(200);
return instance
.post("/anyWithBody", { params: "2" })
.catch(function (error) {
expect(error.message).to.eq("Request failed with status code 404");
});
});
});
| ctimmerm/axios-mock-adapter | test/asymmetric.spec.js | JavaScript | mit | 1,140 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class UpdatePagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table(
'pages',
function (Blueprint $table) {
$table->json('version')->nullable();
$table->unsignedInteger('version_no')->nullable();
}
);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table(
'pages',
function ($table) {
$table->dropColumn('version');
$table->dropColumn('version_no');
}
);
}
}
| younginnovations/resourcecontracts-rc-subsite | database/migrations/2020_03_11_052945_update_pages_table.php | PHP | mit | 830 |
'use strict';
var intlNameInitials = function () {
};
var pattern = '{0}{1}';
function _firstLetter(text) {
return text.charAt(0);
}
function _upperCase(letter) {
if (letter === 'ı'){
return 'I';
}
return letter.toUpperCase();
}
function _isHangul(l){
if ((l > 44032) && (l < 55203)) {
return true;
}
return false;
}
function _initials(letter) {
var l = letter.charCodeAt(0);
// Generated by regenerate and unicode-8.0.0
// Greek 117
// Latin 991
// Cyrillic 302
var alphaRegex = '[A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u0370-\u0373\u0375-\u0377\u037A-\u037D\u037F\u0384\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03E1\u03F0-\u0484\u0487-\u052F\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFE]';
var re = new RegExp(alphaRegex,'i');
if (re.test(letter)){
return letter;
}
return '';
}
function _isSupportedInitials(letter) {
var alphaRegex = '[A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u0370-\u0373\u0375-\u0377\u037A-\u037D\u037F\u0384\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03E1\u03F0-\u0484\u0487-\u052F\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFE]';
var re = new RegExp(alphaRegex,'i');
if (re.test(letter)){
return true;
}
return false;
}
function isThai(a){
var thaiRegex = '[\u0E01-\u0E3A\u0E40-\u0E5B]';
var re = new RegExp(thaiRegex,'i');
if (a.length === 1){
return true;
} else {
var letter = _firstLetter(a);
if (re.test(a)) {
return true;
}
}
return false;
}
function isCJK(a){
// HANGUL SYLLABLES
// We want to be sure the full name is Hangul
if (a.length < 3){
var i = 0;
for(var c=0;c< a.length;c++){
if (_isHangul(a.charCodeAt(c)) )
{
i++;
}
}
if (i === a.length){
return true;
}
}
return false;
}
intlNameInitials.prototype.format = function (name, options) {
var initials = '',
a = '',
b = '';
var fields = ['firstName', 'lastName'],
initialName = { firstName : '', lastName: '' };
if (name === null || typeof name !== 'object' ) {
return undefined;
}
fields.forEach(function(field){
if (name.hasOwnProperty(field)) {
if (name[field] === null || name[field].length === 0){
// Nothing to do. but keeping it as placeholder
} else {
if (_isSupportedInitials(_firstLetter(name[field]))) {
initialName[field] = _firstLetter(name[field]);
initials = initials + _upperCase(_initials(initialName[field]));
}
}
}
});
// for CJK
if (name.hasOwnProperty("lastName")){
if (name.lastName === null || name.lastName.length === 0){
} else {
if (isCJK(name.lastName)) {
initials = name.lastName;
}
}
}
if (initials.length === 0){
return undefined;
}
return initials;
};
module.exports = intlNameInitials;
| lwelti/intl-name-initials | src/index.js | JavaScript | mit | 3,252 |
export default [
{
radius: 6,
sizeReduction: .85,
branchProbability: 0.12,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 6,
sizeReduction: .85,
branchProbability: 0.21,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 3,
sizeReduction: .87,
branchProbability: 0.25,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
}, {
radius: 7,
sizeReduction: .82,
branchProbability: 0.22,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 7,
sizeReduction: .82,
branchProbability: 0.22,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 7,
sizeReduction: .82,
branchProbability: 0.27,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},
{
radius: 10,
sizeReduction: .9,
branchProbability: 0.2,
rotation: new THREE.Vector3(0, 1, 0),
color: 'pink'
},{
radius: 10,
sizeReduction: .75,
branchProbability: 0.3,
rotation: new THREE.Vector3(0, 1, 0),
color: 'pink'
}
];
| susielu/3d | src/plantae/conical-dendrite-trees.js | JavaScript | mit | 1,089 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="lv_LV" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Hirocoin</source>
<translation>Par Hirocoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Hirocoin</b> version</source>
<translation><b>Hirocoin</b> versija</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Hirocoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adrešu grāmata</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Adresi vai nosaukumu rediģē ar dubultklikšķi</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Izveidot jaunu adresi</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopēt iezīmēto adresi uz starpliktuvi</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Jauna adrese</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Hirocoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopēt adresi</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Parādīt &QR kodu</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Hirocoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Hirocoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Dzēst</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Hirocoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopēt &Nosaukumu</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Rediģēt</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksportēt adreses</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Fails ar komatu kā atdalītāju (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Kļūda eksportējot</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nevar ierakstīt failā %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Nosaukums</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adrese</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(bez nosaukuma)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Paroles dialogs</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Ierakstiet paroli</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Jauna parole</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Jaunā parole vēlreiz</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Ierakstiet maciņa jauno paroli.<br/>Lūdzu izmantojiet <b>10 vai vairāk nejauši izvēlētas zīmes</b>, vai <b>astoņus un vairāk vārdus</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Šifrēt maciņu</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Lai veikto šo darbību, maciņš jāatslēdz ar paroli.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Atslēgt maciņu</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Šai darbībai maciņš jāatšifrē ar maciņa paroli.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Atšifrēt maciņu</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Mainīt paroli</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Ierakstiet maciņa veco un jauno paroli.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Apstiprināt maciņa šifrēšanu</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR HIROCOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Maciņš nošifrēts</translation>
</message>
<message>
<location line="-56"/>
<source>Hirocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your hirocoins from being stolen by malware infecting your computer.</source>
<translation>Hirocoin aizvērsies, lai pabeigtu šifrēšanu. Atcerieties, ka maciņa šifrēšana nevar pilnībā novērst bitkoinu zādzību, ko veic datorā ieviesušās kaitīgas programmas.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Maciņa šifrēšana neizdevās</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Maciņa šifrēšana neizdevās programmas kļūdas dēļ. Jūsu maciņš netika šifrēts.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Ievadītās paroles nav vienādas.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Maciņu atšifrēt neizdevās</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Maciņa atšifrēšanai ievadītā parole nav pareiza.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Maciņu neizdevās atšifrēt</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Parakstīt &ziņojumu...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sinhronizācija ar tīklu...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Pārskats</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Rādīt vispārēju maciņa pārskatu</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transakcijas</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Skatīt transakciju vēsturi</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Rediģēt saglabātās adreses un nosaukumus</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Rādīt maksājumu saņemšanas adreses</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Iziet</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Aizvērt programmu</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Hirocoin</source>
<translation>Parādīt informāciju par Hirocoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Par &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Parādīt informāciju par Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Iespējas</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>Š&ifrēt maciņu...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Izveidot maciņa rezerves kopiju</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Mainīt paroli</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Hirocoin address</source>
<translation>Nosūtīt bitkoinus uz Hirocoin adresi</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Hirocoin</source>
<translation>Mainīt Hirocoin konfigurācijas uzstādījumus</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Izveidot maciņa rezerves kopiju citur</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Mainīt maciņa šifrēšanas paroli</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debug logs</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Atvērt atkļūdošanas un diagnostikas konsoli</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Pārbaudīt ziņojumu...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Hirocoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Maciņš</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Hirocoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Hirocoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Hirocoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Fails</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Uzstādījumi</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Palīdzība</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Ciļņu rīkjosla</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Hirocoin client</source>
<translation>Hirocoin klients</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Hirocoin network</source>
<translation><numerusform>%n aktīvu savienojumu ar Hirocoin tīklu</numerusform><numerusform>%n aktīvs savienojums ar Hirocoin tīklu</numerusform><numerusform>%n aktīvu savienojumu as Hirocoin tīklu</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Kļūda</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Brīdinājums</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Sinhronizēts</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Sinhronizējos...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Apstiprināt transakcijas maksu</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transakcija nosūtīta</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Ienākoša transakcija</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datums: %1
Daudzums: %2
Tips: %3
Adrese: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Hirocoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Maciņš ir <b>šifrēts</b> un pašlaik <b>atslēgts</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Maciņš ir <b>šifrēts</b> un pašlaik <b>slēgts</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Hirocoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Tīkla brīdinājums</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Mainīt adrese</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Nosaukums</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Adrešu grāmatas ieraksta nosaukums</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adrese</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adrese adrešu grāmatas ierakstā. To var mainīt tikai nosūtīšanas adresēm.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Jauna saņemšanas adrese</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Jauna nosūtīšanas adrese</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Mainīt saņemšanas adresi</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Mainīt nosūtīšanas adresi</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Nupat ierakstītā adrese "%1" jau atrodas adrešu grāmatā.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Hirocoin address.</source>
<translation>Ierakstītā adrese "%1" nav derīga Hirocoin adrese.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Nav iespējams atslēgt maciņu.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Neizdevās ģenerēt jaunu atslēgu.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Hirocoin-Qt</source>
<translation>Hirocoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versija</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Lietojums:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komandrindas izvēles</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Lietotāja interfeisa izvēlnes</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Uzstādiet valodu, piemēram "de_DE" (pēc noklusēšanas: sistēmas lokāle)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Sākt minimizētu</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Uzsākot, parādīt programmas informācijas logu (pēc noklusēšanas: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Iespējas</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Galvenais</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>&Maksāt par transakciju</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Hirocoin after logging in to the system.</source>
<translation>Automātiski sākt Hirocoin pēc pieteikšanās sistēmā.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Hirocoin on system login</source>
<translation>&Sākt Hirocoin reizē ar sistēmu</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Tīkls</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Hirocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Uz rūtera automātiski atvērt Hirocoin klienta portu. Tas strādā tikai tad, ja rūteris atbalsta UPnP un tas ir ieslēgts.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Kartēt portu, izmantojot &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Hirocoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Savienoties caur SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>proxy IP adrese (piem. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Ports:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxy ports (piem. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versija:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>proxy SOCKS versija (piem. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Logs</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Pēc loga minimizācijas rādīt tikai ikonu sistēmas teknē.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizēt uz sistēmas tekni, nevis rīkjoslu</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Logu aizverot, minimizēt, nevis beigt darbu. Kad šī izvēlne iespējota, programma aizvērsies tikai pēc Beigt komandas izvēlnē.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizēt aizverot</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Izskats</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Lietotāja interfeiss un &valoda:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Hirocoin.</source>
<translation>Šeit var iestatīt lietotāja valodu. Iestatījums aktivizēsies pēc Hirocoin pārstartēšanas.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Vienības, kurās attēlot daudzumus:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Izvēlēties dalījuma vienību pēc noklusēšanas, ko izmantot interfeisā un nosūtot bitkoinus.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Hirocoin addresses in the transaction list or not.</source>
<translation>Rādīt vai nē Hirocoin adreses transakciju sarakstā.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Attēlot adreses transakciju sarakstā</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Atcelt</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Pielietot</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>pēc noklusēšanas</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Brīdinājums</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Hirocoin.</source>
<translation>Iestatījums aktivizēsies pēc Bitkoin pārstartēšanas.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Norādītā proxy adrese nav derīga.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Hirocoin network after a connection is established, but this process has not completed yet.</source>
<translation>Attēlotā informācija var būt novecojusi. Jūsu maciņš pēc savienojuma izveides automātiski sinhronizējas ar Hirocoin tīklu, taču šis process vēl nav beidzies.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Bilance:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Neapstiprinātas:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Maciņš</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Pēdējās transakcijas</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Jūsu tekošā bilance</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Kopējā apstiprināmo transakciju vērtība, vēl nav ieskaitīta kopējā bilancē</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>nav sinhronizēts</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start hirocoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR koda dialogs</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Pieprasīt maksājumu</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Daudzums:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Nosaukums:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Ziņojums:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Saglabāt kā...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Kļūda kodējot URI QR kodā.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Rezultāta URI pārāk garš, mēģiniet saīsināt nosaukumu vai ziņojumu. </translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Saglabāt QR kodu</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG attēli (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Klienta vārds</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Klienta versija</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informācija</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Sākuma laiks</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Tīkls</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Savienojumu skaits</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testa tīklā</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Bloku virkne</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Pašreizējais bloku skaits</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Bloku skaita novērtējums</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Pēdējā bloka laiks</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Atvērt</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Hirocoin-Qt help message to get a list with possible Hirocoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsole</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Kompilācijas datums</translation>
</message>
<message>
<location line="-104"/>
<source>Hirocoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Hirocoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Hirocoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Notīrīt konsoli</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Hirocoin RPC console.</source>
<translation>Laipni lūgti Hirocoin RPC konsolē.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Izmantojiet bultiņas uz augšu un leju, lai pārvietotos pa vēsturi, un <b>Ctrl-L</b> ekrāna notīrīšanai.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Ierakstiet <b>help</b> lai iegūtu pieejamo komandu sarakstu.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Sūtīt bitkoinus</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Sūtīt vairākiem saņēmējiem uzreiz</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Dzēst visus transakcijas laukus</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Notīrīt visu</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Bilance:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Apstiprināt nosūtīšanu</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> līdz %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Apstiprināt bitkoinu sūtīšanu</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Vai tiešām vēlaties nosūtīt %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>un</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Nosūtāmajai summai jābūt lielākai par 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Daudzums pārsniedz pieejamo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Kopsumma pārsniedz pieejamo, ja pieskaitīta %1 transakcijas maksa.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Atrastas divas vienādas adreses, vienā nosūtīšanas reizē uz katru adresi var sūtīt tikai vienreiz.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Kļūda: transakcija tika atteikta. Tā var gadīties, ja kāds no maciņā esošiem bitkoiniem jau iztērēts, piemēram, izmantojot wallet.dat kopiju, kurā nav atzīmēti iztērētie bitkoini.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Apjo&ms</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Saņēmējs:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Lai pievienotu adresi adrešu grāmatai, tai jādod nosaukums</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Nosaukums:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Izvēlēties adresi no adrešu grāmatas</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>ielīmēt adresi no starpliktuves</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Dzēst šo saņēmēju</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Hirocoin address (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation>Ierakstiet Hirocoin adresi (piem. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>ielīmēt adresi no starpliktuves</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Hirocoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Notīrīt visu</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Hirocoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Hirocoin address (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation>Ierakstiet Hirocoin adresi (piem. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Hirocoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Hirocoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Atvērts līdz %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/neapstiprinātas</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 apstiprinājumu</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datums</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Daudzums</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, vēl nav veiksmīgi izziņots</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nav zināms</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transakcijas detaļas</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Šis panelis parāda transakcijas detaļas</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Datums</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tips</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adrese</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Daudzums</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Atvērts līdz %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Nav pieslēgts (%1 apstiprinājumu)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Nav apstiprināts (%1 no %2 apstiprinājumu)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Apstiprināts (%1 apstiprinājumu)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Neviens cits mezgls šo bloku nav saņēmis un droši vien netiks akceptēts!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Ģenerēts, taču nav akceptēts</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Saņemts ar</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Saņemts no</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Nosūtīts</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Maksājums sev</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Atrasts</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nav pieejams)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transakcijas statuss. Turiet peli virs šī lauka, lai redzētu apstiprinājumu skaitu.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Transakcijas saņemšanas datums un laiks.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Transakcijas tips.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Transakcijas mērķa adrese.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bilancei pievienotais vai atņemtais daudzums.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Visi</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Šodien</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Šonedēļ</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Šomēnes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Pēdējais mēnesis</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Šogad</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Diapazons...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Saņemts ar</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Nosūtīts</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Sev</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Atrasts</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Cits</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Ierakstiet meklējamo nosaukumu vai adresi</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimālais daudzums</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopēt adresi</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopēt nosaukumu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopēt daudzumu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Mainīt nosaukumu</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Rādīt transakcijas detaļas</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Eksportēt transakcijas datus</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Fails ar komatu kā atdalītāju (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Apstiprināts</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datums</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tips</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Nosaukums</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adrese</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Daudzums</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Eksportēšanas kļūda</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nevar ierakstīt failā %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Diapazons:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Izveidot maciņa rezerves kopiju</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Maciņa dati (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Rezerves kopēšana neizdevās</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Kļūda, saglabājot maciņu jaunajā vietā.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Hirocoin version</source>
<translation>Hirocoin versija</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Lietojums:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or hirocoind</source>
<translation>Nosūtīt komantu uz -server vai hirocoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Komandu saraksts</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Palīdzība par komandu</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Iespējas:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: hirocoin.conf)</source>
<translation>Norādiet konfigurācijas failu (pēc noklusēšanas: hirocoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: hirocoind.pid)</source>
<translation>Norādiet pid failu (pēc noklusēšanas: hirocoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Norādiet datu direktoriju</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Uzstādiet datu bāzes bufera izmēru megabaitos (pēc noklusēšanas: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9348 or testnet: 19348)</source>
<translation>Gaidīt savienojumus portā <port> (pēc noklusēšanas: 9348 vai testnet: 19348)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Uzturēt līdz <n> savienojumiem ar citiem mezgliem(pēc noklusēšanas: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Pievienoties mezglam, lai iegūtu citu mezglu adreses, un atvienoties</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Norādiet savu publisko adresi</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Slieksnis pārkāpējmezglu atvienošanai (pēc noklusēšanas: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Sekundes, cik ilgi atturēt pārkāpējmezglus no atkārtotas pievienošanās (pēc noklusēšanas: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9347 or testnet: 19347)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Pieņemt komandrindas un JSON-RPC komandas</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Darbināt fonā kā servisu un pieņemt komandas</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Izmantot testa tīklu</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=hirocoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Hirocoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Hirocoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Hirocoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Debug izvadei sākumā pievienot laika zīmogu</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Hirocoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Debug/trace informāciju izvadīt konsolē, nevis debug.log failā</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Debug/trace informāciju izvadīt debug programmai</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC savienojumu lietotājvārds</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Brīdinājums</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC savienojumu parole</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Atļaut JSON-RPC savienojumus no norādītās IP adreses</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Nosūtīt komandas mezglam, kas darbojas adresē <ip> (pēc noklusēšanas: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Izpildīt komandu, kad labāk atbilstošais bloks izmainās (%s cmd aizvieto ar bloka hešu)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Atjaunot maciņa formātu uz jaunāko</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Uzstādīt atslēgu bufera izmēru uz <n> (pēc noklusēšanas: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Atkārtoti skanēt bloku virkni, meklējot trūkstošās maciņa transakcijas</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPC savienojumiem izmantot OpenSSL (https)</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servera sertifikāta fails (pēc noklusēšanas: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Servera privātā atslēga (pēc noklusēšanas: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Pieņemamie šifri (pēc noklusēšanas: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Šis palīdzības paziņojums</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Nevar pievienoties pie %s šajā datorā (pievienošanās atgrieza kļūdu %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Savienoties caurs socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Atļaut DNS uzmeklēšanu priekš -addnode, -seednode un -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Ielādē adreses...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Nevar ielādēt wallet.dat: maciņš bojāts</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Hirocoin</source>
<translation>Nevar ielādēt wallet.dat: maciņa atvēršanai nepieciešama jaunāka Hirocoin versija</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Hirocoin to complete</source>
<translation>Bija nepieciešams pārstartēt maciņu: pabeigšanai pārstartējiet Hirocoin</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Kļūda ielādējot wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Nederīga -proxy adrese: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet komandā norādīts nepazīstams tīkls: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Pieprasīta nezināma -socks proxy versija: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Nevar uzmeklēt -bind adresi: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Nevar atrisināt -externalip adresi: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Nederīgs daudzums priekš -paytxfree=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Nederīgs daudzums</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Nepietiek bitkoinu</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Ielādē bloku indeksu...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Pievienot mezglu, kam pievienoties un turēt savienojumu atvērtu</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Hirocoin is probably already running.</source>
<translation>Nevar pievienoties %s uz šī datora. Hirocoin droši vien jau darbojas.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Maksa par KB, ko pievienot nosūtāmajām transakcijām</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Ielādē maciņu...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Nevar maciņa formātu padarīt vecāku</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Nevar ierakstīt adresi pēc noklusēšanas</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Skanēju no jauna...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Ielāde pabeigta</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Izmantot opciju %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Kļūda</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Konfigurācijas failā jāuzstāda rpcpassword=<password>:
%s
Ja fails neeksistē, izveidojiet to ar atļauju lasīšanai tikai īpašniekam.</translation>
</message>
</context>
</TS>
| GoogolplexCoin/GoogolPlexCoin | src/qt/locale/bitcoin_lv_LV.ts | TypeScript | mit | 106,292 |
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace PoshGit2.TabCompletion
{
public class TabCompletionTests
{
private readonly ITestOutputHelper _log;
public TabCompletionTests(ITestOutputHelper log)
{
_log = log;
}
[InlineData("gi")]
[InlineData("git")]
[InlineData("git.")]
[InlineData("git.exe")]
[Theory]
public async Task GitCommand(string cmd)
{
var repo = Substitute.For<IRepositoryStatus>();
var completer = new TabCompleter(Task.FromResult(repo));
var result = await completer.CompleteAsync(cmd, CancellationToken.None);
Assert.True(result.IsFailure);
}
[InlineData("git ", new string[] { "clone", "init" })]
[Theory]
public async Task NullStatus(string command, string[] expected)
{
var completer = new TabCompleter(Task.FromResult<IRepositoryStatus>(null));
var fullResult = await completer.CompleteAsync(command, CancellationToken.None);
var result = GetResult(fullResult);
Assert.Equal(result, expected.OrderBy(o => o, StringComparer.Ordinal));
}
[InlineData("git add ", new string[] { })]
[InlineData("git rm ", new string[] { })]
[Theory]
public async Task EmptyStatus(string command, string[] expected)
{
var repo = Substitute.For<IRepositoryStatus>();
var completer = new TabCompleter(Task.FromResult(repo));
var fullResult = await completer.CompleteAsync(command, CancellationToken.None);
var result = GetResult(fullResult);
Assert.Equal(result, expected.OrderBy(o => o, StringComparer.Ordinal));
}
[InlineData("git ", "stash")]
[InlineData("git s", "stash")]
[InlineData("git ", "push")]
[InlineData("git p", "push")]
[InlineData("git ", "pull")]
[InlineData("git p", "pull")]
[InlineData("git ", "bisect")]
[InlineData("git bis", "bisect")]
[InlineData("git ", "branch")]
[InlineData("git br", "branch")]
[InlineData("git ", "add")]
[InlineData("git a", "add")]
[InlineData("git ", "rm")]
[InlineData("git r", "rm")]
[InlineData("git ", "merge")]
[InlineData("git m", "merge")]
[InlineData("git ", "mergetool")]
[InlineData("git m", "mergetool")]
[Theory]
public async Task ResultContains(string command, string expected)
{
var completer = CreateTabCompleter();
var fullResult = await completer.CompleteAsync(command, CancellationToken.None);
var result = GetResult(fullResult);
Assert.Contains(expected, result);
}
// Verify command completion
[InlineData("git ", new[] { "add", "am", "annotate", "archive", "bisect", "blame", "branch", "bundle", "checkout", "cherry", "cherry-pick", "citool", "clean", "clone", "commit", "config", "describe", "diff", "difftool", "fetch", "format-patch", "gc", "grep", "gui", "help", "init", "instaweb", "log", "merge", "mergetool", "mv", "notes", "prune", "pull", "push", "rebase", "reflog", "remote", "rerere", "reset", "revert", "rm", "shortlog", "show", "stash", "status", "submodule", "svn", "tag", "whatchanged" })]
[InlineData("git.exe ", new[] { "add", "am", "annotate", "archive", "bisect", "blame", "branch", "bundle", "checkout", "cherry", "cherry-pick", "citool", "clean", "clone", "commit", "config", "describe", "diff", "difftool", "fetch", "format-patch", "gc", "grep", "gui", "help", "init", "instaweb", "log", "merge", "mergetool", "mv", "notes", "prune", "pull", "push", "rebase", "reflog", "remote", "rerere", "reset", "revert", "rm", "shortlog", "show", "stash", "status", "submodule", "svn", "tag", "whatchanged" })]
// git add
[InlineData("git add ", new[] { "working-duplicate", "working-modified", "working-added", "working-unmerged" })]
[InlineData("git add working-m", new[] { "working-modified" })]
// git rm
[InlineData("git rm ", new[] { "working-deleted", "working-duplicate" })]
[InlineData("git rm working-a", new string[] { })]
[InlineData("git rm working-d", new string[] { "working-deleted", "working-duplicate" })]
// git bisect
[InlineData("git bisect ", new[] { "start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run" })]
[InlineData("git bisect s", new[] { "start", "skip" })]
[InlineData("git bisect bad ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git bisect good ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git bisect reset ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git bisect skip ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git bisect bad f", new string[] { "feature1", "feature2" })]
[InlineData("git bisect good f", new string[] { "feature1", "feature2" })]
[InlineData("git bisect reset f", new string[] { "feature1", "feature2" })]
[InlineData("git bisect skip f", new string[] { "feature1", "feature2" })]
[InlineData("git bisect bad g", new string[] { })]
[InlineData("git bisect good g", new string[] { })]
[InlineData("git bisect reset g", new string[] { })]
[InlineData("git bisect skip g", new string[] { })]
[InlineData("git bisect skip H", new string[] { "HEAD" })]
// git notes
[InlineData("git notes ", new[] { "edit", "show" })]
[InlineData("git notes e", new[] { "edit" })]
// git reflog
[InlineData("git reflog ", new[] { "expire", "delete", "show" })]
[InlineData("git reflog e", new[] { "expire" })]
// git branch
[InlineData("git branch -d ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch -D ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch -m ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch -M ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch -d f", new string[] { "feature1", "feature2" })]
[InlineData("git branch -D f", new string[] { "feature1", "feature2" })]
[InlineData("git branch -m f", new string[] { "feature1", "feature2" })]
[InlineData("git branch -M f", new string[] { "feature1", "feature2" })]
[InlineData("git branch -d g", new string[] { })]
[InlineData("git branch -D g", new string[] { })]
[InlineData("git branch -m g", new string[] { })]
[InlineData("git branch -M g", new string[] { })]
[InlineData("git branch newBranch ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch newBranch f", new string[] { "feature1", "feature2" })]
[InlineData("git branch newBranch g", new string[] { })]
// git push
[InlineData("git push ", new string[] { "origin", "other" })]
[InlineData("git push oth", new string[] { "other" })]
[InlineData("git push origin ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git push origin fe", new string[] { "feature1", "feature2" })]
[InlineData("git push origin :", new string[] { ":remotefeature", ":cutfeature" })]
[InlineData("git push origin :re", new string[] { ":remotefeature" })]
// git pull
[InlineData("git pull ", new string[] { "origin", "other" })]
[InlineData("git pull oth", new string[] { "other" })]
[InlineData("git pull origin ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git pull origin fe", new string[] { "feature1", "feature2" })]
// git fetch
[InlineData("git fetch ", new string[] { "origin", "other" })]
[InlineData("git fetch oth", new string[] { "other" })]
// git submodule
[InlineData("git submodule ", new string[] { "add", "status", "init", "update", "summary", "foreach", "sync" })]
[InlineData("git submodule s", new string[] { "status", "summary", "sync" })]
// git svn
[InlineData("git svn ", new string[] { "init", "fetch", "clone", "rebase", "dcommit", "branch", "tag", "log", "blame", "find-rev", "set-tree", "create-ignore", "show-ignore", "mkdirs", "commit-diff", "info", "proplist", "propget", "show-externals", "gc", "reset" })]
[InlineData("git svn f", new string[] { "fetch", "find-rev" })]
// git stash
[InlineData("git stash ", new string[] { "list", "save", "show", "drop", "pop", "apply", "branch", "clear", "create" })]
[InlineData("git stash s", new string[] { "save", "show" })]
[InlineData("git stash show ", new string[] { "stash", "wip" })]
[InlineData("git stash show w", new string[] { "wip" })]
[InlineData("git stash show d", new string[] { })]
[InlineData("git stash apply ", new string[] { "stash", "wip" })]
[InlineData("git stash apply w", new string[] { "wip" })]
[InlineData("git stash apply d", new string[] { })]
[InlineData("git stash drop ", new string[] { "stash", "wip" })]
[InlineData("git stash drop w", new string[] { "wip" })]
[InlineData("git stash drop d", new string[] { })]
[InlineData("git stash pop ", new string[] { "stash", "wip" })]
[InlineData("git stash pop w", new string[] { "wip" })]
[InlineData("git stash pop d", new string[] { })]
[InlineData("git stash branch ", new string[] { "stash", "wip" })]
[InlineData("git stash branch w", new string[] { "wip" })]
[InlineData("git stash branch d", new string[] { })]
// Tests for commit
[InlineData("git commit -C ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git commit -C O", new string[] { "ORIG_HEAD" })]
[InlineData("git commit -C o", new string[] { "origin/cutfeature", "origin/remotefeature" })]
// git remote
[InlineData("git remote ", new[] { "add", "rename", "rm", "set-head", "show", "prune", "update" })]
[InlineData("git remote r", new[] { "rename", "rm" })]
[InlineData("git remote rename ", new string[] { "origin", "other" })]
[InlineData("git remote rename or", new string[] { "origin" })]
[InlineData("git remote rm ", new string[] { "origin", "other" })]
[InlineData("git remote rm or", new string[] { "origin" })]
[InlineData("git remote set-head ", new string[] { "origin", "other" })]
[InlineData("git remote set-head or", new string[] { "origin" })]
[InlineData("git remote set-branches ", new string[] { "origin", "other" })]
[InlineData("git remote set-branches or", new string[] { "origin" })]
[InlineData("git remote set-url ", new string[] { "origin", "other" })]
[InlineData("git remote set-url or", new string[] { "origin" })]
[InlineData("git remote show ", new string[] { "origin", "other" })]
[InlineData("git remote show or", new string[] { "origin", })]
[InlineData("git remote prune ", new string[] { "origin", "other" })]
[InlineData("git remote prune or", new string[] { "origin" })]
// git help <cmd>
[InlineData("git help ", new[] { "add", "am", "annotate", "archive", "bisect", "blame", "branch", "bundle", "checkout", "cherry", "cherry-pick", "citool", "clean", "clone", "commit", "config", "describe", "diff", "difftool", "fetch", "format-patch", "gc", "grep", "gui", "help", "init", "instaweb", "log", "merge", "mergetool", "mv", "notes", "prune", "pull", "push", "rebase", "reflog", "remote", "rerere", "reset", "revert", "rm", "shortlog", "show", "stash", "status", "submodule", "svn", "tag", "whatchanged" })]
[InlineData("git help ch", new[] { "checkout", "cherry", "cherry-pick" })]
// git checkout -- <files>
[InlineData("git checkout -- ", new[] { "working-deleted", "working-duplicate", "working-modified", "working-unmerged" })]
[InlineData("git checkout -- working-d", new[] { "working-deleted", "working-duplicate" })]
// git merge|mergetool <files>
// TODO: Enable for merge state
//[InlineData("git merge ", new[] { "working-unmerged", "working-duplicate" })]
//[InlineData("git merge working-u", new[] { "working-unmerged" })]
//[InlineData("git merge j", new string[] { })]
//[InlineData("git mergetool ", new[] { "working-unmerged", "working-duplicate" })]
//[InlineData("git mergetool working-u", new[] { "working-unmerged" })]
//[InlineData("git mergetool j", new string[] { })]
// git checkout <branch>
[InlineData("git checkout ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git cherry-pick <branch>
[InlineData("git cherry ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git cherry-pick <branch>
[InlineData("git cherry-pick ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git diff <branch>
[InlineData("git diff ", new[] { "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git diff --cached ", new[] { "working-modified", "working-duplicate", "working-unmerged", "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git diff --staged ", new[] { "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git difftool <branch>
[InlineData("git difftool ", new[] { "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git difftool --cached ", new[] { "working-modified", "working-duplicate", "working-unmerged", "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git difftool --staged ", new[] { "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git log <branch>
[InlineData("git log ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git merge <branch>
[InlineData("git merge ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git rebase <branch>
[InlineData("git rebase ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git reflog <branch>
[InlineData("git reflog show ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git reset <branch>
[InlineData("git reset ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git reset HEAD <file>
[InlineData("git reset HEAD ", new[] { "index-added", "index-deleted", "index-modified", "index-unmerged" })]
[InlineData("git reset HEAD index-a", new[] { "index-added" })]
// git revert <branch>
[InlineData("git revert ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git show<branch>
[InlineData("git show ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[Theory]
public async Task CheckCompletion(string cmd, string[] expected)
{
var completer = CreateTabCompleter();
await CompareAsync(completer, cmd, expected.OrderBy(o => o, StringComparer.Ordinal));
}
// git add
[InlineData("git add ", new[] { "working duplicate", "working modified", "working added", "working unmerged" })]
[InlineData("git add \"working m", new[] { "working modified" })]
[InlineData("git add \'working m", new[] { "working modified" })]
// git rm
[InlineData("git rm ", new[] { "working deleted", "working duplicate" })]
[InlineData("git rm \"working d", new string[] { "working deleted", "working duplicate" })]
[InlineData("git rm \'working d", new string[] { "working deleted", "working duplicate" })]
// git checkout -- <files>
[InlineData("git checkout -- ", new[] { "working deleted", "working duplicate", "working modified", "working unmerged" })]
[InlineData("git checkout -- \"wor", new[] { "working deleted", "working duplicate", "working modified", "working unmerged" })]
[InlineData("git checkout -- \"working d", new[] { "working deleted", "working duplicate" })]
[InlineData("git checkout -- \'working d", new[] { "working deleted", "working duplicate" })]
// git merge|mergetool <files>
// TODO: Enable for merge state
//[InlineData("git merge ", new[] { "working unmerged", "working duplicate" })]
//[InlineData("git merge working u", new[] { "working unmerged" })]
//[InlineData("git merge j", new string[] { })]
//[InlineData("git mergetool ", new[] { "working unmerged", "working duplicate" })]
//[InlineData("git mergetool working u", new[] { "working unmerged" })]
//[InlineData("git mergetool j", new string[] { })]
// git diff <branch>
[InlineData("git diff ", new[] { "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git diff --cached ", new[] { "working modified", "working duplicate", "working unmerged", "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git diff --staged ", new[] { "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git difftool <branch>
[InlineData("git difftool ", new[] { "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git difftool --cached ", new[] { "working modified", "working duplicate", "working unmerged", "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git difftool --staged ", new[] { "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git reset HEAD <file>
[InlineData("git reset HEAD ", new[] { "index added", "index deleted", "index modified", "index unmerged" })]
[InlineData("git reset HEAD \"index a", new[] { "index added" })]
[InlineData("git reset HEAD \'index a", new[] { "index added" })]
[Theory]
public async Task CheckCompletionWithQuotations(string cmd, string[] initialExpected)
{
const string quot = "\"";
var completer = CreateTabCompleter(" ");
var expected = initialExpected
.OrderBy(o => o, StringComparer.Ordinal)
.Select(o => o.Contains(" ") ? $"{quot}{o}{quot}" : o);
await CompareAsync(completer, cmd, expected);
}
private async Task CompareAsync(ITabCompleter completer, string cmd, IEnumerable<string> expected)
{
var fullResult = await completer.CompleteAsync(cmd, CancellationToken.None);
var result = GetResult(fullResult);
_log.WriteLine("Expected output:");
_log.WriteLine(string.Join(Environment.NewLine, expected));
_log.WriteLine(string.Empty);
_log.WriteLine("Actual output:");
_log.WriteLine(string.Join(Environment.NewLine, result));
Assert.Equal(expected, result);
}
private static ITabCompleter CreateTabCompleter(string join = "-")
{
var status = Substitute.For<IRepositoryStatus>();
var working = new ChangedItemsCollection
{
Added = new[] { $"working{join}added", $"working{join}duplicate" },
Deleted = new[] { $"working{join}deleted", $"working{join}duplicate" },
Modified = new[] { $"working{join}modified", $"working{join}duplicate" },
Unmerged = new[] { $"working{join}unmerged", $"working{join}duplicate" }
};
var index = new ChangedItemsCollection
{
Added = new[] { $"index{join}added" },
Deleted = new[] { $"index{join}deleted" },
Modified = new[] { $"index{join}modified" },
Unmerged = new[] { $"index{join}unmerged" }
};
status.Index.Returns(index);
status.Working.Returns(working);
status.LocalBranches.Returns(new[] { "master", "feature1", "feature2" });
status.Remotes.Returns(new[] { "origin", "other" });
status.RemoteBranches.Returns(new[] { "origin/remotefeature", "origin/cutfeature" });
status.Stashes.Returns(new[] { "stash", "wip" });
return new TabCompleter(Task.FromResult(status));
}
private IEnumerable<string> GetResult(TabCompletionResult fullResult)
{
Assert.True(fullResult.IsSuccess);
return (fullResult as TabCompletionResult.Success).Item;
}
}
}
| twsouthwick/poshgit2 | test/PoshGit2.TabCompletion.Tests/TabCompletionTests.cs | C# | mit | 24,041 |
var Purest = require('purest');
function Facebook(opts) {
this._opts = opts || {};
this._opts.provider = 'facebook';
this._purest = new Purest(this._opts);
this._group = 'LIB:SOCIAL:FACEBOOK';
return this;
}
Facebook.prototype.user = function (cb) {
var self = this;
this._purest.query()
.get('me')
.auth(this._opts.auth.token)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
Facebook.prototype.post = function (endpoint, form, cb) {
// form = {message: 'post message'}
this._purest.query()
.post(endpoint || 'me/feed')
.auth(this._opts.auth.token)
.form(form)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
module.exports = function(app) {
return Facebook;
};
| selcukfatihsevinc/app.io | lib/social/facebook.js | JavaScript | mit | 1,038 |
<?php
namespace Lollipop;
defined('LOLLIPOP_BASE') or die('Lollipop wasn\'t loaded correctly.');
/**
* Benchmark Class
*
* @author John Aldrich Bernardo
* @email 4ldrich@protonmail.com
* @package Lollipop
* @description Class for recording benchmarks
*/
class Benchmark
{
/**
* @var array $_marks Recorded microtimes
*
*/
static private $_marks = [];
/**
* Record benchmark
*
* @param string $mark Key name
*
*/
static public function mark($mark) {
self::$_marks[$mark] = [
'time' => microtime(true),
'memory_usage' => memory_get_peak_usage(true)
];
}
/**
* Get detailed benchmark
*
* @access public
* @param string $start Start mark
* @param string $end End mark
* @return array
*
*/
static public function elapsed($start, $end) {
return [
'time_elapsed' => self::elapsedTime($start, $end),
'memory_usage_gap' => self::elapsedMemory($start, $end),
'real_memory_usage' => self::elapsedMemory($start, $end, true)
];
}
/**
* Get elapsed memory between two marks
*
* @access public
* @param string $start Start mark
* @param string $end End mark
* @param bool $real_usage Get real memory usage
* @param bool $inMB Show output in MB instead of Bytes
* @return mixed <string> if $inMB is <true>, <longint> if on <false>
*
*/
static public function elapsedMemory($start, $end, $real_usage = false, $inMB = true) {
$start = isset(self::$_marks[$start]) ? self::$_marks[$start]['memory_usage'] : 0;
$end = isset(self::$_marks[$end]) ? self::$_marks[$end]['memory_usage'] : 0;
$elapsed = !$real_usage ? ($end - $start) : $end;
return $start ? ($inMB ? (($elapsed / 1024 / 1024) . ' MB') : $elapsed) : null;
}
/**
* Compute the elapsed time of two marks
*
* @param string $start Keyname 1
* @param string $end Keyname 2
*
* @return mixed
*
*/
static public function elapsedTime($start, $end) {
$start = isset(self::$_marks[$start]) ? self::$_marks[$start]['time'] : 0;
$end = isset(self::$_marks[$end]) ? self::$_marks[$end]['time'] : 0;
return $start ? round($end - $start, 10) : null;
}
}
| jabernardo/lollipop-php | Library/Benchmark.php | PHP | mit | 2,593 |
#include <windows.h>
#include "NativeCore.hpp"
bool RC_CallConv IsProcessValid(RC_Pointer handle)
{
if (handle == nullptr)
{
return false;
}
const auto retn = WaitForSingleObject(handle, 0);
if (retn == WAIT_FAILED)
{
return false;
}
return retn == WAIT_TIMEOUT;
}
| KN4CK3R/ReClass.NET | NativeCore/Windows/IsProcessValid.cpp | C++ | mit | 281 |
package dev.jee6demo.jspes;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/EventSourceServlet")
public class EventSourceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
PrintWriter pw = response.getWriter();
for (int i = 0; i < 5; i++) {
pw.write("event:new_time\n");
pw.write("data: " + now() + "\n\n");
pw.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pw.write("event:new_time\n");
pw.write("data: STOP\n\n");
pw.flush();
pw.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
public static String now(){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
return dateFormat.format(new Date());
}
}
| fegalo/jee6-demos | jsp/jsp-eventsource/src/main/java/dev/jee6demo/jspes/EventSourceServlet.java | Java | mit | 1,399 |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace XF_ManySwitches.Droid
{
[Activity(Label = "XF_ManySwitches", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| ytabuchi/Study | XF_ManySwitches/XF_ManySwitches/XF_ManySwitches.Droid/MainActivity.cs | C# | mit | 670 |
describe('controllers/home', function () {
var di,
Core,
Home,
Type,
contentModel = {
findOne: function() {
}
},
widgetHooks = [],
widgetHook = {
load: function (a, b, c) {
widgetHooks.push({
name: a,
alias: b,
method: c
});
},
handle: function () {
}
};
beforeEach(function () {
di = require('mvcjs');
di.setAlias('cp', __dirname + '/../../app/controllers/');
Type = di.load('typejs');
Core = di.mock('@{cp}/core', {
'typejs': Type,
'core/controller': {
inherit: function () {
return Type.create.apply(Type, arguments);
}
},
'@{core}/widget-hook': widgetHook
});
Home = di.mock('@{cp}/home', {
'typejs': Type,
'promise': di.load('promise'),
'@{controllersPath}/core': Core,
'@{modelsPath}/content': contentModel
});
});
it('construct', function () {
var api = {};
var controller = new Home(api);
expect(controller.locals.scripts.length).toBe(0);
expect(controller.locals.brand).toBe('MVCJS');
expect(controller.locals.pageTitle).toBe('Mvcjs nodejs framework');
expect(controller.locals.pageDesc).toBe('Mvcjs fast, opinionated lightweight mvc framework for Node.js inspired by Yii framework');
expect(controller.menu.length).toBe(0);
});
it('action_index', function () {
var api = {
locals: {
scripts: []
},
renderFile: function(route, locals) {
return 'RENDERED';
}
};
spyOn(api, 'renderFile').and.callThrough();
di.setAlias('basePath', __dirname + '/../../');
var controller = new Home(api);
var result = controller.action_index.call(api);
expect(api.renderFile).toHaveBeenCalledWith( 'home/index', {
scripts : [ {
src : 'https://buttons.github.io/buttons.js',
id : 'github-bjs',
async : true
} ],
version : '0.1.0-beta-15'
});
expect(result).toBe('RENDERED');
expect(api.locals.scripts.length).toBe(1);
});
it('action_content', function () {
var api = {
locals: {
content: '',
pageTitle: '',
pageDesc: ''
},
renderFile: function(route, locals) {
return 'RENDERED';
}
};
spyOn(api, 'renderFile').and.callThrough();
di.setAlias('basePath', __dirname + '/../../');
var controller = new Home(api);
var result = controller.action_content.call(api, {}, {
text: 'TEXT',
pageTitle: 'TITLE',
pageDesc: 'DESC'
});
expect(api.renderFile).toHaveBeenCalledWith( 'home/content', {
pageTitle: 'TITLE',
pageDesc: 'DESC',
content : 'TEXT'
});
expect(result).toBe('RENDERED');
});
it('before_content', function (done) {
var api = {
getParsedUrl: function(route, locals) {
return {
pathname: '/home/index'
};
}
};
contentModel.findOne = function(data, callback) {
expect(data.url).toBe('/home/index');
callback(null, {
id: 1,
text: 'yes'
});
};
spyOn(api, 'getParsedUrl').and.callThrough();
spyOn(contentModel, 'findOne').and.callThrough();
di.setAlias('basePath', __dirname + '/../../');
var controller = new Home(api);
var result = controller.before_content.call(api);
result.then(function(data) {
expect(api.getParsedUrl).toHaveBeenCalled();
expect(contentModel.findOne).toHaveBeenCalled();
expect(data.id).toBe(1);
expect(data.text).toBe('yes');
done();
});
});
it('before_content error', function (done) {
var api = {
getParsedUrl: function(route, locals) {
return {
pathname: '/home/index'
};
}
};
contentModel.findOne = function(data, callback) {
expect(data.url).toBe('/home/index');
callback(true, {
id: 1,
text: 'yes'
});
};
spyOn(api, 'getParsedUrl').and.callThrough();
spyOn(contentModel, 'findOne').and.callThrough();
di.setAlias('basePath', __dirname + '/../../');
var controller = new Home(api);
var result = controller.before_content.call(api);
result.then(null, function(error) {
console.log('error', error);
done();
});
});
it('beforeEach', function () {
var api = {};
widgetHook.handle = function(hooks) {
expect(hooks.indexOf('menu-hook')).toBe(0);
return hooks.shift();
};
var controller = new Home(api);
expect(controller.beforeEach()).toBe('menu-hook');
expect(controller.locals.scripts.length).toBe(1);
});
it('action_error', function () {
var api = {
locals: {},
setStatusCode: function(code) {
expect(code).toBe(500);
},
renderFile: function(name, locals) {
expect(name).toBe('home/error');
expect(locals.pageTitle).toBe('Error - mvcjs nodejs framework');
expect(locals.text).toBe('ERROR');
return 'RENDER';
}
};
spyOn(api, 'setStatusCode').and.callThrough();
spyOn(api, 'renderFile').and.callThrough();
var controller = new Home({});
var response = controller.action_error.call(api, {
code: 500,
toString: function() {
return "ERROR";
}
});
expect(api.setStatusCode).toHaveBeenCalled();
expect(api.renderFile).toHaveBeenCalled();
expect(response).toBe('RENDER');
});
}); | Siljanovski/gapi | tests/controllers/home-unit-spec.js | JavaScript | mit | 6,456 |
<?php
return array(
/** @brief Table de liaison avec les mots clés */
'table_liaison' => 'jayps_search_word_occurence',
/** @brief Préfixe de la table de liaison avec les mots clés */
'table_liaison_prefixe' => 'mooc_',
/** @brief mots clés interdits */
'forbidden_words' => array(
// 3 lettres
'les', 'des', 'ses', 'son', 'mes', 'mon', 'tes', 'ton', 'une', 'aux', 'est', 'sur', 'par', 'dit',
'the',
// 4 lettres
'pour','sans','dans','avec','deux','vers',
// 5 lettres
'titre',
),
/** @brief allowed some chars in words indexed and in search */
'allowable_chars' => '*?',
/** @brief longueur mimimum des mots à indexer */
'min_word_len' => 3,
/** @brief max number of joins for a search */
'max_join' => 4,
/** @brief For debugging */
'debug' => false,
/** @brief use a transaction to speed up InnoDB insert */
'transaction' => false,
/** @brief use INSERT DELAYED, for MyISAM Engine only*/
'insert_delayed' => true,
/** @brief group insertion of words */
'words_by_insert' => 100,
/** @brief score can be improved by this config*/
'title_boost' => 3,
'html_boost' => array(
'h1' => 3,
'h2' => 2,
'h3' => 1,
'strong' => 1,
)
);
| novius/jayps_search | config/config.php | PHP | mit | 1,338 |
/* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */
/*
* Copyright 2016, Joyent, Inc.
*/
var BINDING = require('./lockfd_binding');
function
check_arg(pos, name, value, type)
{
if (typeof (value) !== type) {
throw (new Error('argument #' + pos + ' (' + name +
') must be of type ' + type));
}
}
function
lockfd(fd, callback)
{
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'callback', callback, 'function');
BINDING.lock_fd(fd, 'write', false, function (ret, errmsg, errno) {
var err = null;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
}
setImmediate(callback, err);
});
}
function
lockfdSync(fd)
{
var cb_fired = false;
var err;
check_arg(1, 'fd', fd, 'number');
BINDING.lock_fd(fd, 'write', true, function (ret, errno, errmsg) {
cb_fired = true;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.__errno = errno;
return;
}
});
if (!cb_fired) {
throw (new Error('lockfdSync: CALLBACK NOT FIRED'));
} else if (err) {
throw (err);
}
return (null);
}
function
flock(fd, op, callback)
{
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'op', op, 'number');
check_arg(3, 'callback', callback, 'function');
BINDING.flock(fd, op, false, function (ret, errmsg, errno) {
var err = null;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
}
setImmediate(callback, err);
});
}
function
flockSync(fd, op)
{
var cb_fired = false;
var err;
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'op', op, 'number');
BINDING.flock(fd, op, true, function (ret, errmsg, errno) {
cb_fired = true;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
return;
}
});
if (!cb_fired) {
throw (new Error('flockSync: CALLBACK NOT FIRED'));
} else if (err) {
throw (err);
}
return (null);
}
module.exports = {
LOCK_SH: 1,
LOCK_EX: 2,
LOCK_NB: 4,
LOCK_UN: 8,
flock: flock,
flockSync: flockSync,
lockfd: lockfd,
lockfdSync: lockfdSync
};
| joyent/node-lockfd | lib/index.js | JavaScript | mit | 2,075 |
'use strict';
angular.module('depthyApp')
.controller('DrawCtrl', function ($scope, $element, depthy, $window, $timeout) {
var drawer = depthy.drawMode,
viewer = depthy.getViewer(),
lastPointerPos = null,
oldViewerOpts = angular.extend({}, depthy.viewer);
drawer.setOptions(depthy.drawOptions || {
depth: 0.5,
size: 0.05,
hardness: 0.5,
opacity: 0.25,
});
angular.extend(depthy.viewer, {
animate: false,
fit: 'contain',
upscale: 2,
// depthPreview: 0.75,
// orient: false,
// hover: false,
});
$scope.drawer = drawer;
$scope.drawOpts = drawer.getOptions();
$scope.preview = 1;
$scope.brushMode = false;
$scope.$watch('drawOpts', function(options) {
if (drawer && options) {
drawer.setOptions(options);
}
}, true);
$scope.$watch('preview', function(preview) {
depthy.viewer.orient = preview === 2;
depthy.viewer.hover = preview === 2;
depthy.viewer.animate = preview === 2 && oldViewerOpts.animate;
depthy.viewer.quality = preview === 2 ? false : 1;
depthy.animateOption(depthy.viewer, {
depthPreview: preview === 0 ? 1 : preview === 1 ? 0.75 : 0,
depthScale: preview === 2 ? oldViewerOpts.depthScale : 0,
depthBlurSize: preview === 2 ? oldViewerOpts.depthBlurSize : 0,
enlarge: 1.0,
}, 250);
});
$scope.togglePreview = function() {
console.log('togglePreview', $scope.preview);
// $scope.preview = ++$scope.preview % 3;
$scope.preview = $scope.preview === 1 ? 2 : 1;
};
$scope.done = function() {
$window.history.back();
};
$scope.cancel = function() {
drawer.cancel();
$window.history.back();
};
$scope.brushIcon = function() {
switch($scope.brushMode) {
case 'picker':
return 'target';
case 'level':
return 'magnet';
default:
return 'draw';
}
};
$element.on('touchstart mousedown', function(e) {
console.log('mousedown');
var event = e.originalEvent,
pointerEvent = event.touches ? event.touches[0] : event;
if (event.target.id !== 'draw') return;
lastPointerPos = viewer.screenToImagePos({x: pointerEvent.pageX, y: pointerEvent.pageY});
if ($scope.brushMode === 'picker' || $scope.brushMode === 'level') {
$scope.drawOpts.depth = drawer.getDepthAtPos(lastPointerPos);
console.log('Picked %s', $scope.drawOpts.depth);
if ($scope.brushMode === 'picker') {
$scope.brushMode = false;
lastPointerPos = null;
$scope.$safeApply();
event.preventDefault();
event.stopPropagation();
return;
} else {
$scope.$safeApply();
}
}
drawer.drawBrush(lastPointerPos);
// updateDepthMap();
event.preventDefault();
event.stopPropagation();
});
$element.on('touchmove mousemove', function(e) {
if (lastPointerPos) {
var event = e.originalEvent,
pointerEvent = event.touches ? event.touches[0] : event,
pointerPos = viewer.screenToImagePos({x: pointerEvent.pageX, y: pointerEvent.pageY});
drawer.drawBrushTo(pointerPos);
lastPointerPos = pointerPos;
}
});
$element.on('touchend mouseup', function(event) {
console.log('mouseup', event);
if (lastPointerPos) {
lastPointerPos = null;
$scope.$safeApply();
}
// if(window.location.href.indexOf('preview')<0){
// updateDepthMap();
// }
});
$element.on('click', function(e) {
console.log('click');
// updateDepthMap();
});
function getSliderForKey(e) {
var id = 'draw-brush-depth';
if (e.shiftKey && e.altKey) {
id = 'draw-brush-hardness';
} else if (e.altKey) {
id = 'draw-brush-opacity';
} else if (e.shiftKey) {
id = 'draw-brush-size';
}
var el = $element.find('.' + id + ' [range-stepper]');
el.click(); // simulate click to notify change
return el.controller('rangeStepper');
}
function onKeyDown(e) {
console.log('keydown', e);
var s, handled = false;
console.log('keydown which %d shift %s alt %s ctrl %s', e.which, e.shiftKey, e.altKey, e.ctrlKey);
if (e.which === 48) { // 0
getSliderForKey(e).percent(0.5);
handled = true;
} else if (e.which >= 49 && e.which <= 57) { // 1-9
getSliderForKey(e).percent((e.which - 49) / 8);
handled = true;
} else if (e.which === 189) { // -
s = getSliderForKey(e);
s.percent(s.percent() - 0.025);
handled = true;
} else if (e.which === 187) { // +
s = getSliderForKey(e);
s.percent(s.percent() + 0.025);
handled = true;
} else if (e.which === 32) {
$element.find('.draw-preview').click();
handled = true;
} else if (e.which === 90) { // z
$element.find('.draw-undo').click();
handled = true;
} else if (e.which === 80) { // p
$element.find('.draw-picker').click();
handled = true;
} else if (e.which === 76) { // l
$element.find('.draw-level').click();
handled = true;
} else if (e.which === 81) { // l
$scope.preview = $scope.preview === 1 ? 2 : 1;
handled = true;
}
if (handled) {
e.preventDefault();
$scope.$safeApply();
}
}
$($window).on('keydown', onKeyDown);
$element.find('.draw-brush-depth').on('touchstart mousedown click', function() {
$scope.brushMode = false;
});
$element.on('$destroy', function() {
$element.off('touchstart mousedown');
$element.off('touchmove mousemove');
$($window).off('keydown', onKeyDown);
depthy.animateOption(depthy.viewer, {
depthPreview: oldViewerOpts.depthPreview,
depthScale: oldViewerOpts.depthScale,
depthBlurSize: oldViewerOpts.depthBlurSize,
enlarge: oldViewerOpts.enlarge,
}, 250);
$timeout(function() {
angular.extend(depthy.viewer, oldViewerOpts);
}, 251);
if (drawer.isCanceled()) {
// restore opened depthmap
viewer.setDepthmap(depthy.opened.depthSource, depthy.opened.depthUsesAlpha);
} else {
if (drawer.isModified()) {
updateDepthMap();
}
}
drawer.destroy(true);
});
function updateDepthMap(){
depthy.drawOptions = drawer.getOptions();
// remember drawn depthmap
// store it as jpg
console.log('updateDepthMap',viewer);
viewer.exportDepthmap().then(function(url) {
depthy.opened.markAsModified();
depthy.opened.depthSource = url; //viewer.getDepthmap().texture;
depthy.opened.depthUsesAlpha = false;
viewer.setDepthmap(url);
depthy.opened.onDepthmapOpened();
localStorage.depthMapUrl = url;
var intercom = Intercom.getInstance();
intercom.emit('depthMapUrl', {message: url});
});
}
}); | amcassetti/parallax-pro-creator | app/scripts/controllers/draw.js | JavaScript | mit | 6,782 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="el_GR" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About BigBang</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>BigBang</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BigBang developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Διπλό-κλικ για επεξεργασία της διεύθυνσης ή της ετικέτας</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Δημιούργησε νέα διεύθυνση</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Αντέγραψε την επιλεγμένη διεύθυνση στο πρόχειρο του συστήματος</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your BigBang addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a BigBang address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Αντιγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified BigBang address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Διαγραφή</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Αντιγραφή &επιγραφής</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Επεξεργασία</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Ετικέτα</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(χωρίς ετικέτα)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Φράση πρόσβασης </translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Βάλτε κωδικό πρόσβασης</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Νέος κωδικός πρόσβασης</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Επανέλαβε τον νέο κωδικό πρόσβασης</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Εισάγετε τον νέο κωδικό πρόσβασης στον πορτοφόλι <br/> Παρακαλώ χρησιμοποιείστε ένα κωδικό με <b> 10 ή περισσότερους τυχαίους χαρακτήρες</b> ή <b> οχτώ ή παραπάνω λέξεις</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Αυτη η ενεργεία χρειάζεται τον κωδικό του πορτοφολιού για να ξεκλειδώσει το πορτοφόλι.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Ξεκλειδωσε το πορτοφολι</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Αυτη η ενεργεια χρειάζεται τον κωδικο του πορτοφολιου για να αποκρυπτογραφησειι το πορτοφολι.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Αποκρυπτογράφησε το πορτοφολι</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Εισάγετε τον παλιό και τον νεο κωδικο στο πορτοφολι.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Επιβεβαίωσε την κρυπτογραφηση του πορτοφολιού</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Είστε σίγουροι ότι θέλετε να κρυπτογραφήσετε το πορτοφόλι σας;</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ΣΗΜΑΝΤΙΚΟ: Τα προηγούμενα αντίγραφα ασφαλείας που έχετε κάνει από το αρχείο του πορτοφόλιου σας θα πρέπει να αντικατασταθουν με το νέο που δημιουργείται, κρυπτογραφημένο αρχείο πορτοφόλιου. Για λόγους ασφαλείας, τα προηγούμενα αντίγραφα ασφαλείας του μη κρυπτογραφημένου αρχείου πορτοφόλιου θα καταστουν άχρηστα μόλις αρχίσετε να χρησιμοποιείτε το νέο κρυπτογραφημένο πορτοφόλι. </translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Προσοχη: το πλήκτρο Caps Lock είναι ενεργο.</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Κρυπτογραφημενο πορτοφολι</translation>
</message>
<message>
<location line="-58"/>
<source>BigBang will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Η κρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Η κρυπτογράφηση του πορτοφολιού απέτυχε λογω εσωτερικού σφάλματος. Το πορτοφολι δεν κρυπτογραφηθηκε.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Οι εισαχθέντες κωδικοί δεν ταιριάζουν.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Ο κωδικος που εισήχθη για την αποκρυπτογραφηση του πορτοφολιού ήταν λαθος.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Η αποκρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Ο κωδικος του πορτοφολιού άλλαξε με επιτυχία.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>Υπογραφή &Μηνύματος...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Συγχρονισμός με το δίκτυο...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>&Επισκόπηση</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Εμφάνισε τη γενική εικόνα του πορτοφολιού</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Συναλλαγές</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Περιήγηση στο ιστορικό συναλλαγών</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>Έ&ξοδος</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Εξοδος από την εφαρμογή</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about BigBang</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Σχετικά με &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Εμφάνισε πληροφορίες σχετικά με Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Επιλογές...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a BigBang address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for BigBang</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Δημιουργία αντιγράφου ασφαλείας πορτοφολιού σε άλλη τοποθεσία</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Αλλαγή του κωδικού κρυπτογράφησης του πορτοφολιού</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Άνοιγμα κονσόλας αποσφαλμάτωσης και διαγνωστικών</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="-202"/>
<source>BigBang</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+180"/>
<source>&About BigBang</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Εμφάνισε/Κρύψε</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Αρχείο</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Ρυθμίσεις</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Βοήθεια</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Εργαλειοθήκη καρτελών</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>BigBang client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to BigBang network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About BigBang card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about BigBang card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Ενημερωμένο</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Ενημέρωση...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Η συναλλαγή απεστάλη</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Εισερχόμενη συναλλαγή</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Ημερομηνία: %1
Ποσό: %2
Τύπος: %3
Διεύθυνση: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid BigBang address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>ξεκλείδωτο</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>κλειδωμένο</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n ώρες </numerusform><numerusform>%n ώρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n ημέρες </numerusform><numerusform>%n ημέρες </numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. BigBang can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Ειδοποίηση Δικτύου</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Ποσό:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Επικυρωμένες</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Αντιγραφή επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Αντιγραφή ποσού</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Αντιγραφη του ID Συναλλαγής</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(χωρίς ετικέτα)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Επεξεργασία Διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Διεύθυνση</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Νέα διεύθυνση λήψης</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Νέα διεύθυνση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Επεξεργασία διεύθυνσης λήψης</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Επεξεργασία διεύθυνσης αποστολής</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Η διεύθυνση "%1" βρίσκεται ήδη στο βιβλίο διευθύνσεων.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid BigBang address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Δεν είναι δυνατό το ξεκλείδωμα του πορτοφολιού.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Η δημιουργία νέου κλειδιού απέτυχε.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>BigBang-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Ρυθμίσεις</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Κύριο</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Αμοιβή &συναλλαγής</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start BigBang after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start BigBang on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Δίκτυο</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the BigBang client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Απόδοση θυρών με χρήστη &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the BigBang network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP διαμεσολαβητή:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Θύρα:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Θύρα διαμεσολαβητή</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Έκδοση:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS εκδοση του διαμεσολαβητη (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Παράθυρο</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Εμφάνιση μόνο εικονιδίου στην περιοχή ειδοποιήσεων κατά την ελαχιστοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Ελαχιστοποίηση στην περιοχή ειδοποιήσεων αντί της γραμμής εργασιών</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Ελαχιστοποίηση αντί για έξοδο κατά το κλείσιμο του παραθύρου</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Ε&λαχιστοποίηση κατά το κλείσιμο</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Απεικόνιση</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Γλώσσα περιβάλλοντος εργασίας: </translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting BigBang.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Μονάδα μέτρησης:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Διαλέξτε την προεπιλεγμένη υποδιαίρεση που θα εμφανίζεται όταν στέλνετε νομίσματα.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show BigBang addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Εμφάνιση διευθύνσεων στη λίστα συναλλαγών</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&ΟΚ</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Ακύρωση</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>προεπιλογή</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting BigBang.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the BigBang network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Το τρέχον διαθέσιμο υπόλοιπο</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Ανώριμος</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Εξορυγμενο υπόλοιπο που δεν έχει ακόμα ωριμάσει </translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Σύνολο:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Το τρέχον συνολικό υπόλοιπο</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Πρόσφατες συναλλαγές</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>εκτός συγχρονισμού</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Όνομα Πελάτη</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>Μη διαθέσιμο</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Έκδοση Πελάτη</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Πληροφορία</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Χρησιμοποιηση της OpenSSL εκδοσης</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Χρόνος εκκίνησης</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Δίκτυο</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Αριθμός συνδέσεων</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Αλυσίδα μπλοκ</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Τρέχον αριθμός μπλοκ</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Κατ' εκτίμηση συνολικά μπλοκς</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Χρόνος τελευταίου μπλοκ</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Άνοιγμα</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the BigBang-Qt help message to get a list with possible BigBang command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Κονσόλα</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Ημερομηνία κατασκευής</translation>
</message>
<message>
<location line="-104"/>
<source>BigBang - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>BigBang Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Αρχείο καταγραφής εντοπισμού σφαλμάτων </translation>
</message>
<message>
<location line="+7"/>
<source>Open the BigBang debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Καθαρισμός κονσόλας</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the BigBang RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Χρησιμοποιήστε το πάνω και κάτω βέλος για να περιηγηθείτε στο ιστορικο, και <b>Ctrl-L</b> για εκκαθαριση οθονης.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Γράψτε <b>help</b> για μια επισκόπηση των διαθέσιμων εντολών</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Ποσό:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 BBC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Αποστολή σε πολλούς αποδέκτες ταυτόχρονα</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Προσθήκη αποδέκτη</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Υπόλοιπο:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 BBC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Επιβεβαίωση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>Αποστολη</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a BigBang address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Αντιγραφή ποσού</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Επιβεβαίωση αποστολής νομισμάτων</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Η διεύθυνση του αποδέκτη δεν είναι σωστή. Παρακαλώ ελέγξτε ξανά.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Το ποσό πληρωμής πρέπει να είναι μεγαλύτερο από 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Το ποσό ξεπερνάει το διαθέσιμο υπόλοιπο</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Το σύνολο υπερβαίνει το υπόλοιπό σας όταν συμπεριληφθεί και η αμοιβή %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Βρέθηκε η ίδια διεύθυνση δύο φορές. Επιτρέπεται μία μόνο εγγραφή για κάθε διεύθυνση, σε κάθε διαδικασία αποστολής.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid BigBang address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(χωρίς ετικέτα)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Ποσό:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Πληρωμή &σε:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Εισάγετε μια επιγραφή για αυτή τη διεύθυνση ώστε να καταχωρηθεί στο βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Επικόλληση διεύθυνσης από το πρόχειρο</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a BigBang address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Υπογραφές - Είσοδος / Επαλήθευση μήνυματος </translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Υπογραφή Μηνύματος</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Μπορείτε να υπογράφετε μηνύματα με τις διευθύνσεις σας, ώστε ν' αποδεικνύετε πως αυτές σας ανήκουν. Αποφεύγετε να υπογράφετε κάτι αόριστο καθώς ενδέχεται να εξαπατηθείτε. Υπογράφετε μόνο πλήρης δηλώσεις με τις οποίες συμφωνείτε.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Επικόλληση διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Εισάγετε εδώ το μήνυμα που θέλετε να υπογράψετε</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Αντέγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this BigBang address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Επαναφορά όλων των πεδίων μήνυματος</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Πληκτρολογήστε την υπογραφή διεύθυνσης, μήνυμα (βεβαιωθείτε ότι έχετε αντιγράψει τις αλλαγές γραμμής, κενά, tabs, κ.λπ. ακριβώς) και την υπογραφή παρακάτω, για να ελέγξει το μήνυμα. Να είστε προσεκτικοί για να μην διαβάσετε περισσότερα στην υπογραφή ό, τι είναι στην υπογραφή ίδιο το μήνυμα , για να μην εξαπατηθούν από έναν άνθρωπο -in - the-middle επίθεση.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified BigBang address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Επαναφορά όλων επαλήθευμενων πεδίων μήνυματος </translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a BigBang address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Κάντε κλικ στο "Υπογραφή Μηνύματος" για να λάβετε την υπογραφή</translation>
</message>
<message>
<location line="+3"/>
<source>Enter BigBang signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Η διεύθυνση που εισήχθη είναι λάθος.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Παρακαλούμε ελέγξτε την διεύθυνση και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Η διεύθυνση που έχει εισαχθεί δεν αναφέρεται σε ένα πλήκτρο.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Το προσωπικό κλειδί εισαγμενης διευθυνσης δεν είναι διαθέσιμο.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Η υπογραφή του μηνύματος απέτυχε.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Μήνυμα υπεγράφη.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Η υπογραφή δεν μπόρεσε να αποκρυπτογραφηθεί.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Παρακαλούμε ελέγξτε την υπογραφή και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Η υπογραφή δεν ταιριάζει με το μήνυμα. </translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Η επιβεβαίωση του μηνύματος απέτυχε</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Μήνυμα επιβεβαιώθηκε.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/χωρίς σύνδεση;</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/χωρίς επιβεβαίωση</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 επιβεβαιώσεις</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Κατάσταση</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Πηγή</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Δημιουργία </translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Από</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Προς</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation> δική σας διεύθυνση </translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>eπιγραφή</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Πίστωση </translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>μη αποδεκτό</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Τέλος συναλλαγής </translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Καθαρό ποσό</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Μήνυμα</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Σχόλιο:</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID Συναλλαγής:</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Πληροφορίες αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Συναλλαγή</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>εισροές </translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>αληθής</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>αναληθής </translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, δεν έχει ακόμα μεταδοθεί μ' επιτυχία</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>άγνωστο</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Λεπτομέρειες συναλλαγής</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Αυτό το παράθυρο δείχνει μια λεπτομερή περιγραφή της συναλλαγής</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Τύπος</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Επικυρωμένη (%1 επικυρώσεις)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Αυτό το μπλοκ δεν έχει παραληφθεί από κανέναν άλλο κόμβο και κατά πάσα πιθανότητα θα απορριφθεί!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Δημιουργήθηκε αλλά απορρίφθηκε</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Παραλαβή με</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ελήφθη από</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Αποστολή προς</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Πληρωμή προς εσάς</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Εξόρυξη</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(δ/α)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Κατάσταση συναλλαγής. Πηγαίνετε το ποντίκι πάνω από αυτό το πεδίο για να δείτε τον αριθμό των επικυρώσεων</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Ημερομηνία κι ώρα λήψης της συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Είδος συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Διεύθυνση αποστολής της συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Ποσό που αφαιρέθηκε ή προστέθηκε στο υπόλοιπο.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Όλα</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Σήμερα</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Αυτή την εβδομάδα</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Αυτόν τον μήνα</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Τον προηγούμενο μήνα</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Αυτό το έτος</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Έκταση...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Ελήφθη με</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Απεστάλη προς</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Προς εσάς</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Εξόρυξη</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Άλλο</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Αναζήτηση με βάση τη διεύθυνση ή την επιγραφή</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Ελάχιστο ποσό</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Αντιγραφή επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Αντιγραφή ποσού</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Αντιγραφη του ID Συναλλαγής</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Επεξεργασία επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Εμφάνιση λεπτομερειών συναλλαγής</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Επικυρωμένες</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Τύπος</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Επιγραφή</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Έκταση:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>έως</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>BigBang version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or BigBangd</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Λίστα εντολών</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Επεξήγηση εντολής</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Επιλογές:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: BigBang.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: BigBangd.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Ορισμός φακέλου δεδομένων</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Όρισε το μέγεθος της βάσης προσωρινής αποθήκευσης σε megabytes(προεπιλογή:25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Μέγιστες αριθμός συνδέσεων με τους peers <n> (προεπιλογή: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Σύνδεση σε έναν κόμβο για την ανάκτηση διευθύνσεων από ομοτίμους, και αποσυνδέσh</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Διευκρινίστε τη δικιά σας δημόσια διεύθυνση.</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Όριο αποσύνδεσης προβληματικών peers (προεπιλογή: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Δευτερόλεπτα πριν επιτραπεί ξανά η σύνδεση των προβληματικών peers (προεπιλογή: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η πόρτα RPC %u για αναμονή IPv4: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Αποδοχή εντολών κονσόλας και JSON-RPC</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Εκτέλεση στο παρασκήνιο κι αποδοχή εντολών</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Χρήση του δοκιμαστικού δικτύου</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Να δέχεσαι συνδέσεις από έξω(προεπιλογή:1)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η υποδοχη RPC %u για αναμονη του IPv6, επεσε πισω στο IPv4:%s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Προειδοποίηση: Η παράμετρος -paytxfee είναι πολύ υψηλή. Πρόκειται για την αμοιβή που θα πληρώνετε για κάθε συναλλαγή που θα στέλνετε.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong BigBang will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Προειδοποίηση : Σφάλμα wallet.dat κατα την ανάγνωση ! Όλα τα κλειδιά αναγνωρισθηκαν σωστά, αλλά τα δεδομένα των συναλλαγών ή καταχωρήσεις στο βιβλίο διευθύνσεων μπορεί να είναι ελλιπείς ή λανθασμένα. </translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Προειδοποίηση : το αρχειο wallet.dat ειναι διεφθαρμένο, τα δεδομένα σώζονται ! Original wallet.dat αποθηκεύονται ως wallet.{timestamp}.bak στο %s . Αν το υπόλοιπο του ή τις συναλλαγές σας, είναι λάθος θα πρέπει να επαναφέρετε από ένα αντίγραφο ασφαλείας</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Προσπάθεια για ανακτησει ιδιωτικων κλειδιων από ενα διεφθαρμένο αρχειο wallet.dat </translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Αποκλεισμός επιλογων δημιουργίας: </translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Σύνδεση μόνο με ορισμένους κόμβους</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Ανακαλύψτε την δικη σας IP διεύθυνση (προεπιλογή: 1 όταν ακούει και δεν - externalip) </translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>ταλαιπωρηθειτε για να ακούσετε σε οποιαδήποτε θύρα. Χρήση - ακούστε = 0 , αν θέλετε αυτό.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Μέγιστος buffer λήψης ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Μέγιστος buffer αποστολής ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation> Συνδέση μόνο σε κόμβους του δικτύου <net> (IPv4, IPv6 ή Tor) </translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Ρυθμίσεις SSL: (ανατρέξτε στο Bitcoin Wiki για οδηγίες ρυθμίσεων SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στην κονσόλα αντί του αρχείου debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Ορίστε το μέγιστο μέγεθος μπλοκ σε bytes (προεπιλογή: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Συρρίκνωση του αρχείο debug.log κατα την εκκίνηση του πελάτη (προεπιλογή: 1 όταν δεν-debug)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Ορισμός λήξης χρονικού ορίου σε χιλιοστά του δευτερολέπτου(προεπιλογή:5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:1)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Όνομα χρήστη για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Προειδοποίηση: Αυτή η έκδοση είναι ξεπερασμένη, απαιτείται αναβάθμιση </translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>Το αρχειο wallet.dat ειναι διεφθαρμένο, η διάσωση απέτυχε</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Κωδικός για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=BigBangrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "BigBang Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Αποδοχή συνδέσεων JSON-RPC από συγκεκριμένη διεύθυνση IP</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Αποστολή εντολών στον κόμβο <ip> (προεπιλογή: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Αναβάθμισε το πορτοφόλι στην τελευταία έκδοση</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Όριο πλήθους κλειδιών pool <n> (προεπιλογή: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Επανέλεγχος της αλυσίδας μπλοκ για απούσες συναλλαγές</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Χρήση του OpenSSL (https) για συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Αρχείο πιστοποιητικού του διακομιστή (προεπιλογή: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Προσωπικό κλειδί του διακομιστή (προεπιλογή: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Αυτό το κείμενο βοήθειας</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. BigBang is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>BigBang</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή (bind returned error %d, %s) </translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Να επιτρέπονται οι έλεγχοι DNS για προσθήκη και σύνδεση κόμβων</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Φόρτωση διευθύνσεων...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Κατεστραμμένο Πορτοφόλι</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of BigBang</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart BigBang to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Σφάλμα φόρτωσης αρχείου wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Άγνωστo δίκτυο ορίζεται σε onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Άγνωστo δίκτυο ορίζεται: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Λάθος ποσότητα</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Ανεπαρκές κεφάλαιο</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Προσέθεσε ένα κόμβο για σύνδεση και προσπάθησε να κρατήσεις την σύνδεση ανοιχτή</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. BigBang is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Φόρτωση πορτοφολιού...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Δεν μπορώ να υποβαθμίσω το πορτοφόλι</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Ανίχνευση...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Η φόρτωση ολοκληρώθηκε</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Χρήση της %s επιλογής</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Σφάλμα</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Πρέπει να βάλεις ένα κωδικό στο αρχείο παραμέτρων: %s
Εάν το αρχείο δεν υπάρχει, δημιούργησε το με δικαιώματα μόνο για ανάγνωση από τον δημιουργό</translation>
</message>
</context>
</TS> | Lefter1s/BigBang | src/qt/locale/bitcoin_el_GR.ts | TypeScript | mit | 128,896 |
<?php
function event_stat_alexa_calculated($ranks){
}
function event_stat_similarweb_calculated($ranks){
} | iqbalfn/admin | application/events/stat.php | PHP | mit | 114 |
// ***********************************************************************
// <copyright file="AssemblyInfo.cs" company="Holotrek">
// Copyright © Holotrek 2016
// </copyright>
// ***********************************************************************
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Kore.Domain.EF.Tests")]
[assembly: AssemblyDescription("Tests for the Holotrek's Entity Framework Core")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Holotrek")]
[assembly: AssemblyProduct("Kore.Domain.EF.Tests")]
[assembly: AssemblyCopyright("Copyright © Holotrek 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ec0e5775-8da3-4994-9148-9c5eb80af625")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.*")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| holotrek/kore-csharp | Kore/Domain/EF/Kore.Domain.EF.Tests/Properties/AssemblyInfo.cs | C# | mit | 1,736 |
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_PHPMailer {
public function My_PHPMailer()
{
require_once('class.phpmailer.php');
}
}
?> | ProyectoDAW2/Proyecto | application/libraries/my_phpmailer.php | PHP | mit | 177 |
<?php
return array(
'service_manager' => array(
'factories' => array(
'Twilio\Options\ModuleOptions' => 'Twilio\Options\Factory\ModuleOptionsFactory',
'Twilio\Service\TwilioService' => 'Twilio\Service\Factory\TwilioServiceFactory'
)
)
);
| al3xdm/Twilio | config/module.config.php | PHP | mit | 287 |
<?php
$lang['date_year'] = 'Ano';
$lang['date_years'] = 'Anos';
$lang['date_month'] = 'Mês';
$lang['date_months'] = 'Meses';
$lang['date_week'] = 'Semana';
$lang['date_weeks'] = 'Semanas';
$lang['date_day'] = 'Dia';
$lang['date_days'] = 'Dias';
$lang['date_hour'] = 'Hora';
$lang['date_hours'] = 'Horas';
$lang['date_minute'] = 'Minuto';
$lang['date_minutes'] = 'Minutos';
$lang['date_second'] = 'Segundo';
$lang['date_seconds'] = 'Segundos';
$lang['UM12'] = '(UTC -12:00) Baker/Howland Island';
$lang['UM11'] = '(UTC -11:00) Samoa Time Zone, Niue';
$lang['UM10'] = '(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti';
$lang['UM95'] = '(UTC -9:30) Marquesas Islands';
$lang['UM9'] = '(UTC -9:00) Alaska Standard Time, Gambier Islands';
$lang['UM8'] = '(UTC -8:00) Pacific Standard Time, Clipperton Island';
$lang['UM7'] = '(UTC -7:00) Mountain Standard Time';
$lang['UM6'] = '(UTC -6:00) Central Standard Time';
$lang['UM5'] = '(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time';
$lang['UM45'] = '(UTC -4:30) Venezuelan Standard Time';
$lang['UM4'] = '(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time';
$lang['UM35'] = '(UTC -3:30) Newfoundland Standard Time';
$lang['UM3'] = '(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay';
$lang['UM2'] = '(UTC -2:00) South Georgia/South Sandwich Islands';
$lang['UM1'] = '(UTC -1:00) Azores, Cape Verde Islands';
$lang['UTC'] = '(UTC) Greenwich Mean Time, Western European Time';
$lang['UP1'] = '(UTC +1:00) Central European Time, West Africa Time';
$lang['UP2'] = '(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time';
$lang['UP3'] = '(UTC +3:00) Moscow Time, East Africa Time';
$lang['UP35'] = '(UTC +3:30) Iran Standard Time';
$lang['UP4'] = '(UTC +4:00) Azerbaijan Standard Time, Samara Time';
$lang['UP45'] = '(UTC +4:30) Afghanistan';
$lang['UP5'] = '(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time';
$lang['UP55'] = '(UTC +5:30) Indian Standard Time, Sri Lanka Time';
$lang['UP575'] = '(UTC +5:45) Nepal Time';
$lang['UP6'] = '(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time';
$lang['UP65'] = '(UTC +6:30) Cocos Islands, Myanmar';
$lang['UP7'] = '(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam';
$lang['UP8'] = '(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time';
$lang['UP875'] = '(UTC +8:45) Australian Central Western Standard Time';
$lang['UP9'] = '(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time';
$lang['UP95'] = '(UTC +9:30) Australian Central Standard Time';
$lang['UP10'] = '(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time';
$lang['UP105'] = '(UTC +10:30) Lord Howe Island';
$lang['UP11'] = '(UTC +11:00) Magadan Time, Solomon Islands, Vanuatu';
$lang['UP115'] = '(UTC +11:30) Norfolk Island';
$lang['UP12'] = '(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time';
$lang['UP1275'] = '(UTC +12:45) Chatham Islands Standard Time';
$lang['UP13'] = '(UTC +13:00) Phoenix Islands Time, Tonga';
$lang['UP14'] = '(UTC +14:00) Line Islands';
| srpurdy/SharpEdgeCMS | framework_2_2_3/language/pt-BR/date_lang.php | PHP | mit | 3,088 |
// Package time extends the time package in the stdlib.
package time
| goph/stdlib | time/time.go | GO | mit | 69 |
/* eslint-disable node/no-deprecated-api */
module.exports.pathBasename = pathBasename
module.exports.hasSuffix = hasSuffix
module.exports.serialize = serialize
module.exports.translate = translate
module.exports.stringToStream = stringToStream
module.exports.debrack = debrack
module.exports.stripLineEndings = stripLineEndings
module.exports.fullUrlForReq = fullUrlForReq
module.exports.routeResolvedFile = routeResolvedFile
module.exports.getQuota = getQuota
module.exports.overQuota = overQuota
module.exports.getContentType = getContentType
module.exports.parse = parse
const fs = require('fs')
const path = require('path')
const util = require('util')
const $rdf = require('rdflib')
const from = require('from2')
const url = require('url')
const debug = require('./debug').fs
const getSize = require('get-folder-size')
const ns = require('solid-namespace')($rdf)
/**
* Returns a fully qualified URL from an Express.js Request object.
* (It's insane that Express does not provide this natively.)
*
* Usage:
*
* ```
* console.log(util.fullUrlForReq(req))
* // -> https://example.com/path/to/resource?q1=v1
* ```
*
* @param req {IncomingRequest}
*
* @return {string}
*/
function fullUrlForReq (req) {
const fullUrl = url.format({
protocol: req.protocol,
host: req.get('host'),
pathname: url.resolve(req.baseUrl, req.path),
query: req.query
})
return fullUrl
}
/**
* Removes the `<` and `>` brackets around a string and returns it.
* Used by the `allow` handler in `verifyDelegator()` logic.
* @method debrack
*
* @param s {string}
*
* @return {string}
*/
function debrack (s) {
if (!s || s.length < 2) {
return s
}
if (s[0] !== '<') {
return s
}
if (s[s.length - 1] !== '>') {
return s
}
return s.substring(1, s.length - 1)
}
async function parse (data, baseUri, contentType) {
const graph = $rdf.graph()
return new Promise((resolve, reject) => {
try {
return $rdf.parse(data, graph, baseUri, contentType, (err, str) => {
if (err) {
return reject(err)
}
resolve(str)
})
} catch (err) {
return reject(err)
}
})
}
function pathBasename (fullpath) {
let bname = ''
if (fullpath) {
bname = (fullpath.lastIndexOf('/') === fullpath.length - 1)
? ''
: path.basename(fullpath)
}
return bname
}
function hasSuffix (path, suffixes) {
for (const i in suffixes) {
if (path.indexOf(suffixes[i], path.length - suffixes[i].length) !== -1) {
return true
}
}
return false
}
function serialize (graph, baseUri, contentType) {
return new Promise((resolve, reject) => {
try {
// target, kb, base, contentType, callback
$rdf.serialize(null, graph, baseUri, contentType, function (err, result) {
if (err) {
return reject(err)
}
if (result === undefined) {
return reject(new Error('Error serializing the graph to ' +
contentType))
}
resolve(result)
})
} catch (err) {
reject(err)
}
})
}
function translate (stream, baseUri, from, to) {
return new Promise((resolve, reject) => {
let data = ''
stream
.on('data', function (chunk) {
data += chunk
})
.on('end', function () {
const graph = $rdf.graph()
$rdf.parse(data, graph, baseUri, from, function (err) {
if (err) return reject(err)
resolve(serialize(graph, baseUri, to))
})
})
})
}
function stringToStream (string) {
return from(function (size, next) {
// if there's no more content
// left in the string, close the stream.
if (!string || string.length <= 0) {
return next(null, null)
}
// Pull in a new chunk of text,
// removing it from the string.
const chunk = string.slice(0, size)
string = string.slice(size)
// Emit "chunk" from the stream.
next(null, chunk)
})
}
/**
* Removes line endings from a given string. Used for WebID TLS Certificate
* generation.
*
* @param obj {string}
*
* @return {string}
*/
function stripLineEndings (obj) {
if (!obj) { return obj }
return obj.replace(/(\r\n|\n|\r)/gm, '')
}
/**
* Adds a route that serves a static file from another Node module
*/
function routeResolvedFile (router, path, file, appendFileName = true) {
const fullPath = appendFileName ? path + file.match(/[^/]+$/) : path
const fullFile = require.resolve(file)
router.get(fullPath, (req, res) => res.sendFile(fullFile))
}
/**
* Returns the number of bytes that the user owning the requested POD
* may store or Infinity if no limit
*/
async function getQuota (root, serverUri) {
const filename = path.join(root, 'settings/serverSide.ttl')
let prefs
try {
prefs = await _asyncReadfile(filename)
} catch (error) {
debug('Setting no quota. While reading serverSide.ttl, got ' + error)
return Infinity
}
const graph = $rdf.graph()
const storageUri = serverUri + '/'
try {
$rdf.parse(prefs, graph, storageUri, 'text/turtle')
} catch (error) {
throw new Error('Failed to parse serverSide.ttl, got ' + error)
}
return Number(graph.anyValue($rdf.sym(storageUri), ns.solid('storageQuota'))) || Infinity
}
/**
* Returns true of the user has already exceeded their quota, i.e. it
* will check if new requests should be rejected, which means they
* could PUT a large file and get away with it.
*/
async function overQuota (root, serverUri) {
const quota = await getQuota(root, serverUri)
if (quota === Infinity) {
return false
}
// TODO: cache this value?
const size = await actualSize(root)
return (size > quota)
}
/**
* Returns the number of bytes that is occupied by the actual files in
* the file system. IMPORTANT NOTE: Since it traverses the directory
* to find the actual file sizes, this does a costly operation, but
* neglible for the small quotas we currently allow. If the quotas
* grow bigger, this will significantly reduce write performance, and
* so it needs to be rewritten.
*/
function actualSize (root) {
return util.promisify(getSize)(root)
}
function _asyncReadfile (filename) {
return util.promisify(fs.readFile)(filename, 'utf-8')
}
/**
* Get the content type from a headers object
* @param headers An Express or Fetch API headers object
* @return {string} A content type string
*/
function getContentType (headers) {
const value = headers.get ? headers.get('content-type') : headers['content-type']
return value ? value.replace(/;.*/, '') : 'application/octet-stream'
}
| linkeddata/ldnode | lib/utils.js | JavaScript | mit | 6,588 |
Template.postSubmit.onCreated(function() {
Session.set('postSubmitErrors', {});
});
Template.postSubmit.helpers({
errorMessage: function(field) {
return Session.get('postSubmitErrors')[field];
},
errorClass: function (field) {
return !!Session.get('postSubmitErrors')[field] ? 'has-error' : '';
}
});
Template.postSubmit.onRendered(function(){
// AutoForm.hooks({
// postSubmitForm: hooksObject
// });
});
// Template.postSubmit.events({
// 'submit form': function(e) {
// e.preventDefault();
// var post = {
// url: $(e.target).find('[name=url]').val(),
// title: $(e.target).find('[name=title]').val()
// };
// var errors = validatePost(post);
// if (errors.title || errors.url)
// return Session.set('postSubmitErrors', errors);
// Meteor.call('postInsert', post, function(error, result) {
// // display the error to the user and abort
// if (error)
// return throwError(error.reason);
// // show this result but route anyway
// if (result.postExists)
// throwError('This link has already been posted');
// Router.go('postPage', {_id: result._id});
// });
// }
// }); | fuzzybabybunny/microscope-orionjs | client/templates/posts/post_submit.js | JavaScript | mit | 1,228 |
<?php
// Text
$_['text_sizechart'] = 'Größentabelle';
| trydalcoholic/opencart-materialize | source/opencart_3.0.x/upload/catalog/language/de-de/extension/module/sizechart.php | PHP | mit | 56 |
package ru.mephi.interpreter;
import org.antlr.v4.runtime.tree.ParseTree;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Anton_Chkadua
*/
public class Scope {
static Scope GLOBAL = new Scope(null);
private Scope parent;
private Map<BigInteger, Variable> variables = new HashMap<>();
private Map<Function, ParseTree> functions = new HashMap<>();
private BigInteger memoryCounter = BigInteger.ZERO;
Scope(Scope parent) {
this.parent = parent;
if (parent != null) {
memoryCounter = parent.getMemoryCounter();
}
}
private BigInteger getMemoryCounter() {
return memoryCounter;
}
void add(Variable variable) throws RuntimeLangException {
if (variables.values().contains(variable)) {
throw new RuntimeLangException(RuntimeLangException.Type.DUPLICATE_IDENTIFIER);
}
if (variable instanceof Array) {
((Array) variable).setScope(this);
for (int i = 0; i < ((Array) variable).memoryLength; i++) {
variables.put(memoryCounter, variable);
memoryCounter = memoryCounter.add(BigInteger.ONE);
}
} else {
variables.put(memoryCounter, variable);
memoryCounter = memoryCounter.add(BigInteger.ONE);
}
}
public void remove(String name) throws RuntimeLangException {
Variable toBeRemoved = get(name);
BigInteger address = variables.keySet().stream().filter(key -> variables.get(key).equals(toBeRemoved)).findFirst().orElseThrow(() -> new RuntimeLangException(
RuntimeLangException.Type.NO_SUCH_VARIABLE));
variables.remove(address);
}
Scope getParent() {
return parent;
}
Variable get(String name) throws RuntimeLangException {
Variable candidate =
variables.values().stream().filter(variable -> variable.getName().equals(name)).findAny()
.orElse(null);
if (candidate == null) {
if (parent != null) {
candidate = parent.get(name);
} else {
throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_VARIABLE);
}
}
return candidate;
}
Variable getByAddress(Pointer pointer) throws RuntimeLangException {
Variable variable = variables.get(pointer.getValue());
System.out.println(variable);
if (variable instanceof Array)
{
int address = getVariableAddress(variable).intValue();
int index = pointer.getValue().intValue() - address;
return variable.getElement(index);
} else {
return variable;
}
}
void setValueByAddress(Pointer pointer, BigInteger value) throws RuntimeLangException {
if (pointer.constantValue) throw new RuntimeLangException(RuntimeLangException.Type.ILLEGAL_MODIFICATION);
variables.get(pointer.getValue()).setValue(value);
}
BigInteger getVariableAddress(Variable variable) throws RuntimeLangException {
if (!variables.values().contains(variable)) {
throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_VARIABLE);
}
for (Map.Entry<BigInteger, Variable> entry : variables.entrySet()) {
if (entry.getValue().name.equals(variable.name)) return entry.getKey();
}
return null;
}
void addFunction(Function function, ParseTree functionTree) throws RuntimeLangException {
if (functions.containsKey(function)) {
throw new RuntimeLangException(RuntimeLangException.Type.DUPLICATE_IDENTIFIER);
}
functions.put(function, functionTree);
}
ParseTree getFunctionTree(String name, List<Class> types) throws RuntimeLangException {
ParseTree tree = functions.get(getFunction(name, types));
if (tree == null) {
if (parent != null) {
tree = parent.getFunctionTree(name, types);
} else {
throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION);
}
}
return tree;
}
Function getFunction(String name, List<Class> types) throws RuntimeLangException {
Map.Entry<Function, ParseTree> entryCandidate =
functions.entrySet().stream().filter(entry -> entry.getKey().name.equals(name)).findAny()
.orElse(null);
Function candidate = null;
if (entryCandidate == null) {
if (parent != null) {
candidate = parent.getFunction(name, types);
}
} else {
candidate = entryCandidate.getKey();
}
if (candidate == null) {
if (name.equals("main")) {
throw new RuntimeLangException(RuntimeLangException.Type.NO_MAIN_FUNCTION);
} else {
throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION);
}
}
if (candidate.args.size() != types.size()) {
throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION);
}
for (int i = 0; i < candidate.args.size(); i++) {
if (!candidate.args.get(i).getType().equals(types.get(i))) {
throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION);
}
}
return candidate;
}
@Override
public String toString() {
String parent = this.parent != null ? this.parent.toString() : "";
StringBuilder builder = new StringBuilder();
for (Variable variable : variables.values()) {
builder.append(variable.getName()).append("-").append(variable.getType()).append("-length-")
.append(variable.getLength());
try {
builder.append("-value-").append(variable.getValue()).append('-').append(variable.constantValue)
.append("\r\n");
} catch (RuntimeLangException e) {
System.out.println(e.getType());
}
}
return builder.insert(0, parent).toString();
}
}
| AVChkadua/interpreter | src/ru/mephi/interpreter/Scope.java | Java | mit | 6,273 |
<?php
return array (
'id' => 'sec_e900_ver1_sub10',
'fallback' => 'sec_e900_ver1',
'capabilities' =>
array (
'accept_third_party_cookie' => 'false',
'j2me_max_jar_size' => '700000',
'ajax_support_getelementbyid' => 'true',
'ajax_support_events' => 'true',
),
);
| cuckata23/wurfl-data | data/sec_e900_ver1_sub10.php | PHP | mit | 289 |
<?php
return array (
'id' => 'dell_streak_7_ver1_suban32',
'fallback' => 'dell_streak_7_ver1',
'capabilities' =>
array (
'device_os_version' => '3.2',
),
);
| cuckata23/wurfl-data | data/dell_streak_7_ver1_suban32.php | PHP | mit | 172 |
#include <cstring>
#include <iostream>
#include <algorithm>
#include "matcher.h"
#include "edit.h"
#include "char.h"
#include "instrumentation.h"
#define INIT_POS -1
#define __DEBUG__ false
// the node represented by a given point
#define node(p) (distances[(p)->j][(p)->i])
// the edit distance at a given point, from the distance matrix
#define dist(p) (node(p).distance)
using namespace std;
// simply reverses a string in place
void strrev(char *str, int len) {
for(int i = 0; i < len / 2; i++) {
std::swap(str[i], str[len - i - 1]);
}
}
// empty constructor
EditTable::EditTable() {
}
// destructor
EditTable::~EditTable() {
// free the rows of the table
free_rows();
// free the table itself
delete[] distances;
// get rid of the best match
if(best_match != NULL) {
delete best_match;
}
}
// compares the 3 given points based on their given distances, and
// returns the point with the lowest distance
Point *min3(Point *p1, int d1, Point *p2, int d2, Point *p3, int d3) {
if(d1 < d2) {
return d1 < d3 ? p1 : p3;
} else {
return d2 < d3 ? p2 : p3;
}
}
// get the point surrounding (j,i) with the minimum distance
Point *EditTable::min_neighbour(int j, int i) {
// the only valid surrounding for the top-corner is (0,0)
if(j == 1 && i == 1) {
return new Point(0, 0);
// if we're in the top row, we can't go up any higher
} else if(j == 1) {
return new Point(j, i - 1);
// if we're in the leftmost column, we CAN go more left
// (since it just means we're starting the match from there)
} else if(i == 1) {
return new Point(j, 0);
// otherwise,
} else {
// 3 comparisons here
inc_comparisons(3);
return min3(
// just above it
new Point(j - 1, i),
distances[j - 1][i].distance,
// just to its left
new Point(j, i - 1),
distances[j][i - 1].distance,
// top-left corner
new Point(j - 1, i - 1),
distances[j - 1][i - 1].distance +
// add 1 if we need a replacement
(text[j - 1] == query->query_str[i - 1] ? 0 : 1)
);
}
}
// j is the index into the text,
// i is the index into the query
// assuming j != 0 and i != 0
int EditTable::set_distance(int j, int i) {
Node &node = distances[j][i];
// get the valid neighbour with the minimum edit distance
node.from = min_neighbour(j, i);
node.distance = dist(node.from);
// if the two characters at this node are different,
if( query->query_str[i - 1] != text[j - 1] ) {
// add 1 to the edit distance (replacement)
node.distance++;
}
// return the edit distance of this node
return node.distance;
}
// dump the whole table
void EditTable::dump() {
// print the query characters
cerr << '\t';
for(int i = 0; i < query->query_len; i++) {
cerr << '\t';
pc(cerr, query->query_str[i]);
}
cerr << endl;
for(int j = 0; j <= text_len; j++) {
for(int i = 0; i <= query->query_len; i++) {
// print the text characters
if(i == 0 && j != 0) {
pc(cerr, text[j - 1]);
}
cerr << '\t';
// print the actual distance
cerr << distances[j][i].distance;
}
cerr << endl;
}
}
// traceback the best match
SearchResult *EditTable::get_match() {
SearchResult *result;
// if there is no match, return an empty search result
if(best_match->j == INIT_POS) {
return new SearchResult(0);
}
// if the match has too high a distance, return an empty search result
if(dist(best_match) > query->errors_allowed) {
return new SearchResult(0);
}
// allocate memory for the result
result = new SearchResult(query->query_len + query->errors_allowed);
// the easy stuff first
result->errors = dist(best_match);
result->match_len = 0;
// start off at the node with the best match
Point *current = best_match;
while(current != NULL) {
// add the next char to the result
result->match[result->match_len++] = text[current->j - 1];
// advance to the next node
current = node(current).from;
}
// we don't really want to include the \0 char
result->match_len--;
// reverse the string in place
strrev(result->match, result->match_len);
/*// print the result
if(__DEBUG__) {
pc(cerr, result->match, result->match_len);
cerr << endl;
}*/
return result;
}
void EditTable::free_rows() {
// free the rows of the table
for(int j = 0; j <= text_len; j++) {
if(query != NULL) {
delete[] distances[j];
}
}
}
void EditTable::fill_table() {
// there are going to be the same amount of creates/accesses here
inc_comparisons((text_len + 1) * (query->query_len + 1));
inc_ds((text_len + 1) * (query->query_len + 1));
// reset the best match
best_match = new Point(INIT_POS, INIT_POS);
// the first row and column have a distance 0
for(int j = 0; j <= text_len; j++) {
// allocate memory for each row
distances[j] = new Node[text_len + 1];
// set the first column to 0
distances[j][0].distance = 0;
}
for(int i = 0; i <= query->query_len; i++) {
// set the first row to 0
distances[0][i].distance = 0;
}
// first go through the text (rows)
for(int j = 1; j <= text_len; j++) {
// then go through the query (columns)
for(int i = 1; i <= query->query_len; i++) {
// work out the edit distance
set_distance(j, i);
// if we're in the last column (the end of the query string),
// [remember matches only happen at the end of the query string]
if(i == query->query_len) {
// if this is the first time we get to the end of the query,
// or if it's got a lower edit distance than the current
// best match,
if( best_match->j == INIT_POS ||
distances[j][i].distance < dist(best_match) ) {
// then update the best match to be this point
best_match->j = j;
best_match->i = i;
}
}
}
}
}
SearchResult *EditTable::execute_query(SearchQuery *query) {
SearchResult *result;
// save the query
this->query = query;
// fill the table
this->fill_table();
// dump it
if(__DEBUG__) {
this->dump();
}
// get the best match
result = get_match();
// finally, return the match
return result;
}
void EditTable::load_text(char *text, int len) {
// save these values
this->text = new char[len];
strncpy(this->text, text, len);
this->text_len = len;
// build an empty array
this->distances = new Node *[text_len + 1];
}
// used by main which doesn't know about the EditTable
Matcher *create_matcher() {
return new EditTable();
}
| pmansour/algorithms | string-matching/edittable-and-tries/edit.cpp | C++ | mit | 6,604 |
<?php
/*
* This file is part of the Beloop package.
*
* Copyright (c) 2016 AHDO Studio B.V.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Arkaitz Garro <arkaitz.garro@gmail.com>
*/
namespace Beloop\Bundle\InstagramBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\KernelInterface;
use Beloop\Bundle\CoreBundle\Abstracts\AbstractBundle;
use Beloop\Bundle\InstagramBundle\CompilerPass\MappingCompilerPass;
use Beloop\Bundle\InstagramBundle\DependencyInjection\BeloopInstagramExtension;
/**
* BeloopInstagramBundle Bundle.
*/
class BeloopInstagramBundle extends AbstractBundle
{
/**
* @param ContainerBuilder $container
*/
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new MappingCompilerPass());
}
/**
* Returns the bundle's container extension.
*
* @return ExtensionInterface The container extension
*/
public function getContainerExtension()
{
return new BeloopInstagramExtension();
}
/**
* Create instance of current bundle, and return dependent bundle namespaces.
*
* @param KernelInterface $kernel
* @return array Bundle instances
*/
public static function getBundleDependencies(KernelInterface $kernel)
{
return [
'Beloop\Bundle\CoreBundle\BeloopCoreBundle',
'Beloop\Bundle\CoreBundle\BeloopUserBundle',
];
}
}
| beloop/components | src/Beloop/Bundle/InstagramBundle/BeloopInstagramBundle.php | PHP | mit | 1,660 |
import { IQuotation } from '../../model/QuotationService/IQuotation';
export interface IQuoteDisplayProps {
quote: IQuotation;
}
| BobGerman/SPFx | quotes/src/webparts/quoteDisplay/components/QuoteDisplay/IQuoteDisplayProps.ts | TypeScript | mit | 132 |
version https://git-lfs.github.com/spec/v1
oid sha256:c4d5490597798effaf63d11e546f0b200f196f28e17c69d39ce236de0c6683f0
size 64139
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.2/scrollview-paginator/scrollview-paginator-coverage.js | JavaScript | mit | 130 |
module Souschef
# Loads Souschef configuration YAML
class Config
# Public - Reads the configuration file
#
# Returns Hash
def self.read
verify_file
YAML.load_file(File.expand_path('~/.souschef.yml'))
end
# Private - Checks if we have a configuraiton file
#
# Returns nil
def self.verify_file
conf = File.expand_path('~/.souschef.yml')
fail "'~/.souschef.yml' missing!" unless File.exist?(conf)
end
end
end
| akrasic/souschef | lib/souschef/config.rb | Ruby | mit | 477 |
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"os/user"
"path/filepath"
"strings"
"crypto/tls"
"net/http"
)
type configCommand struct {
config *ClientConfig
}
// skipVerifyHTTPClient returns an *http.Client with InsecureSkipVerify set
// to true for its TLS config. This allows self-signed SSL certificates.
func skipVerifyHTTPClient(skipVerify bool) *http.Client {
if skipVerify {
tlsConfig := &tls.Config{InsecureSkipVerify: true}
transport := &http.Transport{TLSClientConfig: tlsConfig}
return &http.Client{Transport: transport}
}
return http.DefaultClient
}
func (cmd *configCommand) Run(args []string) error {
if len(args) < 1 {
cmd.Usage()
os.Exit(1)
}
var config *ClientConfig
if cfg, err := LoadClientConfig(); err == nil {
config = cfg
} else {
config = new(ClientConfig)
}
var run func(*ClientConfig, []string) error
switch strings.ToLower(args[0]) {
case "set":
run = setCmd
case "print":
printConfig()
return nil
default:
cmd.Usage()
os.Exit(1)
}
return run(config, args[1:])
}
func printConfig() {
path, err := clientConfigPath()
if err != nil {
log.Fatal(err)
}
cfgData, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(cfgData))
}
func (cmd *configCommand) Usage() error {
const help = `
mdmctl config print
mdmctl config set -h
`
fmt.Println(help)
return nil
}
func setCmd(cfg *ClientConfig, args []string) error {
flagset := flag.NewFlagSet("set", flag.ExitOnError)
var (
flToken = flagset.String("api-token", "", "api token to connect to micromdm server")
flServerURL = flagset.String("server-url", "", "server url of micromdm server")
flSkipVerify = flagset.Bool("skip-verify", false, "skip verification of server certificate (insecure)")
)
flagset.Usage = usageFor(flagset, "mdmctl config set [flags]")
if err := flagset.Parse(args); err != nil {
return err
}
if *flToken != "" {
cfg.APIToken = *flToken
}
if *flServerURL != "" {
if !strings.HasPrefix(*flServerURL, "http") ||
!strings.HasPrefix(*flServerURL, "https") {
*flServerURL = "https://" + *flServerURL
}
u, err := url.Parse(*flServerURL)
if err != nil {
return err
}
u.Scheme = "https"
u.Path = "/"
cfg.ServerURL = u.String()
}
cfg.SkipVerify = *flSkipVerify
return SaveClientConfig(cfg)
}
func clientConfigPath() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
return filepath.Join(usr.HomeDir, ".micromdm", "default.json"), err
}
func SaveClientConfig(cfg *ClientConfig) error {
configPath, err := clientConfigPath()
if err != nil {
return err
}
if _, err := os.Stat(filepath.Dir(configPath)); os.IsNotExist(err) {
if err := os.MkdirAll(filepath.Dir(configPath), 0777); err != nil {
return err
}
}
f, err := os.OpenFile(configPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer f.Close()
if cfg == nil {
cfg = new(ClientConfig)
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
return enc.Encode(cfg)
}
func LoadClientConfig() (*ClientConfig, error) {
path, err := clientConfigPath()
if err != nil {
return nil, err
}
cfgData, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("unable to load default config file: %s", err)
}
var cfg ClientConfig
err = json.Unmarshal(cfgData, &cfg)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal %s : %s", path, err)
}
return &cfg, nil
}
type ClientConfig struct {
APIToken string `json:"api_token"`
ServerURL string `json:"server_url"`
SkipVerify bool `json:"skip_verify"`
}
| natewalck/micromdm | cmd/mdmctl/config.go | GO | mit | 3,654 |
module PlazrStore
VERSION = "0.0.1"
end
| Plazr/plazr_store | lib/plazr_store/version.rb | Ruby | mit | 42 |
/*
* TestProxy.cpp
*
* Created on: Sep 6, 2013
* Author: penrique
*/
#include "InvocationManager.h"
#include <bb/system/CardDoneMessage>
#include <bb/system/InvokeRequest>
// to send number data while invoking phone application
#include <bb/PpsObject>
// Map
#include <bb/platform/LocationMapInvoker>
#include <bb/platform/RouteMapInvoker>
// contacts
#include <bb/cascades/pickers/ContactPicker>
using namespace bb::system;
using namespace bb::platform;
using namespace bb::cascades::pickers;
InvocationManager::InvocationManager(const char* name) :
Ti::TiProxy(name) {
// Create a method, it also has to start with `_`
createPropertyFunction("openURL", _openURLMethod);
createPropertyFunction("callPhoneNumber", _callPhoneNumberMethod);
createPropertyFunction("facebookShare", _facebookShareMethod);
createPropertyFunction("openSettings", _openSettingsMethod);
createPropertyFunction("openPdf", _openPdfMethod);
createPropertyFunction("openMap", _openMapMethod);
createPropertyFunction("openContacts", _openContactsMethod);
}
InvocationManager::~InvocationManager() {
// delete instatiated pointers
}
Ti::TiValue InvocationManager::openURLMethod(Ti::TiValue url) {
Ti::TiValue returnValue;
returnValue.toBool();
if (invokeReply_ && !invokeReply_->isFinished()) {
// Don't send another invoke request if one is already pending.
return returnValue;
}
// convert variable to QString
QString myUrl = url.toString();
InvokeRequest request;
request.setTarget("sys.browser");
request.setAction("bb.action.OPEN");
request.setUri(myUrl);
invokeReply_ = invokeManager_.invoke(request);
if (!invokeReply_) {
fprintf(stderr, "Failed to invoke this card\n");
return returnValue;
}
returnValue.setBool(true);
return returnValue;
}
Ti::TiValue InvocationManager::callPhoneNumberMethod(Ti::TiValue number) {
Ti::TiValue returnValue;
returnValue.toBool();
if (invokeReply_ && !invokeReply_->isFinished()) {
// Don't send another invoke request if one is already pending.
return returnValue;
}
// convert variable to QString
QString myNumber = number.toString();
QVariantMap map;
map.insert("number", myNumber);
QByteArray requestData = bb::PpsObject::encode(map, NULL);
InvokeRequest request;
request.setAction("bb.action.DIAL");
request.setMimeType("application/vnd.blackberry.phone.startcall");
request.setData(requestData);
invokeReply_ = invokeManager_.invoke(request);
if (!invokeReply_) {
fprintf(stderr, "Failed to invoke this card\n");
return returnValue;
}
returnValue.setBool(true);
return returnValue;
}
Ti::TiValue InvocationManager::facebookShareMethod(Ti::TiValue text) {
//TODO: support image & url
Ti::TiValue returnValue;
returnValue.toBool();
if (invokeReply_ && !invokeReply_->isFinished()) {
// Don't send another invoke request if one is already pending.
return returnValue;
}
// convert variable to QString
QString myText = text.toString();
InvokeRequest request;
request.setTarget("Facebook");
request.setAction("bb.action.SHARE");
request.setMimeType("text/plain");
//request.setUri(myUrl);
request.setData(myText.toLocal8Bit());
invokeReply_ = invokeManager_.invoke(request);
if (!invokeReply_) {
fprintf(stderr, "Failed to invoke this card\n");
return returnValue;
}
returnValue.setBool(true);
return returnValue;
}
Ti::TiValue InvocationManager::openSettingsMethod(Ti::TiValue page) {
Ti::TiValue returnValue;
returnValue.toBool();
if (invokeReply_ && !invokeReply_->isFinished()) {
// Don't send another invoke request if one is already pending.
return returnValue;
}
// convert variable to QString
QString myPage = page.toString();
InvokeRequest request;
request.setTarget("sys.settings.card");
request.setAction("bb.action.OPEN");
request.setMimeType("settings/view");
request.setUri(myPage);
invokeReply_ = invokeManager_.invoke(request);
if (!invokeReply_) {
fprintf(stderr, "Failed to invoke this card\n");
return returnValue;
}
returnValue.setBool(true);
return returnValue;
}
Ti::TiValue InvocationManager::openPdfMethod(Ti::TiValue url) {
Ti::TiValue returnValue;
returnValue.toBool();
if (invokeReply_ && !invokeReply_->isFinished()) {
// Don't send another invoke request if one is already pending.
return returnValue;
}
// convert variable to QString
QString myUrl = url.toString();
InvokeRequest request;
request.setTarget("com.rim.bb.app.adobeReader.viewer");
request.setAction("bb.action.VIEW");
request.setMimeType("application/pdf");
request.setUri(
"file:" + QDir::currentPath() + "/app/native/assets/" + myUrl);
invokeReply_ = invokeManager_.invoke(request);
if (!invokeReply_) {
fprintf(stderr, "Failed to invoke this card\n");
return returnValue;
}
returnValue.setBool(true);
return returnValue;
}
Ti::TiValue InvocationManager::openMapMethod(Ti::TiValue type) {
Ti::TiValue returnValue;
returnValue.toBool();
// convert variable to QString
QString myType = type.toString();
if (myType == "pin") {
LocationMapInvoker lmi;
// Sample location set as Toronto
// Latitude and Longitude values are expressed
// in WGS 84 datum standard
lmi.setLocationLatitude(25.1980730);
lmi.setLocationLongitude(55.2728830);
lmi.setLocationName("Burj Khalifa");
lmi.setLocationDescription("The tallest building in the world.");
//set "geocode" : false
lmi.setGeocodeLocationEnabled(true);
//set "geolocation" : false
lmi.setCurrentLocationEnabled(true);
lmi.go();
} else {
RouteMapInvoker rmi;
// Latitude and Longitude values are expressed
// in WGS 84 datum standard
rmi.setEndLatitude(25.1412000);
rmi.setEndLongitude(55.1854000);
rmi.setEndName("Burj Al-Arab");
rmi.setEndDescription("The royal suite");
rmi.setEndAddress("Burj Al-Arab, Dubai");
rmi.setNavigationMode(bb::platform::MapNavigationMode::FastestRoute);
rmi.setTransportationMode(bb::platform::MapTransportationMode::Car);
rmi.go();
}
returnValue.setBool(true);
return returnValue;
}
Ti::TiValue InvocationManager::openContactsMethod(Ti::TiValue text) {
Ti::TiValue returnValue;
returnValue.toBool();
ContactPicker *contactPicker = new ContactPicker();
contactPicker->setMode(ContactSelectionMode::Single);
contactPicker->setKindFilters(
QSet<bb::pim::contacts::AttributeKind::Type>()
<< bb::pim::contacts::AttributeKind::Phone);
contactPicker->open();
returnValue.setBool(true);
return returnValue;
}
| HazemKhaled/TiCardInvocation | module/InvocationManager.cpp | C++ | mit | 6,446 |
<?php
namespace Lonquan\TaobaoSDK\Top\Request;
use Lonquan\TaobaoSDK\Top\RequestCheckUtil;
use Lonquan\TaobaoSDK\Top\RequestInterface;
/**
* TOP API: taobao.product.img.delete request
*
* @author auto create
* @since 1.0, 2016.03.05
*/
class ProductImgDeleteRequest implements RequestInterface
{
/**
* 非主图ID
**/
private $id;
/**
* 产品ID.Product的id,通过taobao.product.add接口新增产品的时候会返回id.
**/
private $productId;
private $apiParas = [ ];
public function setId($id)
{
$this->id = $id;
$this->apiParas["id"] = $id;
}
public function getId()
{
return $this->id;
}
public function setProductId($productId)
{
$this->productId = $productId;
$this->apiParas["product_id"] = $productId;
}
public function getProductId()
{
return $this->productId;
}
public function getApiMethodName()
{
return "taobao.product.img.delete";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->id, "id");
RequestCheckUtil::checkNotNull($this->productId, "productId");
}
public function putOtherTextParam($key, $value)
{
$this->apiParas[ $key ] = $value;
$this->$key = $value;
}
}
| lonquan/taobao-sdk | src/Top/Request/ProductImgDeleteRequest.php | PHP | mit | 1,480 |
require "point/version"
module Point
autoload :Point, 'point/point'
def self.sum(*args)
x = y = 0
args.each do |point|
x += point.x
y += point.y
end
self::Point.new(x, y)
end
end
| login73ul/point | lib/point.rb | Ruby | mit | 219 |
<?php
namespace MvMidia\Factory;
use MvMidia\Service\AudioService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class AudioServiceFactory
implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
return new AudioService($entityManager);
}
}
| marcusvy/mv-orion | _server/module/MvMidia/src/MvMidia/Factory/AudioServiceFactory.php | PHP | mit | 420 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _10.CatalanNumbers
{
class Program
{
static void Main(string[] args)
{
// 10. Write a program to calculate the Nth Catalan number by given N.
Console.Write("Insert N = ");
string input = Console.ReadLine();
int num;
int catalanNumber;
int factN = 1;
int factM = 1;
int factK = 1;
if (int.TryParse(input, out num))
{
if (num > -1)
{
if (num == 0)
{
Console.WriteLine("Catalan number given by '0' is: 1");
}
else if (num >= 1)
{
int n = num;
while (n > 1)
{
factN = factN * n; // for (n!)
n = n - 1;
}
n = num + 1;
while (n > 1)
{
factM = factM * n; // for (n + 1)
n = n - 1;
}
n = 2 * num;
while (n > 1)
{
factK = factK * n; // for (2 * n)
n = n - 1;
}
catalanNumber = factK / (factM * factN);
Console.WriteLine("Catalan number given by 'N' is: " + catalanNumber);
}
}
else
{
Console.WriteLine("N < 0");
}
}
else
{
Console.WriteLine("Incorect input!");
}
}
}
}
| bstaykov/Telerik-CSharp-Part-1 | Loops/10.CatalanNumbers/Program.cs | C# | mit | 1,982 |
<?php
/* TwigBundle:Exception:traces.txt.twig */
class __TwigTemplate_c3e3230b69c4964c8a557e1f2f357b5c8020737511aeeb0ff45cb50924b53015 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
if (twig_length_filter($this->env, $this->getAttribute($this->getContext($context, "exception"), "trace"))) {
// line 2
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getContext($context, "exception"), "trace"));
foreach ($context['_seq'] as $context["_key"] => $context["trace"]) {
// line 3
$this->env->loadTemplate("TwigBundle:Exception:trace.txt.twig")->display(array("trace" => $this->getContext($context, "trace")));
// line 4
echo "
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
}
}
public function getTemplateName()
{
return "TwigBundle:Exception:traces.txt.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 42 => 14, 38 => 13, 35 => 4, 26 => 5, 87 => 20, 80 => 19, 55 => 13, 46 => 7, 44 => 10, 36 => 7, 31 => 5, 25 => 3, 21 => 2, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 9, 27 => 4, 24 => 4, 22 => 2, 201 => 92, 199 => 91, 196 => 90, 187 => 84, 183 => 82, 173 => 74, 171 => 73, 168 => 72, 166 => 71, 163 => 70, 158 => 67, 156 => 66, 151 => 63, 142 => 59, 138 => 57, 136 => 56, 133 => 55, 123 => 47, 121 => 46, 117 => 44, 115 => 43, 112 => 42, 105 => 40, 101 => 24, 91 => 31, 86 => 28, 69 => 25, 66 => 15, 62 => 23, 51 => 15, 49 => 19, 39 => 6, 32 => 12, 19 => 1, 57 => 16, 54 => 21, 43 => 8, 40 => 7, 33 => 10, 30 => 3,);
}
}
| lrodriguezcabrales/Tutorial | app/cache/dev/twig/c3/e3/230b69c4964c8a557e1f2f357b5c8020737511aeeb0ff45cb50924b53015.php | PHP | mit | 2,351 |
(function() {
var $, expect, fruits;
$ = require('../');
expect = require('expect.js');
/*
Examples
*/
fruits = '<ul id = "fruits">\n <li class = "apple">Apple</li>\n <li class = "orange">Orange</li>\n <li class = "pear">Pear</li>\n</ul>'.replace(/(\n|\s{2})/g, '');
/*
Tests
*/
describe('$(...)', function() {
describe('.find', function() {
it('() : should return this', function() {
return expect($('ul', fruits).find()[0].name).to.equal('ul');
});
it('(single) : should find one descendant', function() {
return expect($('#fruits', fruits).find('.apple')[0].attribs["class"]).to.equal('apple');
});
it('(many) : should find all matching descendant', function() {
return expect($('#fruits', fruits).find('li')).to.have.length(3);
});
it('(many) : should merge all selected elems with matching descendants');
it('(invalid single) : should return empty if cant find', function() {
return expect($('ul', fruits).find('blah')).to.have.length(0);
});
return it('should return empty if search already empty result', function() {
return expect($('#fruits').find('li')).to.have.length(0);
});
});
describe('.children', function() {
it('() : should get all children', function() {
return expect($('ul', fruits).children()).to.have.length(3);
});
it('(selector) : should return children matching selector', function() {
return expect($('ul', fruits).children('.orange').hasClass('orange')).to.be.ok;
});
it('(invalid selector) : should return empty', function() {
return expect($('ul', fruits).children('.lulz')).to.have.length(0);
});
return it('should only match immediate children, not ancestors');
});
describe('.next', function() {
it('() : should return next element', function() {
return expect($('.orange', fruits).next().hasClass('pear')).to.be.ok;
});
return it('(no next) : should return null (?)');
});
describe('.prev', function() {
it('() : should return previous element', function() {
return expect($('.orange', fruits).prev().hasClass('apple')).to.be.ok;
});
return it('(no prev) : should return null (?)');
});
describe('.siblings', function() {
it('() : should get all the siblings', function() {
return expect($('.orange', fruits).siblings()).to.have.length(2);
});
return it('(selector) : should get all siblings that match the selector', function() {
return expect($('.orange', fruits).siblings('li')).to.have.length(2);
});
});
describe('.each', function() {
return it('( (i, elem) -> ) : should loop selected returning fn with (i, elem)', function() {
var items;
items = [];
$('li', fruits).each(function(i, elem) {
return items[i] = elem;
});
expect(items[0].attribs["class"]).to.equal('apple');
expect(items[1].attribs["class"]).to.equal('orange');
return expect(items[2].attribs["class"]).to.equal('pear');
});
});
describe('.first', function() {
it('() : should return the first item', function() {
var elem, src;
src = $("<span>foo</span><span>bar</span><span>baz</span>");
elem = src.first();
expect(elem.length).to.equal(1);
return expect(elem.html()).to.equal('foo');
});
return it('() : should return an empty object for an empty object', function() {
var first, src;
src = $();
first = src.first();
expect(first.length).to.equal(0);
return expect(first.html()).to.be(null);
});
});
describe('.last', function() {
it('() : should return the last element', function() {
var elem, src;
src = $("<span>foo</span><span>bar</span><span>baz</span>");
elem = src.last();
expect(elem.length).to.equal(1);
return expect(elem.html()).to.equal('baz');
});
return it('() : should return an empty object for an empty object', function() {
var last, src;
src = $();
last = src.last();
expect(last.length).to.equal(0);
return expect(last.html()).to.be(null);
});
});
describe('.first & .last', function() {
return it('() : should return same object if only one object', function() {
var first, last, src;
src = $("<span>bar</span>");
first = src.first();
last = src.last();
expect(first.html()).to.equal(last.html());
expect(first.length).to.equal(1);
expect(first.html()).to.equal('bar');
expect(last.length).to.equal(1);
return expect(last.html()).to.equal('bar');
});
});
return describe('.eq', function() {
return it('(i) : should return the element at the specified index', function() {
expect($('li', fruits).eq(0).text()).to.equal('Apple');
expect($('li', fruits).eq(1).text()).to.equal('Orange');
expect($('li', fruits).eq(2).text()).to.equal('Pear');
expect($('li', fruits).eq(3).text()).to.equal('');
return expect($('li', fruits).eq(-1).text()).to.equal('Pear');
});
});
});
}).call(this);
| wheeyls/meetingVis | node_modules/facile/test/public/javascripts/node_modules/cheerio/test/api.traversing.js | JavaScript | mit | 5,315 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: diplomacy_tensorflow/core/example/feature.proto
#include "diplomacy_tensorflow/core/example/feature.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto {
extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_BytesList;
extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_FloatList;
extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Int64List;
extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FeatureList;
extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FeatureLists_FeatureListEntry_DoNotUse;
extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Features_FeatureEntry_DoNotUse;
extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_Feature;
} // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto
namespace diplomacy {
namespace tensorflow {
class BytesListDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<BytesList>
_instance;
} _BytesList_default_instance_;
class FloatListDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<FloatList>
_instance;
} _FloatList_default_instance_;
class Int64ListDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Int64List>
_instance;
} _Int64List_default_instance_;
class FeatureDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Feature>
_instance;
const ::diplomacy::tensorflow::BytesList* bytes_list_;
const ::diplomacy::tensorflow::FloatList* float_list_;
const ::diplomacy::tensorflow::Int64List* int64_list_;
} _Feature_default_instance_;
class Features_FeatureEntry_DoNotUseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Features_FeatureEntry_DoNotUse>
_instance;
} _Features_FeatureEntry_DoNotUse_default_instance_;
class FeaturesDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Features>
_instance;
} _Features_default_instance_;
class FeatureListDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<FeatureList>
_instance;
} _FeatureList_default_instance_;
class FeatureLists_FeatureListEntry_DoNotUseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<FeatureLists_FeatureListEntry_DoNotUse>
_instance;
} _FeatureLists_FeatureListEntry_DoNotUse_default_instance_;
class FeatureListsDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<FeatureLists>
_instance;
} _FeatureLists_default_instance_;
} // namespace tensorflow
} // namespace diplomacy
namespace protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto {
static void InitDefaultsBytesList() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_BytesList_default_instance_;
new (ptr) ::diplomacy::tensorflow::BytesList();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::diplomacy::tensorflow::BytesList::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_BytesList =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBytesList}, {}};
static void InitDefaultsFloatList() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_FloatList_default_instance_;
new (ptr) ::diplomacy::tensorflow::FloatList();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::diplomacy::tensorflow::FloatList::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_FloatList =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFloatList}, {}};
static void InitDefaultsInt64List() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_Int64List_default_instance_;
new (ptr) ::diplomacy::tensorflow::Int64List();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::diplomacy::tensorflow::Int64List::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_Int64List =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt64List}, {}};
static void InitDefaultsFeature() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_Feature_default_instance_;
new (ptr) ::diplomacy::tensorflow::Feature();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::diplomacy::tensorflow::Feature::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<3> scc_info_Feature =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsFeature}, {
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_BytesList.base,
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FloatList.base,
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Int64List.base,}};
static void InitDefaultsFeatures_FeatureEntry_DoNotUse() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_Features_FeatureEntry_DoNotUse_default_instance_;
new (ptr) ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse();
}
::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_Features_FeatureEntry_DoNotUse =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatures_FeatureEntry_DoNotUse}, {
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base,}};
static void InitDefaultsFeatures() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_Features_default_instance_;
new (ptr) ::diplomacy::tensorflow::Features();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::diplomacy::tensorflow::Features::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_Features =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatures}, {
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Features_FeatureEntry_DoNotUse.base,}};
static void InitDefaultsFeatureList() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_FeatureList_default_instance_;
new (ptr) ::diplomacy::tensorflow::FeatureList();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::diplomacy::tensorflow::FeatureList::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_FeatureList =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatureList}, {
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base,}};
static void InitDefaultsFeatureLists_FeatureListEntry_DoNotUse() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_FeatureLists_FeatureListEntry_DoNotUse_default_instance_;
new (ptr) ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse();
}
::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_FeatureLists_FeatureListEntry_DoNotUse =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatureLists_FeatureListEntry_DoNotUse}, {
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureList.base,}};
static void InitDefaultsFeatureLists() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::diplomacy::tensorflow::_FeatureLists_default_instance_;
new (ptr) ::diplomacy::tensorflow::FeatureLists();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::diplomacy::tensorflow::FeatureLists::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_FeatureLists =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatureLists}, {
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureLists_FeatureListEntry_DoNotUse.base,}};
void InitDefaults() {
::google::protobuf::internal::InitSCC(&scc_info_BytesList.base);
::google::protobuf::internal::InitSCC(&scc_info_FloatList.base);
::google::protobuf::internal::InitSCC(&scc_info_Int64List.base);
::google::protobuf::internal::InitSCC(&scc_info_Feature.base);
::google::protobuf::internal::InitSCC(&scc_info_Features_FeatureEntry_DoNotUse.base);
::google::protobuf::internal::InitSCC(&scc_info_Features.base);
::google::protobuf::internal::InitSCC(&scc_info_FeatureList.base);
::google::protobuf::internal::InitSCC(&scc_info_FeatureLists_FeatureListEntry_DoNotUse.base);
::google::protobuf::internal::InitSCC(&scc_info_FeatureLists.base);
}
::google::protobuf::Metadata file_level_metadata[9];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::BytesList, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::BytesList, value_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FloatList, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FloatList, value_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Int64List, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Int64List, value_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Feature, _internal_metadata_),
~0u, // no _extensions_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Feature, _oneof_case_[0]),
~0u, // no _weak_field_map_
offsetof(::diplomacy::tensorflow::FeatureDefaultTypeInternal, bytes_list_),
offsetof(::diplomacy::tensorflow::FeatureDefaultTypeInternal, float_list_),
offsetof(::diplomacy::tensorflow::FeatureDefaultTypeInternal, int64_list_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Feature, kind_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse, key_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse, value_),
0,
1,
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features, feature_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureList, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureList, feature_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse, key_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse, value_),
0,
1,
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists, feature_list_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::diplomacy::tensorflow::BytesList)},
{ 6, -1, sizeof(::diplomacy::tensorflow::FloatList)},
{ 12, -1, sizeof(::diplomacy::tensorflow::Int64List)},
{ 18, -1, sizeof(::diplomacy::tensorflow::Feature)},
{ 27, 34, sizeof(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse)},
{ 36, -1, sizeof(::diplomacy::tensorflow::Features)},
{ 42, -1, sizeof(::diplomacy::tensorflow::FeatureList)},
{ 48, 55, sizeof(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse)},
{ 57, -1, sizeof(::diplomacy::tensorflow::FeatureLists)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_BytesList_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_FloatList_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_Int64List_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_Feature_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_Features_FeatureEntry_DoNotUse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_Features_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_FeatureList_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_FeatureLists_FeatureListEntry_DoNotUse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_FeatureLists_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
AssignDescriptors(
"diplomacy_tensorflow/core/example/feature.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 9);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n/diplomacy_tensorflow/core/example/feat"
"ure.proto\022\024diplomacy.tensorflow\"\032\n\tBytes"
"List\022\r\n\005value\030\001 \003(\014\"\036\n\tFloatList\022\021\n\005valu"
"e\030\001 \003(\002B\002\020\001\"\036\n\tInt64List\022\021\n\005value\030\001 \003(\003B"
"\002\020\001\"\266\001\n\007Feature\0225\n\nbytes_list\030\001 \001(\0132\037.di"
"plomacy.tensorflow.BytesListH\000\0225\n\nfloat_"
"list\030\002 \001(\0132\037.diplomacy.tensorflow.FloatL"
"istH\000\0225\n\nint64_list\030\003 \001(\0132\037.diplomacy.te"
"nsorflow.Int64ListH\000B\006\n\004kind\"\227\001\n\010Feature"
"s\022<\n\007feature\030\001 \003(\0132+.diplomacy.tensorflo"
"w.Features.FeatureEntry\032M\n\014FeatureEntry\022"
"\013\n\003key\030\001 \001(\t\022,\n\005value\030\002 \001(\0132\035.diplomacy."
"tensorflow.Feature:\0028\001\"=\n\013FeatureList\022.\n"
"\007feature\030\001 \003(\0132\035.diplomacy.tensorflow.Fe"
"ature\"\260\001\n\014FeatureLists\022I\n\014feature_list\030\001"
" \003(\01323.diplomacy.tensorflow.FeatureLists"
".FeatureListEntry\032U\n\020FeatureListEntry\022\013\n"
"\003key\030\001 \001(\t\0220\n\005value\030\002 \001(\0132!.diplomacy.te"
"nsorflow.FeatureList:\0028\001Bi\n\026org.tensorfl"
"ow.exampleB\rFeatureProtosP\001Z;github.com/"
"tensorflow/tensorflow/tensorflow/go/core"
"/example\370\001\001b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 859);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"diplomacy_tensorflow/core/example/feature.proto", &protobuf_RegisterTypes);
}
void AddDescriptors() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto
namespace diplomacy {
namespace tensorflow {
// ===================================================================
void BytesList::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BytesList::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
BytesList::BytesList()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_BytesList.base);
SharedCtor();
// @@protoc_insertion_point(constructor:diplomacy.tensorflow.BytesList)
}
BytesList::BytesList(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
value_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_BytesList.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.BytesList)
}
BytesList::BytesList(const BytesList& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
value_(from.value_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.BytesList)
}
void BytesList::SharedCtor() {
}
BytesList::~BytesList() {
// @@protoc_insertion_point(destructor:diplomacy.tensorflow.BytesList)
SharedDtor();
}
void BytesList::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void BytesList::ArenaDtor(void* object) {
BytesList* _this = reinterpret_cast< BytesList* >(object);
(void)_this;
}
void BytesList::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void BytesList::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* BytesList::descriptor() {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const BytesList& BytesList::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_BytesList.base);
return *internal_default_instance();
}
void BytesList::Clear() {
// @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.BytesList)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
value_.Clear();
_internal_metadata_.Clear();
}
bool BytesList::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:diplomacy.tensorflow.BytesList)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated bytes value = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->add_value()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:diplomacy.tensorflow.BytesList)
return true;
failure:
// @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.BytesList)
return false;
#undef DO_
}
void BytesList::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.BytesList)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated bytes value = 1;
for (int i = 0, n = this->value_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteBytes(
1, this->value(i), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.BytesList)
}
::google::protobuf::uint8* BytesList::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.BytesList)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated bytes value = 1;
for (int i = 0, n = this->value_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteBytesToArray(1, this->value(i), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.BytesList)
return target;
}
size_t BytesList::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.BytesList)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// repeated bytes value = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->value_size());
for (int i = 0, n = this->value_size(); i < n; i++) {
total_size += ::google::protobuf::internal::WireFormatLite::BytesSize(
this->value(i));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void BytesList::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.BytesList)
GOOGLE_DCHECK_NE(&from, this);
const BytesList* source =
::google::protobuf::internal::DynamicCastToGenerated<const BytesList>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.BytesList)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.BytesList)
MergeFrom(*source);
}
}
void BytesList::MergeFrom(const BytesList& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.BytesList)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
value_.MergeFrom(from.value_);
}
void BytesList::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.BytesList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void BytesList::CopyFrom(const BytesList& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.BytesList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool BytesList::IsInitialized() const {
return true;
}
void BytesList::Swap(BytesList* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
BytesList* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void BytesList::UnsafeArenaSwap(BytesList* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void BytesList::InternalSwap(BytesList* other) {
using std::swap;
value_.InternalSwap(CastToBase(&other->value_));
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata BytesList::GetMetadata() const {
protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void FloatList::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FloatList::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FloatList::FloatList()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FloatList.base);
SharedCtor();
// @@protoc_insertion_point(constructor:diplomacy.tensorflow.FloatList)
}
FloatList::FloatList(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
value_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FloatList.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.FloatList)
}
FloatList::FloatList(const FloatList& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
value_(from.value_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.FloatList)
}
void FloatList::SharedCtor() {
}
FloatList::~FloatList() {
// @@protoc_insertion_point(destructor:diplomacy.tensorflow.FloatList)
SharedDtor();
}
void FloatList::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void FloatList::ArenaDtor(void* object) {
FloatList* _this = reinterpret_cast< FloatList* >(object);
(void)_this;
}
void FloatList::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void FloatList::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FloatList::descriptor() {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FloatList& FloatList::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FloatList.base);
return *internal_default_instance();
}
void FloatList::Clear() {
// @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.FloatList)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
value_.Clear();
_internal_metadata_.Clear();
}
bool FloatList::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:diplomacy.tensorflow.FloatList)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated float value = 1 [packed = true];
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
input, this->mutable_value())));
} else if (
static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(13u /* 13 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
1, 10u, input, this->mutable_value())));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:diplomacy.tensorflow.FloatList)
return true;
failure:
// @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.FloatList)
return false;
#undef DO_
}
void FloatList::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.FloatList)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated float value = 1 [packed = true];
if (this->value_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(static_cast< ::google::protobuf::uint32>(
_value_cached_byte_size_));
::google::protobuf::internal::WireFormatLite::WriteFloatArray(
this->value().data(), this->value_size(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.FloatList)
}
::google::protobuf::uint8* FloatList::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.FloatList)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated float value = 1 [packed = true];
if (this->value_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
1,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
static_cast< ::google::protobuf::int32>(
_value_cached_byte_size_), target);
target = ::google::protobuf::internal::WireFormatLite::
WriteFloatNoTagToArray(this->value_, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.FloatList)
return target;
}
size_t FloatList::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.FloatList)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// repeated float value = 1 [packed = true];
{
unsigned int count = static_cast<unsigned int>(this->value_size());
size_t data_size = 4UL * count;
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
static_cast< ::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_value_cached_byte_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void FloatList::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.FloatList)
GOOGLE_DCHECK_NE(&from, this);
const FloatList* source =
::google::protobuf::internal::DynamicCastToGenerated<const FloatList>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.FloatList)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.FloatList)
MergeFrom(*source);
}
}
void FloatList::MergeFrom(const FloatList& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.FloatList)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
value_.MergeFrom(from.value_);
}
void FloatList::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.FloatList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void FloatList::CopyFrom(const FloatList& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.FloatList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool FloatList::IsInitialized() const {
return true;
}
void FloatList::Swap(FloatList* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
FloatList* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void FloatList::UnsafeArenaSwap(FloatList* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FloatList::InternalSwap(FloatList* other) {
using std::swap;
value_.InternalSwap(&other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata FloatList::GetMetadata() const {
protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void Int64List::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Int64List::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Int64List::Int64List()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Int64List.base);
SharedCtor();
// @@protoc_insertion_point(constructor:diplomacy.tensorflow.Int64List)
}
Int64List::Int64List(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
value_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Int64List.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.Int64List)
}
Int64List::Int64List(const Int64List& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
value_(from.value_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.Int64List)
}
void Int64List::SharedCtor() {
}
Int64List::~Int64List() {
// @@protoc_insertion_point(destructor:diplomacy.tensorflow.Int64List)
SharedDtor();
}
void Int64List::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void Int64List::ArenaDtor(void* object) {
Int64List* _this = reinterpret_cast< Int64List* >(object);
(void)_this;
}
void Int64List::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void Int64List::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Int64List::descriptor() {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Int64List& Int64List::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Int64List.base);
return *internal_default_instance();
}
void Int64List::Clear() {
// @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.Int64List)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
value_.Clear();
_internal_metadata_.Clear();
}
bool Int64List::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:diplomacy.tensorflow.Int64List)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated int64 value = 1 [packed = true];
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, this->mutable_value())));
} else if (
static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
1, 10u, input, this->mutable_value())));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:diplomacy.tensorflow.Int64List)
return true;
failure:
// @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.Int64List)
return false;
#undef DO_
}
void Int64List::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.Int64List)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated int64 value = 1 [packed = true];
if (this->value_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(static_cast< ::google::protobuf::uint32>(
_value_cached_byte_size_));
}
for (int i = 0, n = this->value_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt64NoTag(
this->value(i), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.Int64List)
}
::google::protobuf::uint8* Int64List::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.Int64List)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated int64 value = 1 [packed = true];
if (this->value_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
1,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
static_cast< ::google::protobuf::int32>(
_value_cached_byte_size_), target);
target = ::google::protobuf::internal::WireFormatLite::
WriteInt64NoTagToArray(this->value_, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.Int64List)
return target;
}
size_t Int64List::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.Int64List)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// repeated int64 value = 1 [packed = true];
{
size_t data_size = ::google::protobuf::internal::WireFormatLite::
Int64Size(this->value_);
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
static_cast< ::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_value_cached_byte_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Int64List::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.Int64List)
GOOGLE_DCHECK_NE(&from, this);
const Int64List* source =
::google::protobuf::internal::DynamicCastToGenerated<const Int64List>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.Int64List)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.Int64List)
MergeFrom(*source);
}
}
void Int64List::MergeFrom(const Int64List& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.Int64List)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
value_.MergeFrom(from.value_);
}
void Int64List::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.Int64List)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Int64List::CopyFrom(const Int64List& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.Int64List)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Int64List::IsInitialized() const {
return true;
}
void Int64List::Swap(Int64List* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
Int64List* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void Int64List::UnsafeArenaSwap(Int64List* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Int64List::InternalSwap(Int64List* other) {
using std::swap;
value_.InternalSwap(&other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Int64List::GetMetadata() const {
protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void Feature::InitAsDefaultInstance() {
::diplomacy::tensorflow::_Feature_default_instance_.bytes_list_ = const_cast< ::diplomacy::tensorflow::BytesList*>(
::diplomacy::tensorflow::BytesList::internal_default_instance());
::diplomacy::tensorflow::_Feature_default_instance_.float_list_ = const_cast< ::diplomacy::tensorflow::FloatList*>(
::diplomacy::tensorflow::FloatList::internal_default_instance());
::diplomacy::tensorflow::_Feature_default_instance_.int64_list_ = const_cast< ::diplomacy::tensorflow::Int64List*>(
::diplomacy::tensorflow::Int64List::internal_default_instance());
}
void Feature::set_allocated_bytes_list(::diplomacy::tensorflow::BytesList* bytes_list) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_kind();
if (bytes_list) {
::google::protobuf::Arena* submessage_arena =
::google::protobuf::Arena::GetArena(bytes_list);
if (message_arena != submessage_arena) {
bytes_list = ::google::protobuf::internal::GetOwnedMessage(
message_arena, bytes_list, submessage_arena);
}
set_has_bytes_list();
kind_.bytes_list_ = bytes_list;
}
// @@protoc_insertion_point(field_set_allocated:diplomacy.tensorflow.Feature.bytes_list)
}
void Feature::set_allocated_float_list(::diplomacy::tensorflow::FloatList* float_list) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_kind();
if (float_list) {
::google::protobuf::Arena* submessage_arena =
::google::protobuf::Arena::GetArena(float_list);
if (message_arena != submessage_arena) {
float_list = ::google::protobuf::internal::GetOwnedMessage(
message_arena, float_list, submessage_arena);
}
set_has_float_list();
kind_.float_list_ = float_list;
}
// @@protoc_insertion_point(field_set_allocated:diplomacy.tensorflow.Feature.float_list)
}
void Feature::set_allocated_int64_list(::diplomacy::tensorflow::Int64List* int64_list) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_kind();
if (int64_list) {
::google::protobuf::Arena* submessage_arena =
::google::protobuf::Arena::GetArena(int64_list);
if (message_arena != submessage_arena) {
int64_list = ::google::protobuf::internal::GetOwnedMessage(
message_arena, int64_list, submessage_arena);
}
set_has_int64_list();
kind_.int64_list_ = int64_list;
}
// @@protoc_insertion_point(field_set_allocated:diplomacy.tensorflow.Feature.int64_list)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Feature::kBytesListFieldNumber;
const int Feature::kFloatListFieldNumber;
const int Feature::kInt64ListFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Feature::Feature()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base);
SharedCtor();
// @@protoc_insertion_point(constructor:diplomacy.tensorflow.Feature)
}
Feature::Feature(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.Feature)
}
Feature::Feature(const Feature& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
clear_has_kind();
switch (from.kind_case()) {
case kBytesList: {
mutable_bytes_list()->::diplomacy::tensorflow::BytesList::MergeFrom(from.bytes_list());
break;
}
case kFloatList: {
mutable_float_list()->::diplomacy::tensorflow::FloatList::MergeFrom(from.float_list());
break;
}
case kInt64List: {
mutable_int64_list()->::diplomacy::tensorflow::Int64List::MergeFrom(from.int64_list());
break;
}
case KIND_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.Feature)
}
void Feature::SharedCtor() {
clear_has_kind();
}
Feature::~Feature() {
// @@protoc_insertion_point(destructor:diplomacy.tensorflow.Feature)
SharedDtor();
}
void Feature::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
if (has_kind()) {
clear_kind();
}
}
void Feature::ArenaDtor(void* object) {
Feature* _this = reinterpret_cast< Feature* >(object);
(void)_this;
}
void Feature::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void Feature::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Feature::descriptor() {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Feature& Feature::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base);
return *internal_default_instance();
}
void Feature::clear_kind() {
// @@protoc_insertion_point(one_of_clear_start:diplomacy.tensorflow.Feature)
switch (kind_case()) {
case kBytesList: {
if (GetArenaNoVirtual() == NULL) {
delete kind_.bytes_list_;
}
break;
}
case kFloatList: {
if (GetArenaNoVirtual() == NULL) {
delete kind_.float_list_;
}
break;
}
case kInt64List: {
if (GetArenaNoVirtual() == NULL) {
delete kind_.int64_list_;
}
break;
}
case KIND_NOT_SET: {
break;
}
}
_oneof_case_[0] = KIND_NOT_SET;
}
void Feature::Clear() {
// @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.Feature)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
clear_kind();
_internal_metadata_.Clear();
}
bool Feature::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:diplomacy.tensorflow.Feature)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .diplomacy.tensorflow.BytesList bytes_list = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_bytes_list()));
} else {
goto handle_unusual;
}
break;
}
// .diplomacy.tensorflow.FloatList float_list = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_float_list()));
} else {
goto handle_unusual;
}
break;
}
// .diplomacy.tensorflow.Int64List int64_list = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_int64_list()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:diplomacy.tensorflow.Feature)
return true;
failure:
// @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.Feature)
return false;
#undef DO_
}
void Feature::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.Feature)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .diplomacy.tensorflow.BytesList bytes_list = 1;
if (has_bytes_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->_internal_bytes_list(), output);
}
// .diplomacy.tensorflow.FloatList float_list = 2;
if (has_float_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->_internal_float_list(), output);
}
// .diplomacy.tensorflow.Int64List int64_list = 3;
if (has_int64_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, this->_internal_int64_list(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.Feature)
}
::google::protobuf::uint8* Feature::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.Feature)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .diplomacy.tensorflow.BytesList bytes_list = 1;
if (has_bytes_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->_internal_bytes_list(), deterministic, target);
}
// .diplomacy.tensorflow.FloatList float_list = 2;
if (has_float_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->_internal_float_list(), deterministic, target);
}
// .diplomacy.tensorflow.Int64List int64_list = 3;
if (has_int64_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, this->_internal_int64_list(), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.Feature)
return target;
}
size_t Feature::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.Feature)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
switch (kind_case()) {
// .diplomacy.tensorflow.BytesList bytes_list = 1;
case kBytesList: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*kind_.bytes_list_);
break;
}
// .diplomacy.tensorflow.FloatList float_list = 2;
case kFloatList: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*kind_.float_list_);
break;
}
// .diplomacy.tensorflow.Int64List int64_list = 3;
case kInt64List: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*kind_.int64_list_);
break;
}
case KIND_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Feature::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.Feature)
GOOGLE_DCHECK_NE(&from, this);
const Feature* source =
::google::protobuf::internal::DynamicCastToGenerated<const Feature>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.Feature)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.Feature)
MergeFrom(*source);
}
}
void Feature::MergeFrom(const Feature& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.Feature)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
switch (from.kind_case()) {
case kBytesList: {
mutable_bytes_list()->::diplomacy::tensorflow::BytesList::MergeFrom(from.bytes_list());
break;
}
case kFloatList: {
mutable_float_list()->::diplomacy::tensorflow::FloatList::MergeFrom(from.float_list());
break;
}
case kInt64List: {
mutable_int64_list()->::diplomacy::tensorflow::Int64List::MergeFrom(from.int64_list());
break;
}
case KIND_NOT_SET: {
break;
}
}
}
void Feature::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.Feature)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Feature::CopyFrom(const Feature& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.Feature)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Feature::IsInitialized() const {
return true;
}
void Feature::Swap(Feature* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
Feature* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void Feature::UnsafeArenaSwap(Feature* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Feature::InternalSwap(Feature* other) {
using std::swap;
swap(kind_, other->kind_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Feature::GetMetadata() const {
protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
Features_FeatureEntry_DoNotUse::Features_FeatureEntry_DoNotUse() {}
Features_FeatureEntry_DoNotUse::Features_FeatureEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {}
void Features_FeatureEntry_DoNotUse::MergeFrom(const Features_FeatureEntry_DoNotUse& other) {
MergeFromInternal(other);
}
::google::protobuf::Metadata Features_FeatureEntry_DoNotUse::GetMetadata() const {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[4];
}
void Features_FeatureEntry_DoNotUse::MergeFrom(
const ::google::protobuf::Message& other) {
::google::protobuf::Message::MergeFrom(other);
}
// ===================================================================
void Features::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Features::kFeatureFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Features::Features()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Features.base);
SharedCtor();
// @@protoc_insertion_point(constructor:diplomacy.tensorflow.Features)
}
Features::Features(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
feature_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Features.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.Features)
}
Features::Features(const Features& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
feature_.MergeFrom(from.feature_);
// @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.Features)
}
void Features::SharedCtor() {
}
Features::~Features() {
// @@protoc_insertion_point(destructor:diplomacy.tensorflow.Features)
SharedDtor();
}
void Features::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void Features::ArenaDtor(void* object) {
Features* _this = reinterpret_cast< Features* >(object);
(void)_this;
}
void Features::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void Features::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Features::descriptor() {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Features& Features::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Features.base);
return *internal_default_instance();
}
void Features::Clear() {
// @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.Features)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
feature_.Clear();
_internal_metadata_.Clear();
}
bool Features::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:diplomacy.tensorflow.Features)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, .diplomacy.tensorflow.Feature> feature = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
Features_FeatureEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField<
Features_FeatureEntry_DoNotUse,
::std::string, ::diplomacy::tensorflow::Feature,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 >,
::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature > > parser(&feature_);
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), static_cast<int>(parser.key().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"diplomacy.tensorflow.Features.FeatureEntry.key"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:diplomacy.tensorflow.Features)
return true;
failure:
// @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.Features)
return false;
#undef DO_
}
void Features::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.Features)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, .diplomacy.tensorflow.Feature> feature = 1;
if (!this->feature().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"diplomacy.tensorflow.Features.FeatureEntry.key");
}
};
if (output->IsSerializationDeterministic() &&
this->feature().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->feature().size()]);
typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator
it = this->feature().begin();
it != this->feature().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(feature_.NewEntryWrapper(
items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator
it = this->feature().begin();
it != this->feature().end(); ++it) {
entry.reset(feature_.NewEntryWrapper(
it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.Features)
}
::google::protobuf::uint8* Features::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.Features)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, .diplomacy.tensorflow.Feature> feature = 1;
if (!this->feature().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"diplomacy.tensorflow.Features.FeatureEntry.key");
}
};
if (deterministic &&
this->feature().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->feature().size()]);
typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator
it = this->feature().begin();
it != this->feature().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(feature_.NewEntryWrapper(
items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator
it = this->feature().begin();
it != this->feature().end(); ++it) {
entry.reset(feature_.NewEntryWrapper(
it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.Features)
return target;
}
size_t Features::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.Features)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// map<string, .diplomacy.tensorflow.Feature> feature = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->feature_size());
{
::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator
it = this->feature().begin();
it != this->feature().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(feature_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Features::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.Features)
GOOGLE_DCHECK_NE(&from, this);
const Features* source =
::google::protobuf::internal::DynamicCastToGenerated<const Features>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.Features)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.Features)
MergeFrom(*source);
}
}
void Features::MergeFrom(const Features& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.Features)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
feature_.MergeFrom(from.feature_);
}
void Features::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.Features)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Features::CopyFrom(const Features& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.Features)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Features::IsInitialized() const {
return true;
}
void Features::Swap(Features* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
Features* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void Features::UnsafeArenaSwap(Features* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Features::InternalSwap(Features* other) {
using std::swap;
feature_.Swap(&other->feature_);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Features::GetMetadata() const {
protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void FeatureList::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FeatureList::kFeatureFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FeatureList::FeatureList()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureList.base);
SharedCtor();
// @@protoc_insertion_point(constructor:diplomacy.tensorflow.FeatureList)
}
FeatureList::FeatureList(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
feature_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureList.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.FeatureList)
}
FeatureList::FeatureList(const FeatureList& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
feature_(from.feature_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.FeatureList)
}
void FeatureList::SharedCtor() {
}
FeatureList::~FeatureList() {
// @@protoc_insertion_point(destructor:diplomacy.tensorflow.FeatureList)
SharedDtor();
}
void FeatureList::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void FeatureList::ArenaDtor(void* object) {
FeatureList* _this = reinterpret_cast< FeatureList* >(object);
(void)_this;
}
void FeatureList::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void FeatureList::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FeatureList::descriptor() {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FeatureList& FeatureList::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureList.base);
return *internal_default_instance();
}
void FeatureList::Clear() {
// @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.FeatureList)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
feature_.Clear();
_internal_metadata_.Clear();
}
bool FeatureList::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:diplomacy.tensorflow.FeatureList)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .diplomacy.tensorflow.Feature feature = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_feature()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:diplomacy.tensorflow.FeatureList)
return true;
failure:
// @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.FeatureList)
return false;
#undef DO_
}
void FeatureList::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.FeatureList)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .diplomacy.tensorflow.Feature feature = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->feature_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1,
this->feature(static_cast<int>(i)),
output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.FeatureList)
}
::google::protobuf::uint8* FeatureList::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.FeatureList)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .diplomacy.tensorflow.Feature feature = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->feature_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->feature(static_cast<int>(i)), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.FeatureList)
return target;
}
size_t FeatureList::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.FeatureList)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// repeated .diplomacy.tensorflow.Feature feature = 1;
{
unsigned int count = static_cast<unsigned int>(this->feature_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->feature(static_cast<int>(i)));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void FeatureList::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.FeatureList)
GOOGLE_DCHECK_NE(&from, this);
const FeatureList* source =
::google::protobuf::internal::DynamicCastToGenerated<const FeatureList>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.FeatureList)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.FeatureList)
MergeFrom(*source);
}
}
void FeatureList::MergeFrom(const FeatureList& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.FeatureList)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
feature_.MergeFrom(from.feature_);
}
void FeatureList::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.FeatureList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void FeatureList::CopyFrom(const FeatureList& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.FeatureList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool FeatureList::IsInitialized() const {
return true;
}
void FeatureList::Swap(FeatureList* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
FeatureList* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void FeatureList::UnsafeArenaSwap(FeatureList* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FeatureList::InternalSwap(FeatureList* other) {
using std::swap;
CastToBase(&feature_)->InternalSwap(CastToBase(&other->feature_));
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata FeatureList::GetMetadata() const {
protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
FeatureLists_FeatureListEntry_DoNotUse::FeatureLists_FeatureListEntry_DoNotUse() {}
FeatureLists_FeatureListEntry_DoNotUse::FeatureLists_FeatureListEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {}
void FeatureLists_FeatureListEntry_DoNotUse::MergeFrom(const FeatureLists_FeatureListEntry_DoNotUse& other) {
MergeFromInternal(other);
}
::google::protobuf::Metadata FeatureLists_FeatureListEntry_DoNotUse::GetMetadata() const {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[7];
}
void FeatureLists_FeatureListEntry_DoNotUse::MergeFrom(
const ::google::protobuf::Message& other) {
::google::protobuf::Message::MergeFrom(other);
}
// ===================================================================
void FeatureLists::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FeatureLists::kFeatureListFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FeatureLists::FeatureLists()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureLists.base);
SharedCtor();
// @@protoc_insertion_point(constructor:diplomacy.tensorflow.FeatureLists)
}
FeatureLists::FeatureLists(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
feature_list_(arena) {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureLists.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.FeatureLists)
}
FeatureLists::FeatureLists(const FeatureLists& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
feature_list_.MergeFrom(from.feature_list_);
// @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.FeatureLists)
}
void FeatureLists::SharedCtor() {
}
FeatureLists::~FeatureLists() {
// @@protoc_insertion_point(destructor:diplomacy.tensorflow.FeatureLists)
SharedDtor();
}
void FeatureLists::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
void FeatureLists::ArenaDtor(void* object) {
FeatureLists* _this = reinterpret_cast< FeatureLists* >(object);
(void)_this;
}
void FeatureLists::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void FeatureLists::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* FeatureLists::descriptor() {
::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FeatureLists& FeatureLists::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureLists.base);
return *internal_default_instance();
}
void FeatureLists::Clear() {
// @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.FeatureLists)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
feature_list_.Clear();
_internal_metadata_.Clear();
}
bool FeatureLists::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:diplomacy.tensorflow.FeatureLists)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, .diplomacy.tensorflow.FeatureList> feature_list = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
FeatureLists_FeatureListEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField<
FeatureLists_FeatureListEntry_DoNotUse,
::std::string, ::diplomacy::tensorflow::FeatureList,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 >,
::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList > > parser(&feature_list_);
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), static_cast<int>(parser.key().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"diplomacy.tensorflow.FeatureLists.FeatureListEntry.key"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:diplomacy.tensorflow.FeatureLists)
return true;
failure:
// @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.FeatureLists)
return false;
#undef DO_
}
void FeatureLists::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.FeatureLists)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, .diplomacy.tensorflow.FeatureList> feature_list = 1;
if (!this->feature_list().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"diplomacy.tensorflow.FeatureLists.FeatureListEntry.key");
}
};
if (output->IsSerializationDeterministic() &&
this->feature_list().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->feature_list().size()]);
typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator
it = this->feature_list().begin();
it != this->feature_list().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(feature_list_.NewEntryWrapper(
items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator
it = this->feature_list().begin();
it != this->feature_list().end(); ++it) {
entry.reset(feature_list_.NewEntryWrapper(
it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.FeatureLists)
}
::google::protobuf::uint8* FeatureLists::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.FeatureLists)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, .diplomacy.tensorflow.FeatureList> feature_list = 1;
if (!this->feature_list().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"diplomacy.tensorflow.FeatureLists.FeatureListEntry.key");
}
};
if (deterministic &&
this->feature_list().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->feature_list().size()]);
typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator
it = this->feature_list().begin();
it != this->feature_list().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(feature_list_.NewEntryWrapper(
items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
}
} else {
::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator
it = this->feature_list().begin();
it != this->feature_list().end(); ++it) {
entry.reset(feature_list_.NewEntryWrapper(
it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.FeatureLists)
return target;
}
size_t FeatureLists::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.FeatureLists)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// map<string, .diplomacy.tensorflow.FeatureList> feature_list = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->feature_list_size());
{
::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry;
for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator
it = this->feature_list().begin();
it != this->feature_list().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(feature_list_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void FeatureLists::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.FeatureLists)
GOOGLE_DCHECK_NE(&from, this);
const FeatureLists* source =
::google::protobuf::internal::DynamicCastToGenerated<const FeatureLists>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.FeatureLists)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.FeatureLists)
MergeFrom(*source);
}
}
void FeatureLists::MergeFrom(const FeatureLists& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.FeatureLists)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
feature_list_.MergeFrom(from.feature_list_);
}
void FeatureLists::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.FeatureLists)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void FeatureLists::CopyFrom(const FeatureLists& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.FeatureLists)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool FeatureLists::IsInitialized() const {
return true;
}
void FeatureLists::Swap(FeatureLists* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
FeatureLists* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void FeatureLists::UnsafeArenaSwap(FeatureLists* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FeatureLists::InternalSwap(FeatureLists* other) {
using std::swap;
feature_list_.Swap(&other->feature_list_);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata FeatureLists::GetMetadata() const {
protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace tensorflow
} // namespace diplomacy
namespace google {
namespace protobuf {
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::BytesList* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::BytesList >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::BytesList >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::FloatList* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::FloatList >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::FloatList >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::Int64List* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::Int64List >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::Int64List >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::Feature* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::Feature >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::Feature >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::Features* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::Features >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::Features >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::FeatureList* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::FeatureList >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::FeatureList >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse >(arena);
}
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::FeatureLists* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::FeatureLists >(Arena* arena) {
return Arena::CreateMessageInternal< ::diplomacy::tensorflow::FeatureLists >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
| diplomacy/research | diplomacy_research/proto/diplomacy_tensorflow/core/example/feature.pb.cc | C++ | mit | 110,384 |
require 'spec_helper'
require 'gitnesse/cli'
module Gitnesse
describe Cli, type: :cli do
let(:help) do
<<-EOS
USAGE: gitnesse push
Pushes local features to remote git-based wiki
Pushes the local features files to the remote git-based wiki, creating/updating
wiki pages as necessary.
Examples:
gitnesse push # will push local features to remote wiki
EOS
end
it "has help info" do
expect(gitnesse("help push")).to eq help
end
end
end
| hybridgroup/gitnesse | spec/lib/cli/task/push_spec.rb | Ruby | mit | 478 |
package GlidersGrid;
import java.util.Iterator;
import repast.simphony.context.Context;
import repast.simphony.engine.schedule.ScheduledMethod;
import repast.simphony.query.space.grid.MooreQuery;
import repast.simphony.space.grid.Grid;
import repast.simphony.space.grid.GridPoint;
import repast.simphony.util.ContextUtils;
public class Dead {
private Grid<Object> grid;
private int state;
public Dead(Grid<Object> grid) {
this.grid = grid;
}
// calculate the state for the next time tick for dead cells
@ScheduledMethod(start = 1, interval = 1, priority = 4)
public void step1() {
MooreQuery<Dead> query = new MooreQuery(grid, this);
int neighbours = 0;
for (Object o : query.query()) {
if (o instanceof Living) {
neighbours++;
if (neighbours ==3) {
}
}
}
if (neighbours == 3) {
state = 1;
} else {
state = 0;
}
}
// visualise the change into the underlay and grid
@ScheduledMethod(start = 1, interval = 1, priority = 1)
public void step2() {
if (state == 1) {
GridPoint gpt = grid.getLocation(this);
Context<Object> context = ContextUtils.getContext(this);
context.remove(this);
Living livingCell = new Living(grid);
context.add(livingCell);
grid.moveTo(livingCell, gpt.getX(), gpt.getY());
context.add(livingCell);
}
}
} | ZawilecxD/Social-Network-Simulator | GlidersGrid/src/GlidersGrid/Dead.java | Java | mit | 1,307 |
#region Copyright (c) 2009 S. van Deursen
/* The CuttingEdge.Conditions library enables developers to validate pre- and postconditions in a fluent
* manner.
*
* To contact me, please visit my blog at http://www.cuttingedge.it/blogs/steven/
*
* Copyright (c) 2009 S. van Deursen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
using System;
using System.ComponentModel;
namespace CuttingEdge.Conditions
{
/// <summary>
/// The RequiresValidator can be used for precondition checks.
/// </summary>
/// <typeparam name="T">The type of the argument to be validated</typeparam>
internal class RequiresValidator<T> : ConditionValidator<T>
{
internal RequiresValidator(string argumentName, T value) : base(argumentName, value)
{
}
internal virtual Exception BuildExceptionBasedOnViolationType(ConstraintViolationType type,
string message)
{
switch (type)
{
case ConstraintViolationType.OutOfRangeViolation:
return new ArgumentOutOfRangeException(this.ArgumentName, message);
case ConstraintViolationType.InvalidEnumViolation:
string enumMessage = this.BuildInvalidEnumArgumentExceptionMessage(message);
return new InvalidEnumArgumentException(enumMessage);
default:
if (this.Value != null)
{
return new ArgumentException(message, this.ArgumentName);
}
else
{
return new ArgumentNullException(this.ArgumentName, message);
}
}
}
/// <summary>Throws an exception.</summary>
/// <param name="condition">Describes the condition that doesn't hold, e.g., "Value should not be
/// null".</param>
/// <param name="additionalMessage">An additional message that will be appended to the exception
/// message, e.g. "The actual value is 3.". This value may be null or empty.</param>
/// <param name="type">Gives extra information on the exception type that must be build. The actual
/// implementation of the validator may ignore some or all values.</param>
protected override void ThrowExceptionCore(string condition, string additionalMessage,
ConstraintViolationType type)
{
string message = BuildExceptionMessage(condition, additionalMessage);
Exception exceptionToThrow = this.BuildExceptionBasedOnViolationType(type, message);
throw exceptionToThrow;
}
private static string BuildExceptionMessage(string condition, string additionalMessage)
{
if (!String.IsNullOrEmpty(additionalMessage))
{
return condition + ". " + additionalMessage;
}
else
{
return condition + ".";
}
}
private string BuildInvalidEnumArgumentExceptionMessage(string message)
{
ArgumentException argumentException = new ArgumentException(message, this.ArgumentName);
// Returns the message formatted according to the current culture.
// Note that the 'Parameter name' part of the message is culture sensitive.
return argumentException.Message;
}
}
}
| conditions/conditions | CuttingEdge.Conditions/RequiresValidator.cs | C# | mit | 4,490 |
(function(){
'use strict';
function ListService($http){
this.getList = function(list_id){
return $http.get('/lists/' + list_id + ".json")
}
}
ListService.$inject = ['$http']
angular
.module('app')
.service('ListService', ListService)
}()) | jd2rogers2/presently | old-code/ListService.js | JavaScript | mit | 273 |
angular.module('movieApp')
.directive('movieResult', function () {
var directive = {
restrict: 'E',
replace: true,
scope: {
result: '=result'
},
template: [
'<div class="row">',
'<div class="col-sm-4">',
'<img ng-src="{{result.Poster}}" alt="{{result.Title}}" width="220px">',
'</div>',
'<div class="col-sm-8">',
'<h3>{{result.Title}}</h3>',
'<p>{{result.Plot}}</p>',
'<p><strong>Director:</strong> {{result.Director}}</p>',
'<p><strong>Actors:</strong> {{result.Actors}}</p>',
'<p><strong>Released:</strong> {{result.Released}} ({{result.Released | fromNow}})</p>',
'<p><strong>Genre:</strong> {{result.Genre}}</p>',
'</div>',
'</div>'
].join('')
};
return directive;
}); | cjp666/MovieApp | src/movie-app/movie-result.directive.js | JavaScript | mit | 751 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sandsound</title>
<link rel="stylesheet" href="/css/reset.css">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<canvas id="canvas" class="background"></canvas>
<!-- Ne s'affiche que si sur mobile :) -->
<div class="mobile">
<a href="/"><img class="logo" src="/css/img/logo.png" alt="SandSound"></a>
<p>Pour profiter de l'expérience SandSound, rendez-vous sur une tablette ou desktop !</p>
</div>
<div class="sidebar">
<a href="/"><img class="logo" src="/css/img/logo.png" alt="SandSound"></a>
<nav>
<ul>
<li class="active"><a href="{{ route('profile', ['name' => $user->name]) }}">Profil</a></li>
<li>{{ link_to_route('room', 'Rejoindre un salon') }}</li>
<li>{{ link_to_route('form-private', 'Nouveau salon') }}</li>
<li>{{ link_to_route('rank', 'Classement') }}</li>
</ul>
</nav>
</div>
<div class="content">
<div class="content__infos">
<ul>
<li class="content__infos--pseudo">{{ $user->name }}</li>
<li class="content__infos--pts">{{ $user->score->xp }}<span> pts </span></li>
<li class="content__infos--niv"><span>Niv :</span> {{ $user->score->lvl_total }}</li>
</ul>
</div>
<div class="content__title">
<h1>| {{ $user->name }}</h1>
<div class="content__title--intro">
<p>{{ $user->name }} est niveau <span>{{ $user->score->lvl_total }}</span>.</p>
</div>
<div class="content__title--explain">
<p>
Découvrez les dernières musiques de <span>{{ $user->name }}</span>.
</p>
</div>
<div class="content__experiencepre">
<ul>
<li class="content__experiencepre--bass">| Bass : <span>{{ $user->score->lvl_bass }}</span></li>
<li class="content__experiencepre--pads">| Ambiance : <span>{{ $user->score->lvl_ambiance }}</span></li>
<li class="content__experiencepre--drum">| Drum : <span>{{ $user->score->lvl_drum }}</span></li>
<li class="content__experiencepre--lead">| Lead : <span>{{ $user->score->lvl_lead }}</span></li>
</ul>
</div>
<div class="content__experience">
<ul>
<li class="content__experience--bass"></li>
<li class="content__experience--pads"></li>
<li class="content__experience--drum"></li>
<li class="content__experience--lead"></li>
</ul>
</div>
@if (count($songs))
<div class="content__title--score">
<table>
<thead>
<tr>
<th scope="col">Nom de la chanson :</th>
<th scope="col">Score :</th>
</tr>
<tbody>
@foreach ($songs as $song)
<tr>
<td>
{{ $song->name }}</td>
<td>{{ $song->score }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="/js/index.js"></script>
</body>
</html>
| vbillardm/Projet_Fin_ann-e | resources/views/profile/detail.blade.php | PHP | mit | 3,476 |
require 'lapine/test/exchange'
module Lapine
module Test
module RSpecHelper
def self.setup(_example = nil)
RSpec::Mocks::AllowanceTarget.new(Lapine::Exchange).to(
RSpec::Mocks::Matchers::Receive.new(:new, ->(name, properties) {
Lapine::Test::Exchange.new(name, properties)
})
)
end
def self.teardown
Lapine.close_connections!
end
end
end
end
| wanelo/lapine | lib/lapine/test/rspec_helper.rb | Ruby | mit | 436 |
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/animation/UnitBezier.h"
#include <gtest/gtest.h>
using namespace WebCore;
namespace {
TEST(UnitBezierTest, BasicUse)
{
UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
EXPECT_EQ(0.875, bezier.solve(0.5, 0.005));
}
TEST(UnitBezierTest, Overshoot)
{
UnitBezier bezier(0.5, 2.0, 0.5, 2.0);
EXPECT_EQ(1.625, bezier.solve(0.5, 0.005));
}
TEST(UnitBezierTest, Undershoot)
{
UnitBezier bezier(0.5, -1.0, 0.5, -1.0);
EXPECT_EQ(-0.625, bezier.solve(0.5, 0.005));
}
TEST(UnitBezierTest, InputAtEdgeOfRange)
{
UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
EXPECT_EQ(0.0, bezier.solve(0.0, 0.005));
EXPECT_EQ(1.0, bezier.solve(1.0, 0.005));
}
TEST(UnitBezierTest, InputOutOfRange)
{
UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
EXPECT_EQ(0.0, bezier.solve(-1.0, 0.005));
EXPECT_EQ(1.0, bezier.solve(2.0, 0.005));
}
TEST(UnitBezierTest, InputOutOfRangeLargeEpsilon)
{
UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
EXPECT_EQ(0.0, bezier.solve(-1.0, 1.0));
EXPECT_EQ(1.0, bezier.solve(2.0, 1.0));
}
} // namespace
| lordmos/blink | Source/platform/animation/UnitBezierTest.cpp | C++ | mit | 2,438 |
using Brandbank.Xml.Logging;
using System;
namespace Brandbank.Api.Clients
{
public sealed class FeedbackClientLogger : IFeedbackClient
{
private readonly ILogger<IFeedbackClient> _logger;
private readonly IFeedbackClient _feedbackClient;
public FeedbackClientLogger(ILogger<IFeedbackClient> logger, IFeedbackClient feedbackClient)
{
_logger = logger;
_feedbackClient = feedbackClient;
}
public int UploadCompressedFeedback(byte[] compressedFeedback)
{
_logger.LogDebug("Uploading compressed feedback to Brandbank");
try
{
var response = _feedbackClient.UploadCompressedFeedback(compressedFeedback);
_logger.LogDebug(response == 0
? "Uploaded compressed feedback to Brandbank"
: $"Upload compressed feedback to Brandbank failed, response code {response}");
return response;
}
catch (Exception e)
{
_logger.LogError($"Upload compressed feedback to Brandbank failed: {e}");
throw;
}
}
public void Dispose()
{
_logger.LogDebug("Disposing feedback client");
try
{
_feedbackClient.Dispose();
_logger.LogDebug("Disposed feedback client");
}
catch (Exception e)
{
_logger.LogError($"Disposing feedback client failed: {e}");
throw;
}
}
}
}
| Brandbank/Brandbank-Xml-And-Api-Helpers | Brandbank.Api/Clients/FeedbackClientLogger.cs | C# | mit | 1,649 |
<?php
namespace Zodream\Infrastructure\Http\Input;
/**
* Created by PhpStorm.
* User: zx648
* Date: 2016/4/3
* Time: 9:23
*/
use Zodream\Infrastructure\Base\MagicObject;
abstract class BaseInput extends MagicObject {
/**
* 格式化
* @param array|string $data
* @return array|string
*/
protected function _clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[strtolower($this->_clean($key))] = $this->_clean($value);
}
} else if (defined('APP_SAFE') && APP_SAFE){
$data = htmlspecialchars($data, ENT_COMPAT);
}
return $data;
}
protected function setValues(array $data) {
$this->set($this->_clean($data));
}
public function get($name = null, $default = null) {
return parent::get(strtolower($name), $default);
}
} | zx648383079/zodream | src/Infrastructure/Http/Input/BaseInput.php | PHP | mit | 932 |
<?php
/*
* This file is part of the Grosona.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace Grosona;
use Grosona\PhpProcess\Utils\Logger;
use Grosona\PhpProcess\TrobuleHandler;
/**
* Read configurations from the file.
*
* @author hchsiao
*/
class TroubleHandler implements TrobuleHandler {
protected $logger = null;
public function activate(Logger $logger) {
$this->logger = $logger;
}
public function handle(\Exception $err) {
if(
is_int(stripos($err->getMessage(), "Error validating access token: Session has expired")) ||
is_int(stripos($err->getMessage(), "Invalid appsecret_proof"))
) {
$msg = "token died\n";
echo $msg;
} else if(is_int(stripos($err->getMessage(), "Access token mismatch"))) {
$msg = "token confilict\n";
echo $msg;
} else {
$msg = (string) $err;
}
$this->logger->log("<Exception> $msg", Logger::LEVEL_ERROR);
}
public function shutdown() {
$logger = $this->logger;
if(!$logger instanceof Logger) {
die();
}
$err = error_get_last();
$errMsg = $err['message'];
if(is_int(stripos($errMsg, "FacebookSDKException' with message 'Connection timed out"))) {
$logger->log("facebook server down", Logger::LEVEL_WARN);
} else if(
is_int(stripos($errMsg, "operation failed")) ||
is_int(stripos($errMsg, "Gateway Time-out")) ||
is_int(stripos($errMsg, "HTTP request failed")) ||
is_int(stripos($errMsg, "Connection timed out")) ||
// faild to download image, will retry so it's OK
is_int(stripos($errMsg, "Undefined variable: http_response_header")) ||
is_int(stripos($errMsg, "Stream returned an empty response"))
// facebook http request failed, retry too
) {
$logger->log("HTTP request failed", Logger::LEVEL_INFO);
} else if($errMsg) {
$type = $err['type'];
$place = $err['file'] . '(' . $err['line'] . ')';
$logger->log("<Shutdown Type=$type> $errMsg at $place", Logger::LEVEL_ERROR);
}
}
}
| hchsiao/grosona | src/Grosona/TroubleHandler.php | PHP | mit | 2,474 |
class DashboardController < ApplicationController
def index
end
end
# vim: fo=tcq
| MaxMEllon/udon-dou | app/controllers/dashboard_controller.rb | Ruby | mit | 87 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_request(
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2020-11-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'),
"managedInstanceName": _SERIALIZER.url("managed_instance_name", managed_instance_name, 'str'),
"databaseName": _SERIALIZER.url("database_name", database_name, 'str'),
"queryId": _SERIALIZER.url("query_id", query_id, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_by_query_request(
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
subscription_id: str,
*,
start_time: Optional[str] = None,
end_time: Optional[str] = None,
interval: Optional[Union[str, "_models.QueryTimeGrainType"]] = None,
**kwargs: Any
) -> HttpRequest:
api_version = "2020-11-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}/statistics')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'),
"managedInstanceName": _SERIALIZER.url("managed_instance_name", managed_instance_name, 'str'),
"databaseName": _SERIALIZER.url("database_name", database_name, 'str'),
"queryId": _SERIALIZER.url("query_id", query_id, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if start_time is not None:
query_parameters['startTime'] = _SERIALIZER.query("start_time", start_time, 'str')
if end_time is not None:
query_parameters['endTime'] = _SERIALIZER.query("end_time", end_time, 'str')
if interval is not None:
query_parameters['interval'] = _SERIALIZER.query("interval", interval, 'str')
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class ManagedDatabaseQueriesOperations(object):
"""ManagedDatabaseQueriesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.sql.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def get(
self,
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
**kwargs: Any
) -> "_models.ManagedInstanceQuery":
"""Get query by query id.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance.
:type managed_instance_name: str
:param database_name: The name of the database.
:type database_name: str
:param query_id:
:type query_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ManagedInstanceQuery, or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.ManagedInstanceQuery
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceQuery"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
database_name=database_name,
query_id=query_id,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('ManagedInstanceQuery', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}'} # type: ignore
@distributed_trace
def list_by_query(
self,
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
start_time: Optional[str] = None,
end_time: Optional[str] = None,
interval: Optional[Union[str, "_models.QueryTimeGrainType"]] = None,
**kwargs: Any
) -> Iterable["_models.ManagedInstanceQueryStatistics"]:
"""Get query execution statistics by query id.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance.
:type managed_instance_name: str
:param database_name: The name of the database.
:type database_name: str
:param query_id:
:type query_id: str
:param start_time: Start time for observed period.
:type start_time: str
:param end_time: End time for observed period.
:type end_time: str
:param interval: The time step to be used to summarize the metric values.
:type interval: str or ~azure.mgmt.sql.models.QueryTimeGrainType
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ManagedInstanceQueryStatistics or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceQueryStatistics]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceQueryStatistics"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_query_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
database_name=database_name,
query_id=query_id,
subscription_id=self._config.subscription_id,
start_time=start_time,
end_time=end_time,
interval=interval,
template_url=self.list_by_query.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_query_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
database_name=database_name,
query_id=query_id,
subscription_id=self._config.subscription_id,
start_time=start_time,
end_time=end_time,
interval=interval,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ManagedInstanceQueryStatistics", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_query.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}/statistics'} # type: ignore
| Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/_managed_database_queries_operations.py | Python | mit | 12,909 |
<?php
namespace Koalamon\IntegrationBundle\Integration;
class Integration
{
private $name;
private $image;
private $description;
private $url;
private $activeElements;
private $totalElements;
/**
* Integration constructor.
*
* @param $name
* @param $image
* @param $description
* @param $url
*/
public function __construct($name, $image, $description, $url = null, $activeElements = null, $totalElements = null)
{
$this->name = $name;
$this->image = $image;
$this->description = $description;
$this->url = $url;
$this->activeElements = $activeElements;
$this->totalElements = $totalElements;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @return mixed
*/
public function getImage()
{
return $this->image;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @return mixed
*/
public function getUrl()
{
return $this->url;
}
/**
* @return null
*/
public function getActiveElements()
{
return $this->activeElements;
}
/**
* @return null
*/
public function getTotalElements()
{
return $this->totalElements;
}
/**
* @param null $activeElements
*/
public function setActiveElements($activeElements)
{
$this->activeElements = $activeElements;
}
public function setUrl($url)
{
$this->url = $url;
}
} | koalamon/KoalamomPlatform | src/Koalamon/IntegrationBundle/Integration/Integration.php | PHP | mit | 1,660 |
import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
| MyNameIsMeerkat/skyline | src/webapp/webapp.py | Python | mit | 2,673 |
/*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 6.4.2 *
* Date : 27 February 2017 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2017 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Attributions: *
* The code in this library is an extension of Bala Vatti's clipping algorithm: *
* "A generic solution to polygon clipping" *
* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
* http://portal.acm.org/citation.cfm?id=129906 *
* *
* Computer graphics and geometric modeling: implementation and algorithms *
* By Max K. Agoston *
* Springer; 1 edition (January 4, 2005) *
* http://books.google.com/books?q=vatti+clipping+agoston *
* *
* See also: *
* "Polygon Offsetting by Computing Winding Numbers" *
* Paper no. DETC2005-85513 pp. 565-575 *
* ASME 2005 International Design Engineering Technical Conferences *
* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
* September 24-28, 2005 , Long Beach, California, USA *
* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
* *
*******************************************************************************/
/*******************************************************************************
* *
* This is a translation of the Delphi Clipper library and the naming style *
* used has retained a Delphi flavour. *
* *
*******************************************************************************/
#include "clipper.hpp"
#include <cmath>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <cstring>
#include <cstdlib>
#include <ostream>
#include <functional>
namespace ClipperLib {
static double const pi = 3.141592653589793238;
static double const two_pi = pi *2;
static double const def_arc_tolerance = 0.25;
enum Direction { dRightToLeft, dLeftToRight };
static int const Unassigned = -1; //edge not currently 'owning' a solution
static int const Skip = -2; //edge that would otherwise close a path
#define HORIZONTAL (-1.0E+40)
#define TOLERANCE (1.0e-20)
#define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))
struct TEdge {
IntPoint Bot;
IntPoint Curr; //current (updated for every new scanbeam)
IntPoint Top;
double Dx;
PolyType PolyTyp;
EdgeSide Side; //side only refers to current side of solution poly
int WindDelta; //1 or -1 depending on winding direction
int WindCnt;
int WindCnt2; //winding count of the opposite polytype
int OutIdx;
TEdge *Next;
TEdge *Prev;
TEdge *NextInLML;
TEdge *NextInAEL;
TEdge *PrevInAEL;
TEdge *NextInSEL;
TEdge *PrevInSEL;
};
struct IntersectNode {
TEdge *Edge1;
TEdge *Edge2;
IntPoint Pt;
};
struct LocalMinimum {
cInt Y;
TEdge *LeftBound;
TEdge *RightBound;
};
struct OutPt;
//OutRec: contains a path in the clipping solution. Edges in the AEL will
//carry a pointer to an OutRec when they are part of the clipping solution.
struct OutRec {
int Idx;
bool IsHole;
bool IsOpen;
OutRec *FirstLeft; //see comments in clipper.pas
PolyNode *PolyNd;
OutPt *Pts;
OutPt *BottomPt;
};
struct OutPt {
int Idx;
IntPoint Pt;
OutPt *Next;
OutPt *Prev;
};
struct Join {
OutPt *OutPt1;
OutPt *OutPt2;
IntPoint OffPt;
};
struct LocMinSorter
{
inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2)
{
return locMin2.Y < locMin1.Y;
}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
inline cInt Round(double val)
{
if ((val < 0)) return static_cast<cInt>(val - 0.5);
else return static_cast<cInt>(val + 0.5);
}
//------------------------------------------------------------------------------
inline cInt Abs(cInt val)
{
return val < 0 ? -val : val;
}
//------------------------------------------------------------------------------
// PolyTree methods ...
//------------------------------------------------------------------------------
void PolyTree::Clear()
{
for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
delete AllNodes[i];
AllNodes.resize(0);
Childs.resize(0);
}
//------------------------------------------------------------------------------
PolyNode* PolyTree::GetFirst() const
{
if (!Childs.empty())
return Childs[0];
else
return 0;
}
//------------------------------------------------------------------------------
int PolyTree::Total() const
{
int result = (int)AllNodes.size();
//with negative offsets, ignore the hidden outer polygon ...
if (result > 0 && Childs[0] != AllNodes[0]) result--;
return result;
}
//------------------------------------------------------------------------------
// PolyNode methods ...
//------------------------------------------------------------------------------
PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false)
{
}
//------------------------------------------------------------------------------
int PolyNode::ChildCount() const
{
return (int)Childs.size();
}
//------------------------------------------------------------------------------
void PolyNode::AddChild(PolyNode& child)
{
unsigned cnt = (unsigned)Childs.size();
Childs.push_back(&child);
child.Parent = this;
child.Index = cnt;
}
//------------------------------------------------------------------------------
PolyNode* PolyNode::GetNext() const
{
if (!Childs.empty())
return Childs[0];
else
return GetNextSiblingUp();
}
//------------------------------------------------------------------------------
PolyNode* PolyNode::GetNextSiblingUp() const
{
if (!Parent) //protects against PolyTree.GetNextSiblingUp()
return 0;
else if (Index == Parent->Childs.size() - 1)
return Parent->GetNextSiblingUp();
else
return Parent->Childs[Index + 1];
}
//------------------------------------------------------------------------------
bool PolyNode::IsHole() const
{
bool result = true;
PolyNode* node = Parent;
while (node)
{
result = !result;
node = node->Parent;
}
return result;
}
//------------------------------------------------------------------------------
bool PolyNode::IsOpen() const
{
return m_IsOpen;
}
//------------------------------------------------------------------------------
#ifndef use_int32
//------------------------------------------------------------------------------
// Int128 class (enables safe math on signed 64bit integers)
// eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1
// Int128 val2((long64)9223372036854775807);
// Int128 val3 = val1 * val2;
// val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)
//------------------------------------------------------------------------------
class Int128
{
public:
ulong64 lo;
long64 hi;
Int128(long64 _lo = 0)
{
lo = (ulong64)_lo;
if (_lo < 0) hi = -1; else hi = 0;
}
Int128(const Int128 &val): lo(val.lo), hi(val.hi){}
Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){}
Int128& operator = (const long64 &val)
{
lo = (ulong64)val;
if (val < 0) hi = -1; else hi = 0;
return *this;
}
bool operator == (const Int128 &val) const
{return (hi == val.hi && lo == val.lo);}
bool operator != (const Int128 &val) const
{ return !(*this == val);}
bool operator > (const Int128 &val) const
{
if (hi != val.hi)
return hi > val.hi;
else
return lo > val.lo;
}
bool operator < (const Int128 &val) const
{
if (hi != val.hi)
return hi < val.hi;
else
return lo < val.lo;
}
bool operator >= (const Int128 &val) const
{ return !(*this < val);}
bool operator <= (const Int128 &val) const
{ return !(*this > val);}
Int128& operator += (const Int128 &rhs)
{
hi += rhs.hi;
lo += rhs.lo;
if (lo < rhs.lo) hi++;
return *this;
}
Int128 operator + (const Int128 &rhs) const
{
Int128 result(*this);
result+= rhs;
return result;
}
Int128& operator -= (const Int128 &rhs)
{
*this += -rhs;
return *this;
}
Int128 operator - (const Int128 &rhs) const
{
Int128 result(*this);
result -= rhs;
return result;
}
Int128 operator-() const //unary negation
{
if (lo == 0)
return Int128(-hi, 0);
else
return Int128(~hi, ~lo + 1);
}
operator double() const
{
const double shift64 = 18446744073709551616.0; //2^64
if (hi < 0)
{
if (lo == 0) return (double)hi * shift64;
else return -(double)(~lo + ~hi * shift64);
}
else
return (double)(lo + hi * shift64);
}
};
//------------------------------------------------------------------------------
Int128 Int128Mul (long64 lhs, long64 rhs)
{
bool negate = (lhs < 0) != (rhs < 0);
if (lhs < 0) lhs = -lhs;
ulong64 int1Hi = ulong64(lhs) >> 32;
ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF);
if (rhs < 0) rhs = -rhs;
ulong64 int2Hi = ulong64(rhs) >> 32;
ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF);
//nb: see comments in clipper.pas
ulong64 a = int1Hi * int2Hi;
ulong64 b = int1Lo * int2Lo;
ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;
Int128 tmp;
tmp.hi = long64(a + (c >> 32));
tmp.lo = long64(c << 32);
tmp.lo += long64(b);
if (tmp.lo < b) tmp.hi++;
if (negate) tmp = -tmp;
return tmp;
};
#endif
//------------------------------------------------------------------------------
// Miscellaneous global functions
//------------------------------------------------------------------------------
bool Orientation(const Path &poly)
{
return Area(poly) >= 0;
}
//------------------------------------------------------------------------------
double Area(const Path &poly)
{
int size = (int)poly.size();
if (size < 3) return 0;
double a = 0;
for (int i = 0, j = size -1; i < size; ++i)
{
a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y);
j = i;
}
return -a * 0.5;
}
//------------------------------------------------------------------------------
double Area(const OutPt *op)
{
const OutPt *startOp = op;
if (!op) return 0;
double a = 0;
do {
a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y);
op = op->Next;
} while (op != startOp);
return a * 0.5;
}
//------------------------------------------------------------------------------
double Area(const OutRec &outRec)
{
return Area(outRec.Pts);
}
//------------------------------------------------------------------------------
bool PointIsVertex(const IntPoint &Pt, OutPt *pp)
{
OutPt *pp2 = pp;
do
{
if (pp2->Pt == Pt) return true;
pp2 = pp2->Next;
}
while (pp2 != pp);
return false;
}
//------------------------------------------------------------------------------
//See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos
//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf
int PointInPolygon(const IntPoint &pt, const Path &path)
{
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
int result = 0;
size_t cnt = path.size();
if (cnt < 3) return 0;
IntPoint ip = path[0];
for(size_t i = 1; i <= cnt; ++i)
{
IntPoint ipNext = (i == cnt ? path[0] : path[i]);
if (ipNext.Y == pt.Y)
{
if ((ipNext.X == pt.X) || (ip.Y == pt.Y &&
((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1;
}
if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y))
{
if (ip.X >= pt.X)
{
if (ipNext.X > pt.X) result = 1 - result;
else
{
double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
(double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
}
} else
{
if (ipNext.X > pt.X)
{
double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
(double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
}
}
}
ip = ipNext;
}
return result;
}
//------------------------------------------------------------------------------
int PointInPolygon (const IntPoint &pt, OutPt *op)
{
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
int result = 0;
OutPt* startOp = op;
for(;;)
{
if (op->Next->Pt.Y == pt.Y)
{
if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y &&
((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1;
}
if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y))
{
if (op->Pt.X >= pt.X)
{
if (op->Next->Pt.X > pt.X) result = 1 - result;
else
{
double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
(double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
}
} else
{
if (op->Next->Pt.X > pt.X)
{
double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
(double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
}
}
}
op = op->Next;
if (startOp == op) break;
}
return result;
}
//------------------------------------------------------------------------------
bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)
{
OutPt* op = OutPt1;
do
{
//nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon
int res = PointInPolygon(op->Pt, OutPt2);
if (res >= 0) return res > 0;
op = op->Next;
}
while (op != OutPt1);
return true;
}
//----------------------------------------------------------------------
bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(e1.Top.Y - e1.Bot.Y, e2.Top.X - e2.Bot.X) ==
Int128Mul(e1.Top.X - e1.Bot.X, e2.Top.Y - e2.Bot.Y);
else
#endif
return (e1.Top.Y - e1.Bot.Y) * (e2.Top.X - e2.Bot.X) ==
(e1.Top.X - e1.Bot.X) * (e2.Top.Y - e2.Bot.Y);
}
//------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
const IntPoint pt3, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y);
else
#endif
return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);
}
//------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y);
else
#endif
return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);
}
//------------------------------------------------------------------------------
inline bool IsHorizontal(TEdge &e)
{
return e.Dx == HORIZONTAL;
}
//------------------------------------------------------------------------------
inline double GetDx(const IntPoint pt1, const IntPoint pt2)
{
return (pt1.Y == pt2.Y) ?
HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);
}
//---------------------------------------------------------------------------
inline void SetDx(TEdge &e)
{
cInt dy = (e.Top.Y - e.Bot.Y);
if (dy == 0) e.Dx = HORIZONTAL;
else e.Dx = (double)(e.Top.X - e.Bot.X) / dy;
}
//---------------------------------------------------------------------------
inline void SwapSides(TEdge &Edge1, TEdge &Edge2)
{
EdgeSide Side = Edge1.Side;
Edge1.Side = Edge2.Side;
Edge2.Side = Side;
}
//------------------------------------------------------------------------------
inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2)
{
int OutIdx = Edge1.OutIdx;
Edge1.OutIdx = Edge2.OutIdx;
Edge2.OutIdx = OutIdx;
}
//------------------------------------------------------------------------------
inline cInt TopX(TEdge &edge, const cInt currentY)
{
return ( currentY == edge.Top.Y ) ?
edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y));
}
//------------------------------------------------------------------------------
void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip)
{
#ifdef use_xyz
ip.Z = 0;
#endif
double b1, b2;
if (Edge1.Dx == Edge2.Dx)
{
ip.Y = Edge1.Curr.Y;
ip.X = TopX(Edge1, ip.Y);
return;
}
else if (Edge1.Dx == 0)
{
ip.X = Edge1.Bot.X;
if (IsHorizontal(Edge2))
ip.Y = Edge2.Bot.Y;
else
{
b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx);
ip.Y = Round(ip.X / Edge2.Dx + b2);
}
}
else if (Edge2.Dx == 0)
{
ip.X = Edge2.Bot.X;
if (IsHorizontal(Edge1))
ip.Y = Edge1.Bot.Y;
else
{
b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx);
ip.Y = Round(ip.X / Edge1.Dx + b1);
}
}
else
{
b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx;
b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx;
double q = (b2-b1) / (Edge1.Dx - Edge2.Dx);
ip.Y = Round(q);
if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
ip.X = Round(Edge1.Dx * q + b1);
else
ip.X = Round(Edge2.Dx * q + b2);
}
if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y)
{
if (Edge1.Top.Y > Edge2.Top.Y)
ip.Y = Edge1.Top.Y;
else
ip.Y = Edge2.Top.Y;
if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
ip.X = TopX(Edge1, ip.Y);
else
ip.X = TopX(Edge2, ip.Y);
}
//finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...
if (ip.Y > Edge1.Curr.Y)
{
ip.Y = Edge1.Curr.Y;
//use the more vertical edge to derive X ...
if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx))
ip.X = TopX(Edge2, ip.Y); else
ip.X = TopX(Edge1, ip.Y);
}
}
//------------------------------------------------------------------------------
void ReversePolyPtLinks(OutPt *pp)
{
if (!pp) return;
OutPt *pp1, *pp2;
pp1 = pp;
do {
pp2 = pp1->Next;
pp1->Next = pp1->Prev;
pp1->Prev = pp2;
pp1 = pp2;
} while( pp1 != pp );
}
//------------------------------------------------------------------------------
void DisposeOutPts(OutPt*& pp)
{
if (pp == 0) return;
pp->Prev->Next = 0;
while( pp )
{
OutPt *tmpPp = pp;
pp = pp->Next;
delete tmpPp;
}
}
//------------------------------------------------------------------------------
inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)
{
std::memset(e, 0, sizeof(TEdge));
e->Next = eNext;
e->Prev = ePrev;
e->Curr = Pt;
e->OutIdx = Unassigned;
}
//------------------------------------------------------------------------------
void InitEdge2(TEdge& e, PolyType Pt)
{
if (e.Curr.Y >= e.Next->Curr.Y)
{
e.Bot = e.Curr;
e.Top = e.Next->Curr;
} else
{
e.Top = e.Curr;
e.Bot = e.Next->Curr;
}
SetDx(e);
e.PolyTyp = Pt;
}
//------------------------------------------------------------------------------
TEdge* RemoveEdge(TEdge* e)
{
//removes e from double_linked_list (but without removing from memory)
e->Prev->Next = e->Next;
e->Next->Prev = e->Prev;
TEdge* result = e->Next;
e->Prev = 0; //flag as removed (see ClipperBase.Clear)
return result;
}
//------------------------------------------------------------------------------
inline void ReverseHorizontal(TEdge &e)
{
//swap horizontal edges' Top and Bottom x's so they follow the natural
//progression of the bounds - ie so their xbots will align with the
//adjoining lower edge. [Helpful in the ProcessHorizontal() method.]
std::swap(e.Top.X, e.Bot.X);
#ifdef use_xyz
std::swap(e.Top.Z, e.Bot.Z);
#endif
}
//------------------------------------------------------------------------------
void SwapPoints(IntPoint &pt1, IntPoint &pt2)
{
IntPoint tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
//------------------------------------------------------------------------------
bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,
IntPoint pt2b, IntPoint &pt1, IntPoint &pt2)
{
//precondition: segments are Collinear.
if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y))
{
if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b);
if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b);
if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a;
if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b;
return pt1.X < pt2.X;
} else
{
if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b);
if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b);
if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a;
if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b;
return pt1.Y > pt2.Y;
}
}
//------------------------------------------------------------------------------
bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2)
{
OutPt *p = btmPt1->Prev;
while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev;
double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt));
p = btmPt1->Next;
while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next;
double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt));
p = btmPt2->Prev;
while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev;
double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt));
p = btmPt2->Next;
while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next;
double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt));
if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) &&
std::min(dx1p, dx1n) == std::min(dx2p, dx2n))
return Area(btmPt1) > 0; //if otherwise identical use orientation
else
return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);
}
//------------------------------------------------------------------------------
OutPt* GetBottomPt(OutPt *pp)
{
OutPt* dups = 0;
OutPt* p = pp->Next;
while (p != pp)
{
if (p->Pt.Y > pp->Pt.Y)
{
pp = p;
dups = 0;
}
else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X)
{
if (p->Pt.X < pp->Pt.X)
{
dups = 0;
pp = p;
} else
{
if (p->Next != pp && p->Prev != pp) dups = p;
}
}
p = p->Next;
}
if (dups)
{
//there appears to be at least 2 vertices at BottomPt so ...
while (dups != p)
{
if (!FirstIsBottomPt(p, dups)) pp = dups;
dups = dups->Next;
while (dups->Pt != pp->Pt) dups = dups->Next;
}
}
return pp;
}
//------------------------------------------------------------------------------
bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1,
const IntPoint pt2, const IntPoint pt3)
{
if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))
return false;
else if (pt1.X != pt3.X)
return (pt2.X > pt1.X) == (pt2.X < pt3.X);
else
return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y);
}
//------------------------------------------------------------------------------
bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)
{
if (seg1a > seg1b) std::swap(seg1a, seg1b);
if (seg2a > seg2b) std::swap(seg2a, seg2b);
return (seg1a < seg2b) && (seg2a < seg1b);
}
//------------------------------------------------------------------------------
// ClipperBase class methods ...
//------------------------------------------------------------------------------
ClipperBase::ClipperBase() //constructor
{
m_CurrentLM = m_MinimaList.begin(); //begin() == end() here
m_UseFullRange = false;
}
//------------------------------------------------------------------------------
ClipperBase::~ClipperBase() //destructor
{
Clear();
}
//------------------------------------------------------------------------------
void RangeTest(const IntPoint& Pt, bool& useFullRange)
{
if (useFullRange)
{
if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange)
throw clipperException("Coordinate outside allowed range");
}
else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange)
{
useFullRange = true;
RangeTest(Pt, useFullRange);
}
}
//------------------------------------------------------------------------------
TEdge* FindNextLocMin(TEdge* E)
{
for (;;)
{
while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next;
if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break;
while (IsHorizontal(*E->Prev)) E = E->Prev;
TEdge* E2 = E;
while (IsHorizontal(*E)) E = E->Next;
if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz.
if (E2->Prev->Bot.X < E->Bot.X) E = E2;
break;
}
return E;
}
//------------------------------------------------------------------------------
TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
{
TEdge *Result = E;
TEdge *Horz = 0;
if (E->OutIdx == Skip)
{
//if edges still remain in the current bound beyond the skip edge then
//create another LocMin and call ProcessBound once more
if (NextIsForward)
{
while (E->Top.Y == E->Next->Bot.Y) E = E->Next;
//don't include top horizontals when parsing a bound a second time,
//they will be contained in the opposite bound ...
while (E != Result && IsHorizontal(*E)) E = E->Prev;
}
else
{
while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev;
while (E != Result && IsHorizontal(*E)) E = E->Next;
}
if (E == Result)
{
if (NextIsForward) Result = E->Next;
else Result = E->Prev;
}
else
{
//there are more edges in the bound beyond result starting with E
if (NextIsForward)
E = Result->Next;
else
E = Result->Prev;
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
locMin.LeftBound = 0;
locMin.RightBound = E;
E->WindDelta = 0;
Result = ProcessBound(E, NextIsForward);
m_MinimaList.push_back(locMin);
}
return Result;
}
TEdge *EStart;
if (IsHorizontal(*E))
{
//We need to be careful with open paths because this may not be a
//true local minima (ie E may be following a skip edge).
//Also, consecutive horz. edges may start heading left before going right.
if (NextIsForward)
EStart = E->Prev;
else
EStart = E->Next;
if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge
{
if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X)
ReverseHorizontal(*E);
}
else if (EStart->Bot.X != E->Bot.X)
ReverseHorizontal(*E);
}
EStart = E;
if (NextIsForward)
{
while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip)
Result = Result->Next;
if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip)
{
//nb: at the top of a bound, horizontals are added to the bound
//only when the preceding edge attaches to the horizontal's left vertex
//unless a Skip edge is encountered when that becomes the top divide
Horz = Result;
while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;
if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;
}
while (E != Result)
{
E->NextInLML = E->Next;
if (IsHorizontal(*E) && E != EStart &&
E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
E = E->Next;
}
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X)
ReverseHorizontal(*E);
Result = Result->Next; //move to the edge just beyond current bound
} else
{
while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip)
Result = Result->Prev;
if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)
{
Horz = Result;
while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;
if (Horz->Next->Top.X == Result->Prev->Top.X ||
Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;
}
while (E != Result)
{
E->NextInLML = E->Prev;
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
ReverseHorizontal(*E);
E = E->Prev;
}
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
ReverseHorizontal(*E);
Result = Result->Prev; //move to the edge just beyond current bound
}
return Result;
}
//------------------------------------------------------------------------------
bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
{
#ifdef use_lines
if (!Closed && PolyTyp == ptClip)
throw clipperException("AddPath: Open paths must be subject.");
#else
if (!Closed)
throw clipperException("AddPath: Open paths have been disabled.");
#endif
int highI = (int)pg.size() -1;
if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI;
while (highI > 0 && (pg[highI] == pg[highI -1])) --highI;
if ((Closed && highI < 2) || (!Closed && highI < 1)) return false;
//create a new edge array ...
TEdge *edges = new TEdge [highI +1];
bool IsFlat = true;
//1. Basic (first) edge initialization ...
try
{
edges[1].Curr = pg[1];
RangeTest(pg[0], m_UseFullRange);
RangeTest(pg[highI], m_UseFullRange);
InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]);
InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]);
for (int i = highI - 1; i >= 1; --i)
{
RangeTest(pg[i], m_UseFullRange);
InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]);
}
}
catch(...)
{
delete [] edges;
throw; //range test fails
}
TEdge *eStart = &edges[0];
//2. Remove duplicate vertices, and (when closed) collinear edges ...
TEdge *E = eStart, *eLoopStop = eStart;
for (;;)
{
//nb: allows matching start and end points when not Closed ...
if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart))
{
if (E == E->Next) break;
if (E == eStart) eStart = E->Next;
E = RemoveEdge(E);
eLoopStop = E;
continue;
}
if (E->Prev == E->Next)
break; //only two vertices
else if (Closed &&
SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) &&
(!m_PreserveCollinear ||
!Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr)))
{
//Collinear edges are allowed for open paths but in closed paths
//the default is to merge adjacent collinear edges into a single edge.
//However, if the PreserveCollinear property is enabled, only overlapping
//collinear edges (ie spikes) will be removed from closed paths.
if (E == eStart) eStart = E->Next;
E = RemoveEdge(E);
E = E->Prev;
eLoopStop = E;
continue;
}
E = E->Next;
if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break;
}
if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next)))
{
delete [] edges;
return false;
}
if (!Closed)
{
m_HasOpenPaths = true;
eStart->Prev->OutIdx = Skip;
}
//3. Do second stage of edge initialization ...
E = eStart;
do
{
InitEdge2(*E, PolyTyp);
E = E->Next;
if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false;
}
while (E != eStart);
//4. Finally, add edge bounds to LocalMinima list ...
//Totally flat paths must be handled differently when adding them
//to LocalMinima list to avoid endless loops etc ...
if (IsFlat)
{
if (Closed)
{
delete [] edges;
return false;
}
E->Prev->OutIdx = Skip;
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
locMin.LeftBound = 0;
locMin.RightBound = E;
locMin.RightBound->Side = esRight;
locMin.RightBound->WindDelta = 0;
for (;;)
{
if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
if (E->Next->OutIdx == Skip) break;
E->NextInLML = E->Next;
E = E->Next;
}
m_MinimaList.push_back(locMin);
m_edges.push_back(edges);
return true;
}
m_edges.push_back(edges);
bool leftBoundIsForward;
TEdge* EMin = 0;
//workaround to avoid an endless loop in the while loop below when
//open paths have matching start and end points ...
if (E->Prev->Bot == E->Prev->Top) E = E->Next;
for (;;)
{
E = FindNextLocMin(E);
if (E == EMin) break;
else if (!EMin) EMin = E;
//E and E.Prev now share a local minima (left aligned if horizontal).
//Compare their slopes to find which starts which bound ...
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
if (E->Dx < E->Prev->Dx)
{
locMin.LeftBound = E->Prev;
locMin.RightBound = E;
leftBoundIsForward = false; //Q.nextInLML = Q.prev
} else
{
locMin.LeftBound = E;
locMin.RightBound = E->Prev;
leftBoundIsForward = true; //Q.nextInLML = Q.next
}
if (!Closed) locMin.LeftBound->WindDelta = 0;
else if (locMin.LeftBound->Next == locMin.RightBound)
locMin.LeftBound->WindDelta = -1;
else locMin.LeftBound->WindDelta = 1;
locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta;
E = ProcessBound(locMin.LeftBound, leftBoundIsForward);
if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward);
TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward);
if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward);
if (locMin.LeftBound->OutIdx == Skip)
locMin.LeftBound = 0;
else if (locMin.RightBound->OutIdx == Skip)
locMin.RightBound = 0;
m_MinimaList.push_back(locMin);
if (!leftBoundIsForward) E = E2;
}
return true;
}
//------------------------------------------------------------------------------
bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
{
bool result = false;
for (Paths::size_type i = 0; i < ppg.size(); ++i)
if (AddPath(ppg[i], PolyTyp, Closed)) result = true;
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::Clear()
{
DisposeLocalMinimaList();
for (EdgeList::size_type i = 0; i < m_edges.size(); ++i)
{
TEdge* edges = m_edges[i];
delete [] edges;
}
m_edges.clear();
m_UseFullRange = false;
m_HasOpenPaths = false;
}
//------------------------------------------------------------------------------
void ClipperBase::Reset()
{
m_CurrentLM = m_MinimaList.begin();
if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process
std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter());
m_Scanbeam = ScanbeamList(); //clears/resets priority_queue
//reset all edges ...
for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
{
InsertScanbeam(lm->Y);
TEdge* e = lm->LeftBound;
if (e)
{
e->Curr = e->Bot;
e->Side = esLeft;
e->OutIdx = Unassigned;
}
e = lm->RightBound;
if (e)
{
e->Curr = e->Bot;
e->Side = esRight;
e->OutIdx = Unassigned;
}
}
m_ActiveEdges = 0;
m_CurrentLM = m_MinimaList.begin();
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeLocalMinimaList()
{
m_MinimaList.clear();
m_CurrentLM = m_MinimaList.begin();
}
//------------------------------------------------------------------------------
bool ClipperBase::PopLocalMinima(cInt Y, const LocalMinimum *&locMin)
{
if (m_CurrentLM == m_MinimaList.end() || (*m_CurrentLM).Y != Y) return false;
locMin = &(*m_CurrentLM);
++m_CurrentLM;
return true;
}
//------------------------------------------------------------------------------
IntRect ClipperBase::GetBounds()
{
IntRect result;
MinimaList::iterator lm = m_MinimaList.begin();
if (lm == m_MinimaList.end())
{
result.left = result.top = result.right = result.bottom = 0;
return result;
}
result.left = lm->LeftBound->Bot.X;
result.top = lm->LeftBound->Bot.Y;
result.right = lm->LeftBound->Bot.X;
result.bottom = lm->LeftBound->Bot.Y;
while (lm != m_MinimaList.end())
{
//todo - needs fixing for open paths
result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y);
TEdge* e = lm->LeftBound;
for (;;) {
TEdge* bottomE = e;
while (e->NextInLML)
{
if (e->Bot.X < result.left) result.left = e->Bot.X;
if (e->Bot.X > result.right) result.right = e->Bot.X;
e = e->NextInLML;
}
result.left = std::min(result.left, e->Bot.X);
result.right = std::max(result.right, e->Bot.X);
result.left = std::min(result.left, e->Top.X);
result.right = std::max(result.right, e->Top.X);
result.top = std::min(result.top, e->Top.Y);
if (bottomE == lm->LeftBound) e = lm->RightBound;
else break;
}
++lm;
}
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::InsertScanbeam(const cInt Y)
{
m_Scanbeam.push(Y);
}
//------------------------------------------------------------------------------
bool ClipperBase::PopScanbeam(cInt &Y)
{
if (m_Scanbeam.empty()) return false;
Y = m_Scanbeam.top();
m_Scanbeam.pop();
while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates.
return true;
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeAllOutRecs(){
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
DisposeOutRec(i);
m_PolyOuts.clear();
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeOutRec(PolyOutList::size_type index)
{
OutRec *outRec = m_PolyOuts[index];
if (outRec->Pts) DisposeOutPts(outRec->Pts);
delete outRec;
m_PolyOuts[index] = 0;
}
//------------------------------------------------------------------------------
void ClipperBase::DeleteFromAEL(TEdge *e)
{
TEdge* AelPrev = e->PrevInAEL;
TEdge* AelNext = e->NextInAEL;
if (!AelPrev && !AelNext && (e != m_ActiveEdges)) return; //already deleted
if (AelPrev) AelPrev->NextInAEL = AelNext;
else m_ActiveEdges = AelNext;
if (AelNext) AelNext->PrevInAEL = AelPrev;
e->NextInAEL = 0;
e->PrevInAEL = 0;
}
//------------------------------------------------------------------------------
OutRec* ClipperBase::CreateOutRec()
{
OutRec* result = new OutRec;
result->IsHole = false;
result->IsOpen = false;
result->FirstLeft = 0;
result->Pts = 0;
result->BottomPt = 0;
result->PolyNd = 0;
m_PolyOuts.push_back(result);
result->Idx = (int)m_PolyOuts.size() - 1;
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2)
{
//check that one or other edge hasn't already been removed from AEL ...
if (Edge1->NextInAEL == Edge1->PrevInAEL ||
Edge2->NextInAEL == Edge2->PrevInAEL) return;
if (Edge1->NextInAEL == Edge2)
{
TEdge* Next = Edge2->NextInAEL;
if (Next) Next->PrevInAEL = Edge1;
TEdge* Prev = Edge1->PrevInAEL;
if (Prev) Prev->NextInAEL = Edge2;
Edge2->PrevInAEL = Prev;
Edge2->NextInAEL = Edge1;
Edge1->PrevInAEL = Edge2;
Edge1->NextInAEL = Next;
}
else if (Edge2->NextInAEL == Edge1)
{
TEdge* Next = Edge1->NextInAEL;
if (Next) Next->PrevInAEL = Edge2;
TEdge* Prev = Edge2->PrevInAEL;
if (Prev) Prev->NextInAEL = Edge1;
Edge1->PrevInAEL = Prev;
Edge1->NextInAEL = Edge2;
Edge2->PrevInAEL = Edge1;
Edge2->NextInAEL = Next;
}
else
{
TEdge* Next = Edge1->NextInAEL;
TEdge* Prev = Edge1->PrevInAEL;
Edge1->NextInAEL = Edge2->NextInAEL;
if (Edge1->NextInAEL) Edge1->NextInAEL->PrevInAEL = Edge1;
Edge1->PrevInAEL = Edge2->PrevInAEL;
if (Edge1->PrevInAEL) Edge1->PrevInAEL->NextInAEL = Edge1;
Edge2->NextInAEL = Next;
if (Edge2->NextInAEL) Edge2->NextInAEL->PrevInAEL = Edge2;
Edge2->PrevInAEL = Prev;
if (Edge2->PrevInAEL) Edge2->PrevInAEL->NextInAEL = Edge2;
}
if (!Edge1->PrevInAEL) m_ActiveEdges = Edge1;
else if (!Edge2->PrevInAEL) m_ActiveEdges = Edge2;
}
//------------------------------------------------------------------------------
void ClipperBase::UpdateEdgeIntoAEL(TEdge *&e)
{
if (!e->NextInLML)
throw clipperException("UpdateEdgeIntoAEL: invalid call");
e->NextInLML->OutIdx = e->OutIdx;
TEdge* AelPrev = e->PrevInAEL;
TEdge* AelNext = e->NextInAEL;
if (AelPrev) AelPrev->NextInAEL = e->NextInLML;
else m_ActiveEdges = e->NextInLML;
if (AelNext) AelNext->PrevInAEL = e->NextInLML;
e->NextInLML->Side = e->Side;
e->NextInLML->WindDelta = e->WindDelta;
e->NextInLML->WindCnt = e->WindCnt;
e->NextInLML->WindCnt2 = e->WindCnt2;
e = e->NextInLML;
e->Curr = e->Bot;
e->PrevInAEL = AelPrev;
e->NextInAEL = AelNext;
if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y);
}
//------------------------------------------------------------------------------
bool ClipperBase::LocalMinimaPending()
{
return (m_CurrentLM != m_MinimaList.end());
}
//------------------------------------------------------------------------------
// TClipper methods ...
//------------------------------------------------------------------------------
Clipper::Clipper(int initOptions) : ClipperBase() //constructor
{
m_ExecuteLocked = false;
m_UseFullRange = false;
m_ReverseOutput = ((initOptions & ioReverseSolution) != 0);
m_StrictSimple = ((initOptions & ioStrictlySimple) != 0);
m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0);
m_HasOpenPaths = false;
#ifdef use_xyz
m_ZFill = 0;
#endif
}
//------------------------------------------------------------------------------
#ifdef use_xyz
void Clipper::ZFillFunction(ZFillCallback zFillFunc)
{
m_ZFill = zFillFunc;
}
//------------------------------------------------------------------------------
#endif
bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType)
{
return Execute(clipType, solution, fillType, fillType);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType)
{
return Execute(clipType, polytree, fillType, fillType);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, Paths &solution,
PolyFillType subjFillType, PolyFillType clipFillType)
{
if( m_ExecuteLocked ) return false;
if (m_HasOpenPaths)
throw clipperException("Error: PolyTree struct is needed for open path clipping.");
m_ExecuteLocked = true;
solution.resize(0);
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
m_UsingPolyTree = false;
bool succeeded = ExecuteInternal();
if (succeeded) BuildResult(solution);
DisposeAllOutRecs();
m_ExecuteLocked = false;
return succeeded;
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
PolyFillType subjFillType, PolyFillType clipFillType)
{
if( m_ExecuteLocked ) return false;
m_ExecuteLocked = true;
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
m_UsingPolyTree = true;
bool succeeded = ExecuteInternal();
if (succeeded) BuildResult2(polytree);
DisposeAllOutRecs();
m_ExecuteLocked = false;
return succeeded;
}
//------------------------------------------------------------------------------
void Clipper::FixHoleLinkage(OutRec &outrec)
{
//skip OutRecs that (a) contain outermost polygons or
//(b) already have the correct owner/child linkage ...
if (!outrec.FirstLeft ||
(outrec.IsHole != outrec.FirstLeft->IsHole &&
outrec.FirstLeft->Pts)) return;
OutRec* orfl = outrec.FirstLeft;
while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts))
orfl = orfl->FirstLeft;
outrec.FirstLeft = orfl;
}
//------------------------------------------------------------------------------
bool Clipper::ExecuteInternal()
{
bool succeeded = true;
try {
Reset();
m_Maxima = MaximaList();
m_SortedEdges = 0;
succeeded = true;
cInt botY, topY;
if (!PopScanbeam(botY)) return false;
InsertLocalMinimaIntoAEL(botY);
while (PopScanbeam(topY) || LocalMinimaPending())
{
ProcessHorizontals();
ClearGhostJoins();
if (!ProcessIntersections(topY))
{
succeeded = false;
break;
}
ProcessEdgesAtTopOfScanbeam(topY);
botY = topY;
InsertLocalMinimaIntoAEL(botY);
}
}
catch(...)
{
succeeded = false;
}
if (succeeded)
{
//fix orientations ...
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec *outRec = m_PolyOuts[i];
if (!outRec->Pts || outRec->IsOpen) continue;
if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))
ReversePolyPtLinks(outRec->Pts);
}
if (!m_Joins.empty()) JoinCommonEdges();
//unfortunately FixupOutPolygon() must be done after JoinCommonEdges()
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec *outRec = m_PolyOuts[i];
if (!outRec->Pts) continue;
if (outRec->IsOpen)
FixupOutPolyline(*outRec);
else
FixupOutPolygon(*outRec);
}
if (m_StrictSimple) DoSimplePolygons();
}
ClearJoins();
ClearGhostJoins();
return succeeded;
}
//------------------------------------------------------------------------------
void Clipper::SetWindingCount(TEdge &edge)
{
TEdge *e = edge.PrevInAEL;
//find the edge of the same polytype that immediately preceeds 'edge' in AEL
while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL;
if (!e)
{
if (edge.WindDelta == 0)
{
PolyFillType pft = (edge.PolyTyp == ptSubject ? m_SubjFillType : m_ClipFillType);
edge.WindCnt = (pft == pftNegative ? -1 : 1);
}
else
edge.WindCnt = edge.WindDelta;
edge.WindCnt2 = 0;
e = m_ActiveEdges; //ie get ready to calc WindCnt2
}
else if (edge.WindDelta == 0 && m_ClipType != ctUnion)
{
edge.WindCnt = 1;
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
else if (IsEvenOddFillType(edge))
{
//EvenOdd filling ...
if (edge.WindDelta == 0)
{
//are we inside a subj polygon ...
bool Inside = true;
TEdge *e2 = e->PrevInAEL;
while (e2)
{
if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0)
Inside = !Inside;
e2 = e2->PrevInAEL;
}
edge.WindCnt = (Inside ? 0 : 1);
}
else
{
edge.WindCnt = edge.WindDelta;
}
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
else
{
//nonZero, Positive or Negative filling ...
if (e->WindCnt * e->WindDelta < 0)
{
//prev edge is 'decreasing' WindCount (WC) toward zero
//so we're outside the previous polygon ...
if (Abs(e->WindCnt) > 1)
{
//outside prev poly but still inside another.
//when reversing direction of prev poly use the same WC
if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
//otherwise continue to 'decrease' WC ...
else edge.WindCnt = e->WindCnt + edge.WindDelta;
}
else
//now outside all polys of same polytype so set own WC ...
edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
} else
{
//prev edge is 'increasing' WindCount (WC) away from zero
//so we're inside the previous polygon ...
if (edge.WindDelta == 0)
edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1);
//if wind direction is reversing prev then use same WC
else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
//otherwise add to WC ...
else edge.WindCnt = e->WindCnt + edge.WindDelta;
}
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
//update WindCnt2 ...
if (IsEvenOddAltFillType(edge))
{
//EvenOdd filling ...
while (e != &edge)
{
if (e->WindDelta != 0)
edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0);
e = e->NextInAEL;
}
} else
{
//nonZero, Positive or Negative filling ...
while ( e != &edge )
{
edge.WindCnt2 += e->WindDelta;
e = e->NextInAEL;
}
}
}
//------------------------------------------------------------------------------
bool Clipper::IsEvenOddFillType(const TEdge& edge) const
{
if (edge.PolyTyp == ptSubject)
return m_SubjFillType == pftEvenOdd; else
return m_ClipFillType == pftEvenOdd;
}
//------------------------------------------------------------------------------
bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const
{
if (edge.PolyTyp == ptSubject)
return m_ClipFillType == pftEvenOdd; else
return m_SubjFillType == pftEvenOdd;
}
//------------------------------------------------------------------------------
bool Clipper::IsContributing(const TEdge& edge) const
{
PolyFillType pft, pft2;
if (edge.PolyTyp == ptSubject)
{
pft = m_SubjFillType;
pft2 = m_ClipFillType;
} else
{
pft = m_ClipFillType;
pft2 = m_SubjFillType;
}
switch(pft)
{
case pftEvenOdd:
//return false if a subj line has been flagged as inside a subj polygon
if (edge.WindDelta == 0 && edge.WindCnt != 1) return false;
break;
case pftNonZero:
if (Abs(edge.WindCnt) != 1) return false;
break;
case pftPositive:
if (edge.WindCnt != 1) return false;
break;
default: //pftNegative
if (edge.WindCnt != -1) return false;
}
switch(m_ClipType)
{
case ctIntersection:
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 != 0);
case pftPositive:
return (edge.WindCnt2 > 0);
default:
return (edge.WindCnt2 < 0);
}
break;
case ctUnion:
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
break;
case ctDifference:
if (edge.PolyTyp == ptSubject)
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
else
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 != 0);
case pftPositive:
return (edge.WindCnt2 > 0);
default:
return (edge.WindCnt2 < 0);
}
break;
case ctXor:
if (edge.WindDelta == 0) //XOr always contributing unless open
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
else
return true;
break;
default:
return true;
}
}
//------------------------------------------------------------------------------
OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
OutPt* result;
TEdge *e, *prevE;
if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))
{
result = AddOutPt(e1, Pt);
e2->OutIdx = e1->OutIdx;
e1->Side = esLeft;
e2->Side = esRight;
e = e1;
if (e->PrevInAEL == e2)
prevE = e2->PrevInAEL;
else
prevE = e->PrevInAEL;
} else
{
result = AddOutPt(e2, Pt);
e1->OutIdx = e2->OutIdx;
e1->Side = esRight;
e2->Side = esLeft;
e = e2;
if (e->PrevInAEL == e1)
prevE = e1->PrevInAEL;
else
prevE = e->PrevInAEL;
}
if (prevE && prevE->OutIdx >= 0 && prevE->Top.Y < Pt.Y && e->Top.Y < Pt.Y)
{
cInt xPrev = TopX(*prevE, Pt.Y);
cInt xE = TopX(*e, Pt.Y);
if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) &&
SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange))
{
OutPt* outPt = AddOutPt(prevE, Pt);
AddJoin(result, outPt, e->Top);
}
}
return result;
}
//------------------------------------------------------------------------------
void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
AddOutPt( e1, Pt );
if (e2->WindDelta == 0) AddOutPt(e2, Pt);
if( e1->OutIdx == e2->OutIdx )
{
e1->OutIdx = Unassigned;
e2->OutIdx = Unassigned;
}
else if (e1->OutIdx < e2->OutIdx)
AppendPolygon(e1, e2);
else
AppendPolygon(e2, e1);
}
//------------------------------------------------------------------------------
void Clipper::AddEdgeToSEL(TEdge *edge)
{
//SEL pointers in PEdge are reused to build a list of horizontal edges.
//However, we don't need to worry about order with horizontal edge processing.
if( !m_SortedEdges )
{
m_SortedEdges = edge;
edge->PrevInSEL = 0;
edge->NextInSEL = 0;
}
else
{
edge->NextInSEL = m_SortedEdges;
edge->PrevInSEL = 0;
m_SortedEdges->PrevInSEL = edge;
m_SortedEdges = edge;
}
}
//------------------------------------------------------------------------------
bool Clipper::PopEdgeFromSEL(TEdge *&edge)
{
if (!m_SortedEdges) return false;
edge = m_SortedEdges;
DeleteFromSEL(m_SortedEdges);
return true;
}
//------------------------------------------------------------------------------
void Clipper::CopyAELToSEL()
{
TEdge* e = m_ActiveEdges;
m_SortedEdges = e;
while ( e )
{
e->PrevInSEL = e->PrevInAEL;
e->NextInSEL = e->NextInAEL;
e = e->NextInAEL;
}
}
//------------------------------------------------------------------------------
void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt)
{
Join* j = new Join;
j->OutPt1 = op1;
j->OutPt2 = op2;
j->OffPt = OffPt;
m_Joins.push_back(j);
}
//------------------------------------------------------------------------------
void Clipper::ClearJoins()
{
for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
delete m_Joins[i];
m_Joins.resize(0);
}
//------------------------------------------------------------------------------
void Clipper::ClearGhostJoins()
{
for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++)
delete m_GhostJoins[i];
m_GhostJoins.resize(0);
}
//------------------------------------------------------------------------------
void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt)
{
Join* j = new Join;
j->OutPt1 = op;
j->OutPt2 = 0;
j->OffPt = OffPt;
m_GhostJoins.push_back(j);
}
//------------------------------------------------------------------------------
void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)
{
const LocalMinimum *lm;
while (PopLocalMinima(botY, lm))
{
TEdge* lb = lm->LeftBound;
TEdge* rb = lm->RightBound;
OutPt *Op1 = 0;
if (!lb)
{
//nb: don't insert LB into either AEL or SEL
InsertEdgeIntoAEL(rb, 0);
SetWindingCount(*rb);
if (IsContributing(*rb))
Op1 = AddOutPt(rb, rb->Bot);
}
else if (!rb)
{
InsertEdgeIntoAEL(lb, 0);
SetWindingCount(*lb);
if (IsContributing(*lb))
Op1 = AddOutPt(lb, lb->Bot);
InsertScanbeam(lb->Top.Y);
}
else
{
InsertEdgeIntoAEL(lb, 0);
InsertEdgeIntoAEL(rb, lb);
SetWindingCount( *lb );
rb->WindCnt = lb->WindCnt;
rb->WindCnt2 = lb->WindCnt2;
if (IsContributing(*lb))
Op1 = AddLocalMinPoly(lb, rb, lb->Bot);
InsertScanbeam(lb->Top.Y);
}
if (rb)
{
if (IsHorizontal(*rb))
{
AddEdgeToSEL(rb);
if (rb->NextInLML)
InsertScanbeam(rb->NextInLML->Top.Y);
}
else InsertScanbeam( rb->Top.Y );
}
if (!lb || !rb) continue;
//if any output polygons share an edge, they'll need joining later ...
if (Op1 && IsHorizontal(*rb) &&
m_GhostJoins.size() > 0 && (rb->WindDelta != 0))
{
for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i)
{
Join* jr = m_GhostJoins[i];
//if the horizontal Rb and a 'ghost' horizontal overlap, then convert
//the 'ghost' join to a real join ready for later ...
if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X))
AddJoin(jr->OutPt1, Op1, jr->OffPt);
}
}
if (lb->OutIdx >= 0 && lb->PrevInAEL &&
lb->PrevInAEL->Curr.X == lb->Bot.X &&
lb->PrevInAEL->OutIdx >= 0 &&
SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) &&
(lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0))
{
OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot);
AddJoin(Op1, Op2, lb->Top);
}
if(lb->NextInAEL != rb)
{
if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 &&
SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) &&
(rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0))
{
OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot);
AddJoin(Op1, Op2, rb->Top);
}
TEdge* e = lb->NextInAEL;
if (e)
{
while( e != rb )
{
//nb: For calculating winding counts etc, IntersectEdges() assumes
//that param1 will be to the Right of param2 ABOVE the intersection ...
IntersectEdges(rb , e , lb->Curr); //order important here
e = e->NextInAEL;
}
}
}
}
}
//------------------------------------------------------------------------------
void Clipper::DeleteFromSEL(TEdge *e)
{
TEdge* SelPrev = e->PrevInSEL;
TEdge* SelNext = e->NextInSEL;
if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted
if( SelPrev ) SelPrev->NextInSEL = SelNext;
else m_SortedEdges = SelNext;
if( SelNext ) SelNext->PrevInSEL = SelPrev;
e->NextInSEL = 0;
e->PrevInSEL = 0;
}
//------------------------------------------------------------------------------
#ifdef use_xyz
void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2)
{
if (pt.Z != 0 || !m_ZFill) return;
else if (pt == e1.Bot) pt.Z = e1.Bot.Z;
else if (pt == e1.Top) pt.Z = e1.Top.Z;
else if (pt == e2.Bot) pt.Z = e2.Bot.Z;
else if (pt == e2.Top) pt.Z = e2.Top.Z;
else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt);
}
//------------------------------------------------------------------------------
#endif
void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt)
{
bool e1Contributing = ( e1->OutIdx >= 0 );
bool e2Contributing = ( e2->OutIdx >= 0 );
#ifdef use_xyz
SetZ(Pt, *e1, *e2);
#endif
#ifdef use_lines
//if either edge is on an OPEN path ...
if (e1->WindDelta == 0 || e2->WindDelta == 0)
{
//ignore subject-subject open path intersections UNLESS they
//are both open paths, AND they are both 'contributing maximas' ...
if (e1->WindDelta == 0 && e2->WindDelta == 0) return;
//if intersecting a subj line with a subj poly ...
else if (e1->PolyTyp == e2->PolyTyp &&
e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion)
{
if (e1->WindDelta == 0)
{
if (e2Contributing)
{
AddOutPt(e1, Pt);
if (e1Contributing) e1->OutIdx = Unassigned;
}
}
else
{
if (e1Contributing)
{
AddOutPt(e2, Pt);
if (e2Contributing) e2->OutIdx = Unassigned;
}
}
}
else if (e1->PolyTyp != e2->PolyTyp)
{
//toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ...
if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 &&
(m_ClipType != ctUnion || e2->WindCnt2 == 0))
{
AddOutPt(e1, Pt);
if (e1Contributing) e1->OutIdx = Unassigned;
}
else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) &&
(m_ClipType != ctUnion || e1->WindCnt2 == 0))
{
AddOutPt(e2, Pt);
if (e2Contributing) e2->OutIdx = Unassigned;
}
}
return;
}
#endif
//update winding counts...
//assumes that e1 will be to the Right of e2 ABOVE the intersection
if ( e1->PolyTyp == e2->PolyTyp )
{
if ( IsEvenOddFillType( *e1) )
{
int oldE1WindCnt = e1->WindCnt;
e1->WindCnt = e2->WindCnt;
e2->WindCnt = oldE1WindCnt;
} else
{
if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt;
else e1->WindCnt += e2->WindDelta;
if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt;
else e2->WindCnt -= e1->WindDelta;
}
} else
{
if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta;
else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0;
if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta;
else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0;
}
PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;
if (e1->PolyTyp == ptSubject)
{
e1FillType = m_SubjFillType;
e1FillType2 = m_ClipFillType;
} else
{
e1FillType = m_ClipFillType;
e1FillType2 = m_SubjFillType;
}
if (e2->PolyTyp == ptSubject)
{
e2FillType = m_SubjFillType;
e2FillType2 = m_ClipFillType;
} else
{
e2FillType = m_ClipFillType;
e2FillType2 = m_SubjFillType;
}
cInt e1Wc, e2Wc;
switch (e1FillType)
{
case pftPositive: e1Wc = e1->WindCnt; break;
case pftNegative: e1Wc = -e1->WindCnt; break;
default: e1Wc = Abs(e1->WindCnt);
}
switch(e2FillType)
{
case pftPositive: e2Wc = e2->WindCnt; break;
case pftNegative: e2Wc = -e2->WindCnt; break;
default: e2Wc = Abs(e2->WindCnt);
}
if ( e1Contributing && e2Contributing )
{
if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||
(e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) )
{
AddLocalMaxPoly(e1, e2, Pt);
}
else
{
AddOutPt(e1, Pt);
AddOutPt(e2, Pt);
SwapSides( *e1 , *e2 );
SwapPolyIndexes( *e1 , *e2 );
}
}
else if ( e1Contributing )
{
if (e2Wc == 0 || e2Wc == 1)
{
AddOutPt(e1, Pt);
SwapSides(*e1, *e2);
SwapPolyIndexes(*e1, *e2);
}
}
else if ( e2Contributing )
{
if (e1Wc == 0 || e1Wc == 1)
{
AddOutPt(e2, Pt);
SwapSides(*e1, *e2);
SwapPolyIndexes(*e1, *e2);
}
}
else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1))
{
//neither edge is currently contributing ...
cInt e1Wc2, e2Wc2;
switch (e1FillType2)
{
case pftPositive: e1Wc2 = e1->WindCnt2; break;
case pftNegative : e1Wc2 = -e1->WindCnt2; break;
default: e1Wc2 = Abs(e1->WindCnt2);
}
switch (e2FillType2)
{
case pftPositive: e2Wc2 = e2->WindCnt2; break;
case pftNegative: e2Wc2 = -e2->WindCnt2; break;
default: e2Wc2 = Abs(e2->WindCnt2);
}
if (e1->PolyTyp != e2->PolyTyp)
{
AddLocalMinPoly(e1, e2, Pt);
}
else if (e1Wc == 1 && e2Wc == 1)
switch( m_ClipType ) {
case ctIntersection:
if (e1Wc2 > 0 && e2Wc2 > 0)
AddLocalMinPoly(e1, e2, Pt);
break;
case ctUnion:
if ( e1Wc2 <= 0 && e2Wc2 <= 0 )
AddLocalMinPoly(e1, e2, Pt);
break;
case ctDifference:
if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||
((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))
AddLocalMinPoly(e1, e2, Pt);
break;
case ctXor:
AddLocalMinPoly(e1, e2, Pt);
}
else
SwapSides( *e1, *e2 );
}
}
//------------------------------------------------------------------------------
void Clipper::SetHoleState(TEdge *e, OutRec *outrec)
{
TEdge *e2 = e->PrevInAEL;
TEdge *eTmp = 0;
while (e2)
{
if (e2->OutIdx >= 0 && e2->WindDelta != 0)
{
if (!eTmp) eTmp = e2;
else if (eTmp->OutIdx == e2->OutIdx) eTmp = 0;
}
e2 = e2->PrevInAEL;
}
if (!eTmp)
{
outrec->FirstLeft = 0;
outrec->IsHole = false;
}
else
{
outrec->FirstLeft = m_PolyOuts[eTmp->OutIdx];
outrec->IsHole = !outrec->FirstLeft->IsHole;
}
}
//------------------------------------------------------------------------------
OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)
{
//work out which polygon fragment has the correct hole state ...
if (!outRec1->BottomPt)
outRec1->BottomPt = GetBottomPt(outRec1->Pts);
if (!outRec2->BottomPt)
outRec2->BottomPt = GetBottomPt(outRec2->Pts);
OutPt *OutPt1 = outRec1->BottomPt;
OutPt *OutPt2 = outRec2->BottomPt;
if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1;
else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2;
else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1;
else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2;
else if (OutPt1->Next == OutPt1) return outRec2;
else if (OutPt2->Next == OutPt2) return outRec1;
else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1;
else return outRec2;
}
//------------------------------------------------------------------------------
bool OutRec1RightOfOutRec2(OutRec* outRec1, OutRec* outRec2)
{
do
{
outRec1 = outRec1->FirstLeft;
if (outRec1 == outRec2) return true;
} while (outRec1);
return false;
}
//------------------------------------------------------------------------------
OutRec* Clipper::GetOutRec(int Idx)
{
OutRec* outrec = m_PolyOuts[Idx];
while (outrec != m_PolyOuts[outrec->Idx])
outrec = m_PolyOuts[outrec->Idx];
return outrec;
}
//------------------------------------------------------------------------------
void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
{
//get the start and ends of both output polygons ...
OutRec *outRec1 = m_PolyOuts[e1->OutIdx];
OutRec *outRec2 = m_PolyOuts[e2->OutIdx];
OutRec *holeStateRec;
if (OutRec1RightOfOutRec2(outRec1, outRec2))
holeStateRec = outRec2;
else if (OutRec1RightOfOutRec2(outRec2, outRec1))
holeStateRec = outRec1;
else
holeStateRec = GetLowermostRec(outRec1, outRec2);
//get the start and ends of both output polygons and
//join e2 poly onto e1 poly and delete pointers to e2 ...
OutPt* p1_lft = outRec1->Pts;
OutPt* p1_rt = p1_lft->Prev;
OutPt* p2_lft = outRec2->Pts;
OutPt* p2_rt = p2_lft->Prev;
//join e2 poly onto e1 poly and delete pointers to e2 ...
if( e1->Side == esLeft )
{
if( e2->Side == esLeft )
{
//z y x a b c
ReversePolyPtLinks(p2_lft);
p2_lft->Next = p1_lft;
p1_lft->Prev = p2_lft;
p1_rt->Next = p2_rt;
p2_rt->Prev = p1_rt;
outRec1->Pts = p2_rt;
} else
{
//x y z a b c
p2_rt->Next = p1_lft;
p1_lft->Prev = p2_rt;
p2_lft->Prev = p1_rt;
p1_rt->Next = p2_lft;
outRec1->Pts = p2_lft;
}
} else
{
if( e2->Side == esRight )
{
//a b c z y x
ReversePolyPtLinks(p2_lft);
p1_rt->Next = p2_rt;
p2_rt->Prev = p1_rt;
p2_lft->Next = p1_lft;
p1_lft->Prev = p2_lft;
} else
{
//a b c x y z
p1_rt->Next = p2_lft;
p2_lft->Prev = p1_rt;
p1_lft->Prev = p2_rt;
p2_rt->Next = p1_lft;
}
}
outRec1->BottomPt = 0;
if (holeStateRec == outRec2)
{
if (outRec2->FirstLeft != outRec1)
outRec1->FirstLeft = outRec2->FirstLeft;
outRec1->IsHole = outRec2->IsHole;
}
outRec2->Pts = 0;
outRec2->BottomPt = 0;
outRec2->FirstLeft = outRec1;
int OKIdx = e1->OutIdx;
int ObsoleteIdx = e2->OutIdx;
e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly
e2->OutIdx = Unassigned;
TEdge* e = m_ActiveEdges;
while( e )
{
if( e->OutIdx == ObsoleteIdx )
{
e->OutIdx = OKIdx;
e->Side = e1->Side;
break;
}
e = e->NextInAEL;
}
outRec2->Idx = outRec1->Idx;
}
//------------------------------------------------------------------------------
OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt)
{
if( e->OutIdx < 0 )
{
OutRec *outRec = CreateOutRec();
outRec->IsOpen = (e->WindDelta == 0);
OutPt* newOp = new OutPt;
outRec->Pts = newOp;
newOp->Idx = outRec->Idx;
newOp->Pt = pt;
newOp->Next = newOp;
newOp->Prev = newOp;
if (!outRec->IsOpen)
SetHoleState(e, outRec);
e->OutIdx = outRec->Idx;
return newOp;
} else
{
OutRec *outRec = m_PolyOuts[e->OutIdx];
//OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'
OutPt* op = outRec->Pts;
bool ToFront = (e->Side == esLeft);
if (ToFront && (pt == op->Pt)) return op;
else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev;
OutPt* newOp = new OutPt;
newOp->Idx = outRec->Idx;
newOp->Pt = pt;
newOp->Next = op;
newOp->Prev = op->Prev;
newOp->Prev->Next = newOp;
op->Prev = newOp;
if (ToFront) outRec->Pts = newOp;
return newOp;
}
}
//------------------------------------------------------------------------------
OutPt* Clipper::GetLastOutPt(TEdge *e)
{
OutRec *outRec = m_PolyOuts[e->OutIdx];
if (e->Side == esLeft)
return outRec->Pts;
else
return outRec->Pts->Prev;
}
//------------------------------------------------------------------------------
void Clipper::ProcessHorizontals()
{
TEdge* horzEdge;
while (PopEdgeFromSEL(horzEdge))
ProcessHorizontal(horzEdge);
}
//------------------------------------------------------------------------------
inline bool IsMinima(TEdge *e)
{
return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e);
}
//------------------------------------------------------------------------------
inline bool IsMaxima(TEdge *e, const cInt Y)
{
return e && e->Top.Y == Y && !e->NextInLML;
}
//------------------------------------------------------------------------------
inline bool IsIntermediate(TEdge *e, const cInt Y)
{
return e->Top.Y == Y && e->NextInLML;
}
//------------------------------------------------------------------------------
TEdge *GetMaximaPair(TEdge *e)
{
if ((e->Next->Top == e->Top) && !e->Next->NextInLML)
return e->Next;
else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML)
return e->Prev;
else return 0;
}
//------------------------------------------------------------------------------
TEdge *GetMaximaPairEx(TEdge *e)
{
//as GetMaximaPair() but returns 0 if MaxPair isn't in AEL (unless it's horizontal)
TEdge* result = GetMaximaPair(e);
if (result && (result->OutIdx == Skip ||
(result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result)))) return 0;
return result;
}
//------------------------------------------------------------------------------
void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2)
{
if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return;
if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return;
if( Edge1->NextInSEL == Edge2 )
{
TEdge* Next = Edge2->NextInSEL;
if( Next ) Next->PrevInSEL = Edge1;
TEdge* Prev = Edge1->PrevInSEL;
if( Prev ) Prev->NextInSEL = Edge2;
Edge2->PrevInSEL = Prev;
Edge2->NextInSEL = Edge1;
Edge1->PrevInSEL = Edge2;
Edge1->NextInSEL = Next;
}
else if( Edge2->NextInSEL == Edge1 )
{
TEdge* Next = Edge1->NextInSEL;
if( Next ) Next->PrevInSEL = Edge2;
TEdge* Prev = Edge2->PrevInSEL;
if( Prev ) Prev->NextInSEL = Edge1;
Edge1->PrevInSEL = Prev;
Edge1->NextInSEL = Edge2;
Edge2->PrevInSEL = Edge1;
Edge2->NextInSEL = Next;
}
else
{
TEdge* Next = Edge1->NextInSEL;
TEdge* Prev = Edge1->PrevInSEL;
Edge1->NextInSEL = Edge2->NextInSEL;
if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1;
Edge1->PrevInSEL = Edge2->PrevInSEL;
if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1;
Edge2->NextInSEL = Next;
if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2;
Edge2->PrevInSEL = Prev;
if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2;
}
if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1;
else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2;
}
//------------------------------------------------------------------------------
TEdge* GetNextInAEL(TEdge *e, Direction dir)
{
return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL;
}
//------------------------------------------------------------------------------
void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right)
{
if (HorzEdge.Bot.X < HorzEdge.Top.X)
{
Left = HorzEdge.Bot.X;
Right = HorzEdge.Top.X;
Dir = dLeftToRight;
} else
{
Left = HorzEdge.Top.X;
Right = HorzEdge.Bot.X;
Dir = dRightToLeft;
}
}
//------------------------------------------------------------------------
/*******************************************************************************
* Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or *
* Bottom of a scanbeam) are processed as if layered. The order in which HEs *
* are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] *
* (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), *
* and with other non-horizontal edges [*]. Once these intersections are *
* processed, intermediate HEs then 'promote' the Edge above (NextInLML) into *
* the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. *
*******************************************************************************/
void Clipper::ProcessHorizontal(TEdge *horzEdge)
{
Direction dir;
cInt horzLeft, horzRight;
bool IsOpen = (horzEdge->WindDelta == 0);
GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
TEdge* eLastHorz = horzEdge, *eMaxPair = 0;
while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML))
eLastHorz = eLastHorz->NextInLML;
if (!eLastHorz->NextInLML)
eMaxPair = GetMaximaPair(eLastHorz);
MaximaList::const_iterator maxIt;
MaximaList::const_reverse_iterator maxRit;
if (m_Maxima.size() > 0)
{
//get the first maxima in range (X) ...
if (dir == dLeftToRight)
{
maxIt = m_Maxima.begin();
while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++;
if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)
maxIt = m_Maxima.end();
}
else
{
maxRit = m_Maxima.rbegin();
while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++;
if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)
maxRit = m_Maxima.rend();
}
}
OutPt* op1 = 0;
for (;;) //loop through consec. horizontal edges
{
bool IsLastHorz = (horzEdge == eLastHorz);
TEdge* e = GetNextInAEL(horzEdge, dir);
while(e)
{
//this code block inserts extra coords into horizontal edges (in output
//polygons) whereever maxima touch these horizontal edges. This helps
//'simplifying' polygons (ie if the Simplify property is set).
if (m_Maxima.size() > 0)
{
if (dir == dLeftToRight)
{
while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X)
{
if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));
maxIt++;
}
}
else
{
while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X)
{
if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));
maxRit++;
}
}
};
if ((dir == dLeftToRight && e->Curr.X > horzRight) ||
(dir == dRightToLeft && e->Curr.X < horzLeft)) break;
//Also break if we've got to the end of an intermediate horizontal edge ...
//nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.
if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML &&
e->Dx < horzEdge->NextInLML->Dx) break;
if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times
{
#ifdef use_xyz
if (dir == dLeftToRight) SetZ(e->Curr, *horzEdge, *e);
else SetZ(e->Curr, *e, *horzEdge);
#endif
op1 = AddOutPt(horzEdge, e->Curr);
TEdge* eNextHorz = m_SortedEdges;
while (eNextHorz)
{
if (eNextHorz->OutIdx >= 0 &&
HorzSegmentsOverlap(horzEdge->Bot.X,
horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
{
OutPt* op2 = GetLastOutPt(eNextHorz);
AddJoin(op2, op1, eNextHorz->Top);
}
eNextHorz = eNextHorz->NextInSEL;
}
AddGhostJoin(op1, horzEdge->Bot);
}
//OK, so far we're still in range of the horizontal Edge but make sure
//we're at the last of consec. horizontals when matching with eMaxPair
if(e == eMaxPair && IsLastHorz)
{
if (horzEdge->OutIdx >= 0)
AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top);
DeleteFromAEL(horzEdge);
DeleteFromAEL(eMaxPair);
return;
}
if(dir == dLeftToRight)
{
IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
IntersectEdges(horzEdge, e, Pt);
}
else
{
IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
IntersectEdges( e, horzEdge, Pt);
}
TEdge* eNext = GetNextInAEL(e, dir);
SwapPositionsInAEL( horzEdge, e );
e = eNext;
} //end while(e)
//Break out of loop if HorzEdge.NextInLML is not also horizontal ...
if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break;
UpdateEdgeIntoAEL(horzEdge);
if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot);
GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
} //end for (;;)
if (horzEdge->OutIdx >= 0 && !op1)
{
op1 = GetLastOutPt(horzEdge);
TEdge* eNextHorz = m_SortedEdges;
while (eNextHorz)
{
if (eNextHorz->OutIdx >= 0 &&
HorzSegmentsOverlap(horzEdge->Bot.X,
horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
{
OutPt* op2 = GetLastOutPt(eNextHorz);
AddJoin(op2, op1, eNextHorz->Top);
}
eNextHorz = eNextHorz->NextInSEL;
}
AddGhostJoin(op1, horzEdge->Top);
}
if (horzEdge->NextInLML)
{
if(horzEdge->OutIdx >= 0)
{
op1 = AddOutPt( horzEdge, horzEdge->Top);
UpdateEdgeIntoAEL(horzEdge);
if (horzEdge->WindDelta == 0) return;
//nb: HorzEdge is no longer horizontal here
TEdge* ePrev = horzEdge->PrevInAEL;
TEdge* eNext = horzEdge->NextInAEL;
if (ePrev && ePrev->Curr.X == horzEdge->Bot.X &&
ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 &&
(ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
SlopesEqual(*horzEdge, *ePrev, m_UseFullRange)))
{
OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot);
AddJoin(op1, op2, horzEdge->Top);
}
else if (eNext && eNext->Curr.X == horzEdge->Bot.X &&
eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 &&
eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
SlopesEqual(*horzEdge, *eNext, m_UseFullRange))
{
OutPt* op2 = AddOutPt(eNext, horzEdge->Bot);
AddJoin(op1, op2, horzEdge->Top);
}
}
else
UpdateEdgeIntoAEL(horzEdge);
}
else
{
if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top);
DeleteFromAEL(horzEdge);
}
}
//------------------------------------------------------------------------------
bool Clipper::ProcessIntersections(const cInt topY)
{
if( !m_ActiveEdges ) return true;
try {
BuildIntersectList(topY);
size_t IlSize = m_IntersectList.size();
if (IlSize == 0) return true;
if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList();
else return false;
}
catch(...)
{
m_SortedEdges = 0;
DisposeIntersectNodes();
throw clipperException("ProcessIntersections error");
}
m_SortedEdges = 0;
return true;
}
//------------------------------------------------------------------------------
void Clipper::DisposeIntersectNodes()
{
for (size_t i = 0; i < m_IntersectList.size(); ++i )
delete m_IntersectList[i];
m_IntersectList.clear();
}
//------------------------------------------------------------------------------
void Clipper::BuildIntersectList(const cInt topY)
{
if ( !m_ActiveEdges ) return;
//prepare for sorting ...
TEdge* e = m_ActiveEdges;
m_SortedEdges = e;
while( e )
{
e->PrevInSEL = e->PrevInAEL;
e->NextInSEL = e->NextInAEL;
e->Curr.X = TopX( *e, topY );
e = e->NextInAEL;
}
//bubblesort ...
bool isModified;
do
{
isModified = false;
e = m_SortedEdges;
while( e->NextInSEL )
{
TEdge *eNext = e->NextInSEL;
IntPoint Pt;
if(e->Curr.X > eNext->Curr.X)
{
IntersectPoint(*e, *eNext, Pt);
if (Pt.Y < topY) Pt = IntPoint(TopX(*e, topY), topY);
IntersectNode * newNode = new IntersectNode;
newNode->Edge1 = e;
newNode->Edge2 = eNext;
newNode->Pt = Pt;
m_IntersectList.push_back(newNode);
SwapPositionsInSEL(e, eNext);
isModified = true;
}
else
e = eNext;
}
if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0;
else break;
}
while ( isModified );
m_SortedEdges = 0; //important
}
//------------------------------------------------------------------------------
void Clipper::ProcessIntersectList()
{
for (size_t i = 0; i < m_IntersectList.size(); ++i)
{
IntersectNode* iNode = m_IntersectList[i];
{
IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt);
SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 );
}
delete iNode;
}
m_IntersectList.clear();
}
//------------------------------------------------------------------------------
bool IntersectListSort(IntersectNode* node1, IntersectNode* node2)
{
return node2->Pt.Y < node1->Pt.Y;
}
//------------------------------------------------------------------------------
inline bool EdgesAdjacent(const IntersectNode &inode)
{
return (inode.Edge1->NextInSEL == inode.Edge2) ||
(inode.Edge1->PrevInSEL == inode.Edge2);
}
//------------------------------------------------------------------------------
bool Clipper::FixupIntersectionOrder()
{
//pre-condition: intersections are sorted Bottom-most first.
//Now it's crucial that intersections are made only between adjacent edges,
//so to ensure this the order of intersections may need adjusting ...
CopyAELToSEL();
std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort);
size_t cnt = m_IntersectList.size();
for (size_t i = 0; i < cnt; ++i)
{
if (!EdgesAdjacent(*m_IntersectList[i]))
{
size_t j = i + 1;
while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++;
if (j == cnt) return false;
std::swap(m_IntersectList[i], m_IntersectList[j]);
}
SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2);
}
return true;
}
//------------------------------------------------------------------------------
void Clipper::DoMaxima(TEdge *e)
{
TEdge* eMaxPair = GetMaximaPairEx(e);
if (!eMaxPair)
{
if (e->OutIdx >= 0)
AddOutPt(e, e->Top);
DeleteFromAEL(e);
return;
}
TEdge* eNext = e->NextInAEL;
while(eNext && eNext != eMaxPair)
{
IntersectEdges(e, eNext, e->Top);
SwapPositionsInAEL(e, eNext);
eNext = e->NextInAEL;
}
if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned)
{
DeleteFromAEL(e);
DeleteFromAEL(eMaxPair);
}
else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
{
if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);
DeleteFromAEL(e);
DeleteFromAEL(eMaxPair);
}
#ifdef use_lines
else if (e->WindDelta == 0)
{
if (e->OutIdx >= 0)
{
AddOutPt(e, e->Top);
e->OutIdx = Unassigned;
}
DeleteFromAEL(e);
if (eMaxPair->OutIdx >= 0)
{
AddOutPt(eMaxPair, e->Top);
eMaxPair->OutIdx = Unassigned;
}
DeleteFromAEL(eMaxPair);
}
#endif
else throw clipperException("DoMaxima error");
}
//------------------------------------------------------------------------------
void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)
{
TEdge* e = m_ActiveEdges;
while( e )
{
//1. process maxima, treating them as if they're 'bent' horizontal edges,
// but exclude maxima with horizontal edges. nb: e can't be a horizontal.
bool IsMaximaEdge = IsMaxima(e, topY);
if(IsMaximaEdge)
{
TEdge* eMaxPair = GetMaximaPairEx(e);
IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair));
}
if(IsMaximaEdge)
{
if (m_StrictSimple) m_Maxima.push_back(e->Top.X);
TEdge* ePrev = e->PrevInAEL;
DoMaxima(e);
if( !ePrev ) e = m_ActiveEdges;
else e = ePrev->NextInAEL;
}
else
{
//2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...
if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML))
{
UpdateEdgeIntoAEL(e);
if (e->OutIdx >= 0)
AddOutPt(e, e->Bot);
AddEdgeToSEL(e);
}
else
{
e->Curr.X = TopX( *e, topY );
e->Curr.Y = topY;
#ifdef use_xyz
e->Curr.Z = topY == e->Top.Y ? e->Top.Z : (topY == e->Bot.Y ? e->Bot.Z : 0);
#endif
}
//When StrictlySimple and 'e' is being touched by another edge, then
//make sure both edges have a vertex here ...
if (m_StrictSimple)
{
TEdge* ePrev = e->PrevInAEL;
if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) &&
(ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0))
{
IntPoint pt = e->Curr;
#ifdef use_xyz
SetZ(pt, *ePrev, *e);
#endif
OutPt* op = AddOutPt(ePrev, pt);
OutPt* op2 = AddOutPt(e, pt);
AddJoin(op, op2, pt); //StrictlySimple (type-3) join
}
}
e = e->NextInAEL;
}
}
//3. Process horizontals at the Top of the scanbeam ...
m_Maxima.sort();
ProcessHorizontals();
m_Maxima.clear();
//4. Promote intermediate vertices ...
e = m_ActiveEdges;
while(e)
{
if(IsIntermediate(e, topY))
{
OutPt* op = 0;
if( e->OutIdx >= 0 )
op = AddOutPt(e, e->Top);
UpdateEdgeIntoAEL(e);
//if output polygons share an edge, they'll need joining later ...
TEdge* ePrev = e->PrevInAEL;
TEdge* eNext = e->NextInAEL;
if (ePrev && ePrev->Curr.X == e->Bot.X &&
ePrev->Curr.Y == e->Bot.Y && op &&
ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
SlopesEqual(e->Curr, e->Top, ePrev->Curr, ePrev->Top, m_UseFullRange) &&
(e->WindDelta != 0) && (ePrev->WindDelta != 0))
{
OutPt* op2 = AddOutPt(ePrev, e->Bot);
AddJoin(op, op2, e->Top);
}
else if (eNext && eNext->Curr.X == e->Bot.X &&
eNext->Curr.Y == e->Bot.Y && op &&
eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
SlopesEqual(e->Curr, e->Top, eNext->Curr, eNext->Top, m_UseFullRange) &&
(e->WindDelta != 0) && (eNext->WindDelta != 0))
{
OutPt* op2 = AddOutPt(eNext, e->Bot);
AddJoin(op, op2, e->Top);
}
}
e = e->NextInAEL;
}
}
//------------------------------------------------------------------------------
void Clipper::FixupOutPolyline(OutRec &outrec)
{
OutPt *pp = outrec.Pts;
OutPt *lastPP = pp->Prev;
while (pp != lastPP)
{
pp = pp->Next;
if (pp->Pt == pp->Prev->Pt)
{
if (pp == lastPP) lastPP = pp->Prev;
OutPt *tmpPP = pp->Prev;
tmpPP->Next = pp->Next;
pp->Next->Prev = tmpPP;
delete pp;
pp = tmpPP;
}
}
if (pp == pp->Prev)
{
DisposeOutPts(pp);
outrec.Pts = 0;
return;
}
}
//------------------------------------------------------------------------------
void Clipper::FixupOutPolygon(OutRec &outrec)
{
//FixupOutPolygon() - removes duplicate points and simplifies consecutive
//parallel edges by removing the middle vertex.
OutPt *lastOK = 0;
outrec.BottomPt = 0;
OutPt *pp = outrec.Pts;
bool preserveCol = m_PreserveCollinear || m_StrictSimple;
for (;;)
{
if (pp->Prev == pp || pp->Prev == pp->Next)
{
DisposeOutPts(pp);
outrec.Pts = 0;
return;
}
//test for duplicate points and collinear edges ...
if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) ||
(SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) &&
(!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt))))
{
lastOK = 0;
OutPt *tmp = pp;
pp->Prev->Next = pp->Next;
pp->Next->Prev = pp->Prev;
pp = pp->Prev;
delete tmp;
}
else if (pp == lastOK) break;
else
{
if (!lastOK) lastOK = pp;
pp = pp->Next;
}
}
outrec.Pts = pp;
}
//------------------------------------------------------------------------------
int PointCount(OutPt *Pts)
{
if (!Pts) return 0;
int result = 0;
OutPt* p = Pts;
do
{
result++;
p = p->Next;
}
while (p != Pts);
return result;
}
//------------------------------------------------------------------------------
void Clipper::BuildResult(Paths &polys)
{
polys.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
if (!m_PolyOuts[i]->Pts) continue;
Path pg;
OutPt* p = m_PolyOuts[i]->Pts->Prev;
int cnt = PointCount(p);
if (cnt < 2) continue;
pg.reserve(cnt);
for (int i = 0; i < cnt; ++i)
{
pg.push_back(p->Pt);
p = p->Prev;
}
polys.push_back(pg);
}
}
//------------------------------------------------------------------------------
void Clipper::BuildResult2(PolyTree& polytree)
{
polytree.Clear();
polytree.AllNodes.reserve(m_PolyOuts.size());
//add each output polygon/contour to polytree ...
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
{
OutRec* outRec = m_PolyOuts[i];
int cnt = PointCount(outRec->Pts);
if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue;
FixHoleLinkage(*outRec);
PolyNode* pn = new PolyNode();
//nb: polytree takes ownership of all the PolyNodes
polytree.AllNodes.push_back(pn);
outRec->PolyNd = pn;
pn->Parent = 0;
pn->Index = 0;
pn->Contour.reserve(cnt);
OutPt *op = outRec->Pts->Prev;
for (int j = 0; j < cnt; j++)
{
pn->Contour.push_back(op->Pt);
op = op->Prev;
}
}
//fixup PolyNode links etc ...
polytree.Childs.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
{
OutRec* outRec = m_PolyOuts[i];
if (!outRec->PolyNd) continue;
if (outRec->IsOpen)
{
outRec->PolyNd->m_IsOpen = true;
polytree.AddChild(*outRec->PolyNd);
}
else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd)
outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd);
else
polytree.AddChild(*outRec->PolyNd);
}
}
//------------------------------------------------------------------------------
void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2)
{
//just swap the contents (because fIntersectNodes is a single-linked-list)
IntersectNode inode = int1; //gets a copy of Int1
int1.Edge1 = int2.Edge1;
int1.Edge2 = int2.Edge2;
int1.Pt = int2.Pt;
int2.Edge1 = inode.Edge1;
int2.Edge2 = inode.Edge2;
int2.Pt = inode.Pt;
}
//------------------------------------------------------------------------------
inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2)
{
if (e2.Curr.X == e1.Curr.X)
{
if (e2.Top.Y > e1.Top.Y)
return e2.Top.X < TopX(e1, e2.Top.Y);
else return e1.Top.X > TopX(e2, e1.Top.Y);
}
else return e2.Curr.X < e1.Curr.X;
}
//------------------------------------------------------------------------------
bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2,
cInt& Left, cInt& Right)
{
if (a1 < a2)
{
if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);}
else {Left = std::max(a1,b2); Right = std::min(a2,b1);}
}
else
{
if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);}
else {Left = std::max(a2,b2); Right = std::min(a1,b1);}
}
return Left < Right;
}
//------------------------------------------------------------------------------
inline void UpdateOutPtIdxs(OutRec& outrec)
{
OutPt* op = outrec.Pts;
do
{
op->Idx = outrec.Idx;
op = op->Prev;
}
while(op != outrec.Pts);
}
//------------------------------------------------------------------------------
void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge)
{
if(!m_ActiveEdges)
{
edge->PrevInAEL = 0;
edge->NextInAEL = 0;
m_ActiveEdges = edge;
}
else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge))
{
edge->PrevInAEL = 0;
edge->NextInAEL = m_ActiveEdges;
m_ActiveEdges->PrevInAEL = edge;
m_ActiveEdges = edge;
}
else
{
if(!startEdge) startEdge = m_ActiveEdges;
while(startEdge->NextInAEL &&
!E2InsertsBeforeE1(*startEdge->NextInAEL , *edge))
startEdge = startEdge->NextInAEL;
edge->NextInAEL = startEdge->NextInAEL;
if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge;
edge->PrevInAEL = startEdge;
startEdge->NextInAEL = edge;
}
}
//----------------------------------------------------------------------
OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)
{
OutPt* result = new OutPt;
result->Pt = outPt->Pt;
result->Idx = outPt->Idx;
if (InsertAfter)
{
result->Next = outPt->Next;
result->Prev = outPt;
outPt->Next->Prev = result;
outPt->Next = result;
}
else
{
result->Prev = outPt->Prev;
result->Next = outPt;
outPt->Prev->Next = result;
outPt->Prev = result;
}
return result;
}
//------------------------------------------------------------------------------
bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,
const IntPoint Pt, bool DiscardLeft)
{
Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight);
Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight);
if (Dir1 == Dir2) return false;
//When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we
//want Op1b to be on the Right. (And likewise with Op2 and Op2b.)
//So, to facilitate this while inserting Op1b and Op2b ...
//when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,
//otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)
if (Dir1 == dLeftToRight)
{
while (op1->Next->Pt.X <= Pt.X &&
op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
op1 = op1->Next;
if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
op1b = DupOutPt(op1, !DiscardLeft);
if (op1b->Pt != Pt)
{
op1 = op1b;
op1->Pt = Pt;
op1b = DupOutPt(op1, !DiscardLeft);
}
}
else
{
while (op1->Next->Pt.X >= Pt.X &&
op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
op1 = op1->Next;
if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
op1b = DupOutPt(op1, DiscardLeft);
if (op1b->Pt != Pt)
{
op1 = op1b;
op1->Pt = Pt;
op1b = DupOutPt(op1, DiscardLeft);
}
}
if (Dir2 == dLeftToRight)
{
while (op2->Next->Pt.X <= Pt.X &&
op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
op2 = op2->Next;
if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
op2b = DupOutPt(op2, !DiscardLeft);
if (op2b->Pt != Pt)
{
op2 = op2b;
op2->Pt = Pt;
op2b = DupOutPt(op2, !DiscardLeft);
};
} else
{
while (op2->Next->Pt.X >= Pt.X &&
op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
op2 = op2->Next;
if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
op2b = DupOutPt(op2, DiscardLeft);
if (op2b->Pt != Pt)
{
op2 = op2b;
op2->Pt = Pt;
op2b = DupOutPt(op2, DiscardLeft);
};
};
if ((Dir1 == dLeftToRight) == DiscardLeft)
{
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
}
else
{
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
}
return true;
}
//------------------------------------------------------------------------------
bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)
{
OutPt *op1 = j->OutPt1, *op1b;
OutPt *op2 = j->OutPt2, *op2b;
//There are 3 kinds of joins for output polygons ...
//1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere
//along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).
//2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same
//location at the Bottom of the overlapping segment (& Join.OffPt is above).
//3. StrictSimple joins where edges touch but are not collinear and where
//Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.
bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y);
if (isHorizontal && (j->OffPt == j->OutPt1->Pt) &&
(j->OffPt == j->OutPt2->Pt))
{
//Strictly Simple join ...
if (outRec1 != outRec2) return false;
op1b = j->OutPt1->Next;
while (op1b != op1 && (op1b->Pt == j->OffPt))
op1b = op1b->Next;
bool reverse1 = (op1b->Pt.Y > j->OffPt.Y);
op2b = j->OutPt2->Next;
while (op2b != op2 && (op2b->Pt == j->OffPt))
op2b = op2b->Next;
bool reverse2 = (op2b->Pt.Y > j->OffPt.Y);
if (reverse1 == reverse2) return false;
if (reverse1)
{
op1b = DupOutPt(op1, false);
op2b = DupOutPt(op2, true);
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
} else
{
op1b = DupOutPt(op1, true);
op2b = DupOutPt(op2, false);
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
}
}
else if (isHorizontal)
{
//treat horizontal joins differently to non-horizontal joins since with
//them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt
//may be anywhere along the horizontal edge.
op1b = op1;
while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2)
op1 = op1->Prev;
while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2)
op1b = op1b->Next;
if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon'
op2b = op2;
while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b)
op2 = op2->Prev;
while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1)
op2b = op2b->Next;
if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon'
cInt Left, Right;
//Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges
if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right))
return false;
//DiscardLeftSide: when overlapping edges are joined, a spike will created
//which needs to be cleaned up. However, we don't want Op1 or Op2 caught up
//on the discard Side as either may still be needed for other joins ...
IntPoint Pt;
bool DiscardLeftSide;
if (op1->Pt.X >= Left && op1->Pt.X <= Right)
{
Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X);
}
else if (op2->Pt.X >= Left&& op2->Pt.X <= Right)
{
Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X);
}
else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right)
{
Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X;
}
else
{
Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X);
}
j->OutPt1 = op1; j->OutPt2 = op2;
return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);
} else
{
//nb: For non-horizontal joins ...
// 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y
// 2. Jr.OutPt1.Pt > Jr.OffPt.Y
//make sure the polygons are correctly oriented ...
op1b = op1->Next;
while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next;
bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) ||
!SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange));
if (Reverse1)
{
op1b = op1->Prev;
while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev;
if ((op1b->Pt.Y > op1->Pt.Y) ||
!SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false;
};
op2b = op2->Next;
while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next;
bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) ||
!SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange));
if (Reverse2)
{
op2b = op2->Prev;
while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev;
if ((op2b->Pt.Y > op2->Pt.Y) ||
!SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false;
}
if ((op1b == op1) || (op2b == op2) || (op1b == op2b) ||
((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false;
if (Reverse1)
{
op1b = DupOutPt(op1, false);
op2b = DupOutPt(op2, true);
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
} else
{
op1b = DupOutPt(op1, true);
op2b = DupOutPt(op2, false);
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
}
}
}
//----------------------------------------------------------------------
static OutRec* ParseFirstLeft(OutRec* FirstLeft)
{
while (FirstLeft && !FirstLeft->Pts)
FirstLeft = FirstLeft->FirstLeft;
return FirstLeft;
}
//------------------------------------------------------------------------------
void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec)
{
//tests if NewOutRec contains the polygon before reassigning FirstLeft
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (outRec->Pts && firstLeft == OldOutRec)
{
if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts))
outRec->FirstLeft = NewOutRec;
}
}
}
//----------------------------------------------------------------------
void Clipper::FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec)
{
//A polygon has split into two such that one is now the inner of the other.
//It's possible that these polygons now wrap around other polygons, so check
//every polygon that's also contained by OuterOutRec's FirstLeft container
//(including 0) to see if they've become inner to the new inner polygon ...
OutRec* orfl = OuterOutRec->FirstLeft;
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
if (!outRec->Pts || outRec == OuterOutRec || outRec == InnerOutRec)
continue;
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (firstLeft != orfl && firstLeft != InnerOutRec && firstLeft != OuterOutRec)
continue;
if (Poly2ContainsPoly1(outRec->Pts, InnerOutRec->Pts))
outRec->FirstLeft = InnerOutRec;
else if (Poly2ContainsPoly1(outRec->Pts, OuterOutRec->Pts))
outRec->FirstLeft = OuterOutRec;
else if (outRec->FirstLeft == InnerOutRec || outRec->FirstLeft == OuterOutRec)
outRec->FirstLeft = orfl;
}
}
//----------------------------------------------------------------------
void Clipper::FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec)
{
//reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (outRec->Pts && firstLeft == OldOutRec)
outRec->FirstLeft = NewOutRec;
}
}
//----------------------------------------------------------------------
void Clipper::JoinCommonEdges()
{
for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
{
Join* join = m_Joins[i];
OutRec *outRec1 = GetOutRec(join->OutPt1->Idx);
OutRec *outRec2 = GetOutRec(join->OutPt2->Idx);
if (!outRec1->Pts || !outRec2->Pts) continue;
if (outRec1->IsOpen || outRec2->IsOpen) continue;
//get the polygon fragment with the correct hole state (FirstLeft)
//before calling JoinPoints() ...
OutRec *holeStateRec;
if (outRec1 == outRec2) holeStateRec = outRec1;
else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2;
else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1;
else holeStateRec = GetLowermostRec(outRec1, outRec2);
if (!JoinPoints(join, outRec1, outRec2)) continue;
if (outRec1 == outRec2)
{
//instead of joining two polygons, we've just created a new one by
//splitting one polygon into two.
outRec1->Pts = join->OutPt1;
outRec1->BottomPt = 0;
outRec2 = CreateOutRec();
outRec2->Pts = join->OutPt2;
//update all OutRec2.Pts Idx's ...
UpdateOutPtIdxs(*outRec2);
if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts))
{
//outRec1 contains outRec2 ...
outRec2->IsHole = !outRec1->IsHole;
outRec2->FirstLeft = outRec1;
if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0))
ReversePolyPtLinks(outRec2->Pts);
} else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts))
{
//outRec2 contains outRec1 ...
outRec2->IsHole = outRec1->IsHole;
outRec1->IsHole = !outRec2->IsHole;
outRec2->FirstLeft = outRec1->FirstLeft;
outRec1->FirstLeft = outRec2;
if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2);
if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0))
ReversePolyPtLinks(outRec1->Pts);
}
else
{
//the 2 polygons are completely separate ...
outRec2->IsHole = outRec1->IsHole;
outRec2->FirstLeft = outRec1->FirstLeft;
//fixup FirstLeft pointers that may need reassigning to OutRec2
if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2);
}
} else
{
//joined 2 polygons together ...
outRec2->Pts = 0;
outRec2->BottomPt = 0;
outRec2->Idx = outRec1->Idx;
outRec1->IsHole = holeStateRec->IsHole;
if (holeStateRec == outRec2)
outRec1->FirstLeft = outRec2->FirstLeft;
outRec2->FirstLeft = outRec1;
if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1);
}
}
}
//------------------------------------------------------------------------------
// ClipperOffset support functions ...
//------------------------------------------------------------------------------
DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2)
{
if(pt2.X == pt1.X && pt2.Y == pt1.Y)
return DoublePoint(0, 0);
double Dx = (double)(pt2.X - pt1.X);
double dy = (double)(pt2.Y - pt1.Y);
double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy );
Dx *= f;
dy *= f;
return DoublePoint(dy, -Dx);
}
//------------------------------------------------------------------------------
// ClipperOffset class
//------------------------------------------------------------------------------
ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)
{
this->MiterLimit = miterLimit;
this->ArcTolerance = arcTolerance;
m_lowest.X = -1;
}
//------------------------------------------------------------------------------
ClipperOffset::~ClipperOffset()
{
Clear();
}
//------------------------------------------------------------------------------
void ClipperOffset::Clear()
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
delete m_polyNodes.Childs[i];
m_polyNodes.Childs.clear();
m_lowest.X = -1;
}
//------------------------------------------------------------------------------
void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType)
{
int highI = (int)path.size() - 1;
if (highI < 0) return;
PolyNode* newNode = new PolyNode();
newNode->m_jointype = joinType;
newNode->m_endtype = endType;
//strip duplicate points from path and also get index to the lowest point ...
if (endType == etClosedLine || endType == etClosedPolygon)
while (highI > 0 && path[0] == path[highI]) highI--;
newNode->Contour.reserve(highI + 1);
newNode->Contour.push_back(path[0]);
int j = 0, k = 0;
for (int i = 1; i <= highI; i++)
if (newNode->Contour[j] != path[i])
{
j++;
newNode->Contour.push_back(path[i]);
if (path[i].Y > newNode->Contour[k].Y ||
(path[i].Y == newNode->Contour[k].Y &&
path[i].X < newNode->Contour[k].X)) k = j;
}
if (endType == etClosedPolygon && j < 2)
{
delete newNode;
return;
}
m_polyNodes.AddChild(*newNode);
//if this path's lowest pt is lower than all the others then update m_lowest
if (endType != etClosedPolygon) return;
if (m_lowest.X < 0)
m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
else
{
IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y];
if (newNode->Contour[k].Y > ip.Y ||
(newNode->Contour[k].Y == ip.Y &&
newNode->Contour[k].X < ip.X))
m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
}
}
//------------------------------------------------------------------------------
void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType)
{
for (Paths::size_type i = 0; i < paths.size(); ++i)
AddPath(paths[i], joinType, endType);
}
//------------------------------------------------------------------------------
void ClipperOffset::FixOrientations()
{
//fixup orientations of all closed paths if the orientation of the
//closed path with the lowermost vertex is wrong ...
if (m_lowest.X >= 0 &&
!Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour))
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedPolygon ||
(node.m_endtype == etClosedLine && Orientation(node.Contour)))
ReversePath(node.Contour);
}
} else
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedLine && !Orientation(node.Contour))
ReversePath(node.Contour);
}
}
}
//------------------------------------------------------------------------------
void ClipperOffset::Execute(Paths& solution, double delta)
{
solution.clear();
FixOrientations();
DoOffset(delta);
//now clean up 'corners' ...
Clipper clpr;
clpr.AddPaths(m_destPolys, ptSubject, true);
if (delta > 0)
{
clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
}
else
{
IntRect r = clpr.GetBounds();
Path outer(4);
outer[0] = IntPoint(r.left - 10, r.bottom + 10);
outer[1] = IntPoint(r.right + 10, r.bottom + 10);
outer[2] = IntPoint(r.right + 10, r.top - 10);
outer[3] = IntPoint(r.left - 10, r.top - 10);
clpr.AddPath(outer, ptSubject, true);
clpr.ReverseSolution(true);
clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
if (solution.size() > 0) solution.erase(solution.begin());
}
}
//------------------------------------------------------------------------------
void ClipperOffset::Execute(PolyTree& solution, double delta)
{
solution.Clear();
FixOrientations();
DoOffset(delta);
//now clean up 'corners' ...
Clipper clpr;
clpr.AddPaths(m_destPolys, ptSubject, true);
if (delta > 0)
{
clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
}
else
{
IntRect r = clpr.GetBounds();
Path outer(4);
outer[0] = IntPoint(r.left - 10, r.bottom + 10);
outer[1] = IntPoint(r.right + 10, r.bottom + 10);
outer[2] = IntPoint(r.right + 10, r.top - 10);
outer[3] = IntPoint(r.left - 10, r.top - 10);
clpr.AddPath(outer, ptSubject, true);
clpr.ReverseSolution(true);
clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
//remove the outer PolyNode rectangle ...
if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0)
{
PolyNode* outerNode = solution.Childs[0];
solution.Childs.reserve(outerNode->ChildCount());
solution.Childs[0] = outerNode->Childs[0];
solution.Childs[0]->Parent = outerNode->Parent;
for (int i = 1; i < outerNode->ChildCount(); ++i)
solution.AddChild(*outerNode->Childs[i]);
}
else
solution.Clear();
}
}
//------------------------------------------------------------------------------
void ClipperOffset::DoOffset(double delta)
{
m_destPolys.clear();
m_delta = delta;
//if Zero offset, just copy any CLOSED polygons to m_p and return ...
if (NEAR_ZERO(delta))
{
m_destPolys.reserve(m_polyNodes.ChildCount());
for (int i = 0; i < m_polyNodes.ChildCount(); i++)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedPolygon)
m_destPolys.push_back(node.Contour);
}
return;
}
//see offset_triginometry3.svg in the documentation folder ...
if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit);
else m_miterLim = 0.5;
double y;
if (ArcTolerance <= 0.0) y = def_arc_tolerance;
else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance)
y = std::fabs(delta) * def_arc_tolerance;
else y = ArcTolerance;
//see offset_triginometry2.svg in the documentation folder ...
double steps = pi / std::acos(1 - y / std::fabs(delta));
if (steps > std::fabs(delta) * pi)
steps = std::fabs(delta) * pi; //ie excessive precision check
m_sin = std::sin(two_pi / steps);
m_cos = std::cos(two_pi / steps);
m_StepsPerRad = steps / two_pi;
if (delta < 0.0) m_sin = -m_sin;
m_destPolys.reserve(m_polyNodes.ChildCount() * 2);
for (int i = 0; i < m_polyNodes.ChildCount(); i++)
{
PolyNode& node = *m_polyNodes.Childs[i];
m_srcPoly = node.Contour;
int len = (int)m_srcPoly.size();
if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon)))
continue;
m_destPoly.clear();
if (len == 1)
{
if (node.m_jointype == jtRound)
{
double X = 1.0, Y = 0.0;
for (cInt j = 1; j <= steps; j++)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[0].X + X * delta),
Round(m_srcPoly[0].Y + Y * delta)));
double X2 = X;
X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos;
}
}
else
{
double X = -1.0, Y = -1.0;
for (int j = 0; j < 4; ++j)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[0].X + X * delta),
Round(m_srcPoly[0].Y + Y * delta)));
if (X < 0) X = 1;
else if (Y < 0) Y = 1;
else X = -1;
}
}
m_destPolys.push_back(m_destPoly);
continue;
}
//build m_normals ...
m_normals.clear();
m_normals.reserve(len);
for (int j = 0; j < len - 1; ++j)
m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1]));
if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon)
m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0]));
else
m_normals.push_back(DoublePoint(m_normals[len - 2]));
if (node.m_endtype == etClosedPolygon)
{
int k = len - 1;
for (int j = 0; j < len; ++j)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
}
else if (node.m_endtype == etClosedLine)
{
int k = len - 1;
for (int j = 0; j < len; ++j)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
m_destPoly.clear();
//re-build m_normals ...
DoublePoint n = m_normals[len -1];
for (int j = len - 1; j > 0; j--)
m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
m_normals[0] = DoublePoint(-n.X, -n.Y);
k = 0;
for (int j = len - 1; j >= 0; j--)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
}
else
{
int k = 0;
for (int j = 1; j < len - 1; ++j)
OffsetPoint(j, k, node.m_jointype);
IntPoint pt1;
if (node.m_endtype == etOpenButt)
{
int j = len - 1;
pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X *
delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta));
m_destPoly.push_back(pt1);
pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X *
delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta));
m_destPoly.push_back(pt1);
}
else
{
int j = len - 1;
k = len - 2;
m_sinA = 0;
m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y);
if (node.m_endtype == etOpenSquare)
DoSquare(j, k);
else
DoRound(j, k);
}
//re-build m_normals ...
for (int j = len - 1; j > 0; j--)
m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y);
k = len - 1;
for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype);
if (node.m_endtype == etOpenButt)
{
pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta),
(cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta));
m_destPoly.push_back(pt1);
pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta),
(cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta));
m_destPoly.push_back(pt1);
}
else
{
k = 1;
m_sinA = 0;
if (node.m_endtype == etOpenSquare)
DoSquare(0, 1);
else
DoRound(0, 1);
}
m_destPolys.push_back(m_destPoly);
}
}
}
//------------------------------------------------------------------------------
void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype)
{
//cross product ...
m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y);
if (std::fabs(m_sinA * m_delta) < 1.0)
{
//dot product ...
double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y );
if (cosA > 0) // angle => 0 degrees
{
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
return;
}
//else angle => 180 degrees
}
else if (m_sinA > 1.0) m_sinA = 1.0;
else if (m_sinA < -1.0) m_sinA = -1.0;
if (m_sinA * m_delta < 0)
{
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
m_destPoly.push_back(m_srcPoly[j]);
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
}
else
switch (jointype)
{
case jtMiter:
{
double r = 1 + (m_normals[j].X * m_normals[k].X +
m_normals[j].Y * m_normals[k].Y);
if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k);
break;
}
case jtSquare: DoSquare(j, k); break;
case jtRound: DoRound(j, k); break;
}
k = j;
}
//------------------------------------------------------------------------------
void ClipperOffset::DoSquare(int j, int k)
{
double dx = std::tan(std::atan2(m_sinA,
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4);
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)),
Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))));
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)),
Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx))));
}
//------------------------------------------------------------------------------
void ClipperOffset::DoMiter(int j, int k, double r)
{
double q = m_delta / r;
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q),
Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q)));
}
//------------------------------------------------------------------------------
void ClipperOffset::DoRound(int j, int k)
{
double a = std::atan2(m_sinA,
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);
int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);
double X = m_normals[k].X, Y = m_normals[k].Y, X2;
for (int i = 0; i < steps; ++i)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + X * m_delta),
Round(m_srcPoly[j].Y + Y * m_delta)));
X2 = X;
X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos;
}
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
}
//------------------------------------------------------------------------------
// Miscellaneous public functions
//------------------------------------------------------------------------------
void Clipper::DoSimplePolygons()
{
PolyOutList::size_type i = 0;
while (i < m_PolyOuts.size())
{
OutRec* outrec = m_PolyOuts[i++];
OutPt* op = outrec->Pts;
if (!op || outrec->IsOpen) continue;
do //for each Pt in Polygon until duplicate found do ...
{
OutPt* op2 = op->Next;
while (op2 != outrec->Pts)
{
if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op)
{
//split the polygon into two ...
OutPt* op3 = op->Prev;
OutPt* op4 = op2->Prev;
op->Prev = op4;
op4->Next = op;
op2->Prev = op3;
op3->Next = op2;
outrec->Pts = op;
OutRec* outrec2 = CreateOutRec();
outrec2->Pts = op2;
UpdateOutPtIdxs(*outrec2);
if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts))
{
//OutRec2 is contained by OutRec1 ...
outrec2->IsHole = !outrec->IsHole;
outrec2->FirstLeft = outrec;
if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec);
}
else
if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts))
{
//OutRec1 is contained by OutRec2 ...
outrec2->IsHole = outrec->IsHole;
outrec->IsHole = !outrec2->IsHole;
outrec2->FirstLeft = outrec->FirstLeft;
outrec->FirstLeft = outrec2;
if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2);
}
else
{
//the 2 polygons are separate ...
outrec2->IsHole = outrec->IsHole;
outrec2->FirstLeft = outrec->FirstLeft;
if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2);
}
op2 = op; //ie get ready for the Next iteration
}
op2 = op2->Next;
}
op = op->Next;
}
while (op != outrec->Pts);
}
}
//------------------------------------------------------------------------------
void ReversePath(Path& p)
{
std::reverse(p.begin(), p.end());
}
//------------------------------------------------------------------------------
void ReversePaths(Paths& p)
{
for (Paths::size_type i = 0; i < p.size(); ++i)
ReversePath(p[i]);
}
//------------------------------------------------------------------------------
void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType)
{
Clipper c;
c.StrictlySimple(true);
c.AddPath(in_poly, ptSubject, true);
c.Execute(ctUnion, out_polys, fillType, fillType);
}
//------------------------------------------------------------------------------
void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType)
{
Clipper c;
c.StrictlySimple(true);
c.AddPaths(in_polys, ptSubject, true);
c.Execute(ctUnion, out_polys, fillType, fillType);
}
//------------------------------------------------------------------------------
void SimplifyPolygons(Paths &polys, PolyFillType fillType)
{
SimplifyPolygons(polys, polys, fillType);
}
//------------------------------------------------------------------------------
inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)
{
double Dx = ((double)pt1.X - pt2.X);
double dy = ((double)pt1.Y - pt2.Y);
return (Dx*Dx + dy*dy);
}
//------------------------------------------------------------------------------
double DistanceFromLineSqrd(
const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2)
{
//The equation of a line in general form (Ax + By + C = 0)
//given 2 points (x?y? & (x?y? is ...
//(y?- y?x + (x?- x?y + (y?- y?x?- (x?- x?y?= 0
//A = (y?- y?; B = (x?- x?; C = (y?- y?x?- (x?- x?y?
//perpendicular distance of point (x?y? = (Ax?+ By?+ C)/Sqrt(A?+ B?
//see http://en.wikipedia.org/wiki/Perpendicular_distance
double A = double(ln1.Y - ln2.Y);
double B = double(ln2.X - ln1.X);
double C = A * ln1.X + B * ln1.Y;
C = A * pt.X + B * pt.Y - C;
return (C * C) / (A * A + B * B);
}
//---------------------------------------------------------------------------
bool SlopesNearCollinear(const IntPoint& pt1,
const IntPoint& pt2, const IntPoint& pt3, double distSqrd)
{
//this function is more accurate when the point that's geometrically
//between the other 2 points is the one that's tested for distance.
//ie makes it more likely to pick up 'spikes' ...
if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y))
{
if ((pt1.X > pt2.X) == (pt1.X < pt3.X))
return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
else if ((pt2.X > pt1.X) == (pt2.X < pt3.X))
return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
else
return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
}
else
{
if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y))
return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y))
return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
else
return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
}
}
//------------------------------------------------------------------------------
bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd)
{
double Dx = (double)pt1.X - pt2.X;
double dy = (double)pt1.Y - pt2.Y;
return ((Dx * Dx) + (dy * dy) <= distSqrd);
}
//------------------------------------------------------------------------------
OutPt* ExcludeOp(OutPt* op)
{
OutPt* result = op->Prev;
result->Next = op->Next;
op->Next->Prev = result;
result->Idx = 0;
return result;
}
//------------------------------------------------------------------------------
void CleanPolygon(const Path& in_poly, Path& out_poly, double distance)
{
//distance = proximity in units/pixels below which vertices
//will be stripped. Default ~= sqrt(2).
size_t size = in_poly.size();
if (size == 0)
{
out_poly.clear();
return;
}
OutPt* outPts = new OutPt[size];
for (size_t i = 0; i < size; ++i)
{
outPts[i].Pt = in_poly[i];
outPts[i].Next = &outPts[(i + 1) % size];
outPts[i].Next->Prev = &outPts[i];
outPts[i].Idx = 0;
}
double distSqrd = distance * distance;
OutPt* op = &outPts[0];
while (op->Idx == 0 && op->Next != op->Prev)
{
if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd))
{
op = ExcludeOp(op);
size--;
}
else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd))
{
ExcludeOp(op->Next);
op = ExcludeOp(op);
size -= 2;
}
else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd))
{
op = ExcludeOp(op);
size--;
}
else
{
op->Idx = 1;
op = op->Next;
}
}
if (size < 3) size = 0;
out_poly.resize(size);
for (size_t i = 0; i < size; ++i)
{
out_poly[i] = op->Pt;
op = op->Next;
}
delete [] outPts;
}
//------------------------------------------------------------------------------
void CleanPolygon(Path& poly, double distance)
{
CleanPolygon(poly, poly, distance);
}
//------------------------------------------------------------------------------
void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance)
{
out_polys.resize(in_polys.size());
for (Paths::size_type i = 0; i < in_polys.size(); ++i)
CleanPolygon(in_polys[i], out_polys[i], distance);
}
//------------------------------------------------------------------------------
void CleanPolygons(Paths& polys, double distance)
{
CleanPolygons(polys, polys, distance);
}
//------------------------------------------------------------------------------
void Minkowski(const Path& poly, const Path& path,
Paths& solution, bool isSum, bool isClosed)
{
int delta = (isClosed ? 1 : 0);
size_t polyCnt = poly.size();
size_t pathCnt = path.size();
Paths pp;
pp.reserve(pathCnt);
if (isSum)
for (size_t i = 0; i < pathCnt; ++i)
{
Path p;
p.reserve(polyCnt);
for (size_t j = 0; j < poly.size(); ++j)
p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y));
pp.push_back(p);
}
else
for (size_t i = 0; i < pathCnt; ++i)
{
Path p;
p.reserve(polyCnt);
for (size_t j = 0; j < poly.size(); ++j)
p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y));
pp.push_back(p);
}
solution.clear();
solution.reserve((pathCnt + delta) * (polyCnt + 1));
for (size_t i = 0; i < pathCnt - 1 + delta; ++i)
for (size_t j = 0; j < polyCnt; ++j)
{
Path quad;
quad.reserve(4);
quad.push_back(pp[i % pathCnt][j % polyCnt]);
quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]);
quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]);
quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]);
if (!Orientation(quad)) ReversePath(quad);
solution.push_back(quad);
}
}
//------------------------------------------------------------------------------
void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed)
{
Minkowski(pattern, path, solution, true, pathIsClosed);
Clipper c;
c.AddPaths(solution, ptSubject, true);
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
void TranslatePath(const Path& input, Path& output, const IntPoint delta)
{
//precondition: input != output
output.resize(input.size());
for (size_t i = 0; i < input.size(); ++i)
output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y);
}
//------------------------------------------------------------------------------
void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed)
{
Clipper c;
for (size_t i = 0; i < paths.size(); ++i)
{
Paths tmp;
Minkowski(pattern, paths[i], tmp, true, pathIsClosed);
c.AddPaths(tmp, ptSubject, true);
if (pathIsClosed)
{
Path tmp2;
TranslatePath(paths[i], tmp2, pattern[0]);
c.AddPath(tmp2, ptClip, true);
}
}
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution)
{
Minkowski(poly1, poly2, solution, false, true);
Clipper c;
c.AddPaths(solution, ptSubject, true);
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
enum NodeType {ntAny, ntOpen, ntClosed};
void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths)
{
bool match = true;
if (nodetype == ntClosed) match = !polynode.IsOpen();
else if (nodetype == ntOpen) return;
if (!polynode.Contour.empty() && match)
paths.push_back(polynode.Contour);
for (int i = 0; i < polynode.ChildCount(); ++i)
AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths);
}
//------------------------------------------------------------------------------
void PolyTreeToPaths(const PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
AddPolyNodeToPaths(polytree, ntAny, paths);
}
//------------------------------------------------------------------------------
void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
AddPolyNodeToPaths(polytree, ntClosed, paths);
}
//------------------------------------------------------------------------------
void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
//Open paths are top level only, so ...
for (int i = 0; i < polytree.ChildCount(); ++i)
if (polytree.Childs[i]->IsOpen())
paths.push_back(polytree.Childs[i]->Contour);
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const IntPoint &p)
{
s << "(" << p.X << "," << p.Y << ")";
return s;
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const Path &p)
{
if (p.empty()) return s;
Path::size_type last = p.size() -1;
for (Path::size_type i = 0; i < last; i++)
s << "(" << p[i].X << "," << p[i].Y << "), ";
s << "(" << p[last].X << "," << p[last].Y << ")\n";
return s;
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const Paths &p)
{
for (Paths::size_type i = 0; i < p.size(); i++)
s << p[i];
s << "\n";
return s;
}
//------------------------------------------------------------------------------
} //ClipperLib namespace
| lymastee/gslib | ext/clipper/clipper.cpp | C++ | mit | 137,526 |
module AttrValidator
# Copied from here https://github.com/rails/rails/blob/master/activesupport/lib/active_support/concern.rb
#
# A typical module looks like this:
#
# module M
# def self.included(base)
# base.extend ClassMethods
# base.class_eval do
# scope :disabled, -> { where(disabled: true) }
# end
# end
#
# module ClassMethods
# ...
# end
# end
#
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be
# written as:
#
# require 'active_support/concern'
#
# module M
# extend ActiveSupport::Concern
#
# included do
# scope :disabled, -> { where(disabled: true) }
# end
#
# module ClassMethods
# ...
# end
# end
#
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module
# and a +Bar+ module which depends on the former, we would typically write the
# following:
#
# module Foo
# def self.included(base)
# base.class_eval do
# def self.method_injected_by_foo
# ...
# end
# end
# end
# end
#
# module Bar
# def self.included(base)
# base.method_injected_by_foo
# end
# end
#
# class Host
# include Foo # We need to include this dependency for Bar
# include Bar # Bar is the module that Host really needs
# end
#
# But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We
# could try to hide these from +Host+ directly including +Foo+ in +Bar+:
#
# module Bar
# include Foo
# def self.included(base)
# base.method_injected_by_foo
# end
# end
#
# class Host
# include Bar
# end
#
# Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt>
# is the +Bar+ module, not the +Host+ class. With <tt>ActiveSupport::Concern</tt>,
# module dependencies are properly resolved:
#
# require 'active_support/concern'
#
# module Foo
# extend ActiveSupport::Concern
# included do
# def self.method_injected_by_foo
# ...
# end
# end
# end
#
# module Bar
# extend ActiveSupport::Concern
# include Foo
#
# included do
# self.method_injected_by_foo
# end
# end
#
# class Host
# include Bar # works, Bar takes care now of its dependencies
# end
module Concern
class MultipleIncludedBlocks < StandardError #:nodoc:
def initialize
super "Cannot define multiple 'included' blocks for a Concern"
end
end
def self.extended(base) #:nodoc:
base.instance_variable_set(:@_dependencies, [])
end
def append_features(base)
if base.instance_variable_defined?(:@_dependencies)
base.instance_variable_get(:@_dependencies) << self
return false
else
return false if base < self
@_dependencies.each { |dep| base.send(:include, dep) }
super
base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods)
base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block)
end
end
def included(base = nil, &block)
if base.nil?
raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block)
@_included_block = block
else
super
end
end
end
end
| AlbertGazizov/attr_validator | lib/attr_validator/concern.rb | Ruby | mit | 3,476 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace TimeOut
{
public partial class partido : Form
{
Team local; // Equipo local
Team visitor; // Equipo visitante
List<Registro> minuteToMinute = new List<Registro>();
Counter count = new Counter();
// Constante que guarda la cantidad limite
// de faltas permitidas previo a la expulsión
const int maxFaltas = 6;
/*
* Hay dos largos procesos en un partido,
* suceden cuando hay Falta o cuando hay Balon Afuera.
*/
bool procesoFalta = false;
bool procesoBalonAfuera = false;
bool localTeamShoot = false;
// Cantidad de tiros libres a tirar tras la falta
int tirosLibresDisponibles = 0;
// This will be checked in the close event,
// avoiding unnintentional actions and lose of data.
bool closeWindow = false;
// Clase para guardar el registro completo del partido
Match partidoJugado;
// Archivo para guardar el registro del partido
string archivoPartidos = "";
public string ArchivoPartidos
{
get { return archivoPartidos; }
set { archivoPartidos = value; }
}
/// <summary>
/// El constructor de la clase.
/// </summary>
/// <param name="a">Equipo local</param>
/// <param name="b">Equipo visitante</param>
public partido(Team a, Team b)
{
InitializeComponent();
local = a;
visitor = b;
if (a != null && b != null) {
actualizarListbox();
this.label_tituloLocal.Text = local.Name;
this.label_tituloVisitante.Text = visitor.Name;
this.label_LTO_restante.Text = Team.TOmax.ToString();
this.label_VTO_restante.Text = Team.TOmax.ToString();
}
}
public void actualizarListbox()
{
cargarTitulares();
cargarVisitantes();
}
void cargarTitulares()
{
listBox_LocalRoster.Items.Clear();
comboBox_LocalSubs.Items.Clear();
foreach (Player p in this.local.Players) {
if (p.Starter)
listBox_LocalRoster.Items.Add(p);
else
comboBox_LocalSubs.Items.Add(p);
}
listBox_LocalRoster.DisplayMember = "CompleteName";
comboBox_LocalSubs.DisplayMember = "CompleteName";
}
void cargarVisitantes()
{
listBox_VisitorRoster.Items.Clear();
comboBox_VisitorSubs.Items.Clear();
foreach (Player p in this.visitor.Players) {
if (p.Starter)
listBox_VisitorRoster.Items.Add(p);
else
comboBox_VisitorSubs.Items.Add(p);
}
listBox_VisitorRoster.DisplayMember = "CompleteName";
comboBox_VisitorSubs.DisplayMember = "CompleteName";
}
/// <summary>
/// Agrega un partido en una lista generica.
/// </summary>
/// <param name="equipo">Partido que sera agregado a la lista.</param>
/// <param name="listaEquipos">Lista que tiene el resto de los partidos</param>
/// <returns>La misma lista con el partido agregado</returns>
List<Match> addMatchToList(Match partido, List<Match> listaPartidos)
{
if (listaPartidos == null)
listaPartidos = new List<Match>();
listaPartidos.Add(partido);
return listaPartidos;
}
/// <summary>
/// Guarda el partido y su información en el archivo
/// </summary>
void guardarPartidoEnArchivo()
{
// Load previous matchs from file
List<Match> listaDePartidos = Main.CargarPartidos();
// Add the new match to the list
listaDePartidos = addMatchToList(this.partidoJugado, listaDePartidos);
// Store the updated list to the file
StreamWriter flujo = new StreamWriter(this.archivoPartidos);
XmlSerializer serial = new XmlSerializer(typeof(List<Match>));
serial.Serialize(flujo, listaDePartidos);
flujo.Close();
}
/// <summary>
/// Guarda las estadísticas recogidas durante el partido.
/// </summary>
void guardarInformación()
{
// Crea la lista
this.partidoJugado = new Match();
// Add match's metadata
partidoJugado.Fecha = DateTime.Now;
partidoJugado.EquipoLocal = local.Name;
partidoJugado.EquipoVisitante = visitor.Name;
// Agrega los nombres de TODOS los jugadores
// y sus respectivas estadísticas
foreach(Player p in local.Players)
{
partidoJugado.JugadoresLocales.Add(p.CompleteName);
// Agrega las estadísticas sumandolas a las actuales
partidoJugado.EstadisticasLocal.Asistencias += p.AsistenciasLogradas;
partidoJugado.EstadisticasLocal.SimplesEncestados += p.TirosLibresAnotados;
partidoJugado.EstadisticasLocal.SimplesFallidos += p.TirosLibresFallados;
partidoJugado.EstadisticasLocal.DoblesEncestados += p.PuntosDoblesAnotados;
partidoJugado.EstadisticasLocal.DoblesFallidos += p.PuntosDoblesFallados;
partidoJugado.EstadisticasLocal.TriplesEncestados += p.PuntosTriplesAnotados;
partidoJugado.EstadisticasLocal.TriplesFallidos += p.PuntosTriplesFallados;
partidoJugado.EstadisticasLocal.RebotesDefensivos += p.RebotesDefensivos;
partidoJugado.EstadisticasLocal.RebotesOfensivos += p.RebotesOfensivos;
partidoJugado.EstadisticasLocal.Faltas += p.FaltasCometidas;
}
foreach(Player p in visitor.Players)
{
partidoJugado.JugadoresVisitantes.Add(p.CompleteName);
// Agrega las estadísticas sumandolas a las actuales
partidoJugado.EstadisticasVisitante.Asistencias += p.AsistenciasLogradas;
partidoJugado.EstadisticasVisitante.SimplesEncestados += p.TirosLibresAnotados;
partidoJugado.EstadisticasVisitante.SimplesFallidos += p.TirosLibresFallados;
partidoJugado.EstadisticasVisitante.DoblesEncestados += p.PuntosDoblesAnotados;
partidoJugado.EstadisticasVisitante.DoblesFallidos += p.PuntosDoblesFallados;
partidoJugado.EstadisticasVisitante.TriplesEncestados += p.PuntosTriplesAnotados;
partidoJugado.EstadisticasVisitante.TriplesFallidos += p.PuntosTriplesFallados;
partidoJugado.EstadisticasVisitante.RebotesDefensivos += p.RebotesDefensivos;
partidoJugado.EstadisticasVisitante.RebotesOfensivos += p.RebotesOfensivos;
partidoJugado.EstadisticasVisitante.Faltas += p.FaltasCometidas;
}
guardarPartidoEnArchivo();
}
/// <summary>
/// Activa el botón de Comienzo del partido
/// </summary>
void activarContinuacion()
{
timer1.Stop();
button1.Text = "Comenzar";
button1.Enabled = true;
this.button1.BackColor = Color.DeepSkyBlue;
}
/// <summary>
/// Congela/detiene el reloj del partido y desactiva el botón de Comienzo
/// </summary>
void congelarContinuacion()
{
timer1.Stop();
button1.Text = "Parado";
button1.Enabled = false;
this.button1.BackColor = Color.Red;
}
/// <summary>
/// Pone el reloj a correr y desactiva el botón
/// </summary>
void correrContinuacion()
{
timer1.Enabled = true;
button1.Text = "Pausar";
button1.Enabled = true;
this.button1.BackColor = Color.Red;
}
/// <summary>
/// Evento llamado cuando finaliza el encuentro.
/// </summary>
void finishMatch()
{
timer1.Stop();
button1.Text = "Finalizado";
button1.Enabled = false;
button1.BackColor = Color.Black;
// Almacena la información recolectada del encuentro
guardarInformación();
// Display a minute-to-minute chart
ShowEvents nuevo = new ShowEvents(this.minuteToMinute);
nuevo.ShowDialog();
// Desactiva la pregunta al salir
closeWindow = true;
this.Close();
}
/// <summary>
/// Cambia el contexto de la ventana deacuerdo al momento correspondiente
/// </summary>
void finalizarCuarto()
{
count.resetCounter();
activarContinuacion();
// Restablece los tiempos muertos
this.local.restartTO();
this.visitor.restartTO();
// Desactiva botones no disponibles
desactivarCambio();
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarRebotes();
if (this.lblCuarto.Text[0] == '1')
this.lblCuarto.Text = "2do Cuarto";
else if (this.lblCuarto.Text[0] == '2')
this.lblCuarto.Text = "3er Cuarto";
else if (this.lblCuarto.Text[0] == '3')
this.lblCuarto.Text = "4to Cuarto";
else
finishMatch();
}
private void timer1_Tick(object sender, EventArgs e)
{
count.decCounter();
this.label_timer.Text = count.getCounter;
if (count.getCounter == "00:00:00")
finalizarCuarto();
}
#region Activar y Desactivar botones y labels
#region Desactivar y Activar puntos
void desactivarDoblesLocal()
{
btn_dobleEncestado_L.Enabled = false;
btn_dobleErrado_L.Enabled = false;
}
void desactivarDoblesVisitante()
{
btn_dobleEncestado_V.Enabled = false;
btn_dobleErrado_V.Enabled = false;
}
void desactivarTriplesLocal()
{
btn_tripleEncestado_L.Enabled = false;
btn_tripleErrado_L.Enabled = false;
}
void desactivarTriplesVisitante()
{
btn_tripleEncestado_V.Enabled = false;
btn_tripleErrado_V.Enabled = false;
}
void desactivarPuntos()
{
desactivarDoblesLocal();
desactivarDoblesVisitante();
desactivarTriplesLocal();
desactivarTriplesVisitante();
}
void activarDoblesLocal()
{
btn_dobleEncestado_L.Enabled = true;
btn_dobleErrado_L.Enabled = true;
}
void activarDoblesVisitante()
{
btn_dobleEncestado_V.Enabled = true;
btn_dobleErrado_V.Enabled = true;
}
void activarTriplesLocal()
{
btn_tripleEncestado_L.Enabled = true;
btn_tripleErrado_L.Enabled = true;
}
void activarTriplesVisitante()
{
btn_tripleEncestado_V.Enabled = true;
btn_tripleErrado_V.Enabled = true;
}
void activarPuntos()
{
activarDoblesLocal();
activarDoblesVisitante();
activarTriplesLocal();
activarTriplesVisitante();
}
#endregion
void activarFalta()
{
button_faltaL.Enabled = true;
button_faltaV.Enabled = true;
}
void desactivarFalta()
{
button_faltaL.Enabled = false;
button_faltaV.Enabled = false;
}
void activarPerdida()
{
//button_perdidaL.Enabled = true;
//button_perdidaV.Enabled = true;
}
void desactivarPerdida()
{
//button_perdidaL.Enabled = false;
//button_perdidaV.Enabled = false;
}
void activarCambio()
{
this.button_changeL.Visible = true;
this.button_changeV.Visible = true;
}
void desactivarCambio()
{
this.button_changeL.Visible = false;
this.button_changeV.Visible = false;
}
void activarTOLocal()
{
if (local.TiemposMuertosRestantes > 0)
this.LocalTO.Enabled = true;
}
void activarTOVisitante()
{
if (visitor.TiemposMuertosRestantes > 0)
this.VisitorTO.Enabled = true;
}
void activarTO()
{
activarTOLocal();
activarTOVisitante();
}
void desactivarTOLocal()
{
this.LocalTO.Enabled = false;
}
void desactivarTOVisitante()
{
this.VisitorTO.Enabled = false;
}
void desactivarTO()
{
desactivarTOLocal();
desactivarTOVisitante();
}
void activarLibreLocal()
{
btn_libreEncestado_L.Enabled = true;
btn_libreErrado_L.Enabled = true;
}
void desactivarLibreLocal()
{
btn_libreEncestado_L.Enabled = false;
btn_libreErrado_L.Enabled = false;
}
void activarLibreVisitante()
{
btn_libreEncestado_V.Enabled = true;
btn_libreErrado_V.Enabled = true;
}
void desactivarLibreVisitante()
{
btn_libreEncestado_V.Enabled = false;
btn_libreErrado_V.Enabled = false;
}
/// <summary>
/// Activa el rebote defensivo del equipo defensor y
/// el rebote ofensivo del equipo atacante
/// </summary>
/// <param name="defensivoLocal">Si es falso, el visitante esta defendiendo el rebote</param>
void activarRebotes(bool defensivoLocal = true)
{
if (defensivoLocal)
{
this.btn_rebote_Defensivo_L.Visible = true;
this.btn_rebote_Ofensivo_V.Visible = true;
}
else
{
this.btn_rebote_Ofensivo_L.Visible = true;
this.btn_rebote_Defensivo_V.Visible = true;
}
}
/// <summary>
/// Desactiva TODOS los rebotes de TODOS los equipos
/// </summary>
void desactivarRebotes()
{
// Locales
this.btn_rebote_Defensivo_L.Visible = false;
this.btn_rebote_Ofensivo_L.Visible = false;
// y Visitantes
this.btn_rebote_Ofensivo_V.Visible = false;
this.btn_rebote_Defensivo_V.Visible = false;
}
#endregion
#region Registros
void registrarSimple(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Tiro Libre Anotado" : "Tiro Libre Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarDoble(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Doble Anotado" : "Doble Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarTriple(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Triple Anotado" : "Triple Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarRebote(string nombreJugador, bool ofensivo = false)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (ofensivo) ? "Rebote Ofensivo" : "Rebote Defensivo";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarFalta(string nombreJugador)
{
string cuarto = lblCuarto.Text[0].ToString();
Registro r = new Registro(cuarto, this.label_timer.Text, "Falta", nombreJugador);
minuteToMinute.Add(r);
}
/// <summary>
/// Registra una canasta simple, doble o triple Encestada. Cambia el anotador del partido
/// </summary>
/// <param name="valor">Puede ser 1, 2 o 3</param>
/// <param name="jugador">Jugador al que se le asignara el punto</param>
/// <param name="local">Si es falso, corresponde al equipo visitante</param>
void anotacion(int valor, Player jugador, bool local = true)
{
switch (valor)
{
case 1:
jugador.TirosLibresAnotados++;
registrarSimple(jugador.CompleteName);
break;
case 2:
jugador.PuntosDoblesAnotados++;
registrarDoble(jugador.CompleteName);
break;
case 3:
jugador.PuntosTriplesAnotados++;
registrarTriple(jugador.CompleteName);
break;
}
Label score = null;
if (local)
score = this.label_ptsLocal;
else
score = this.label_ptsVsitor;
int pts = Convert.ToInt32(score.Text) + valor;
score.Text = pts.ToString();
}
/// <summary>
/// Registra una canasta simple, doble o triple Fallida.
/// Of course it does not change the scorer
/// </summary>
/// <param name="valor">Puede ser 1, 2 o 3</param>
/// <param name="jugador">Jugador al que se le asignara el fallo</param>
void fallo(int valor, Player jugador)
{
switch (valor)
{
case 1:
jugador.TirosLibresFallados++;
registrarSimple(jugador.CompleteName, false);
break;
case 2:
jugador.PuntosDoblesFallados++;
registrarDoble(jugador.CompleteName, false);
break;
case 3:
jugador.PuntosTriplesFallados++;
registrarTriple(jugador.CompleteName, false);
break;
}
}
#endregion
// ******************** //
// * METODOS LLAMADOS * //
// * POR EL USUARIO * //
// ******************** //
/// <summary>
/// Sucede cuando el usuario presiona el boton de "Comienzo" del partido
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
desactivarCambio();
desactivarRebotes();
desactivarPuntos();
desactivarPerdida();
desactivarFalta();
desactivarLibreLocal();
desactivarLibreVisitante();
if (procesoFalta)
{
MessageBox.Show("Se continua con los tiros libres..");
congelarContinuacion();
activarCambio();
// Check which team received fault and enable its free shoots
if (localTeamShoot)
activarLibreLocal();
else
activarLibreVisitante();
localTeamShoot = false;
}
else
{
// Check if time is running...
if (timer1.Enabled)
{ //... User want to stop timing
desactivarPerdida();
desactivarPuntos();
desactivarFalta();
activarContinuacion();
activarCambio();
}
else
{ //... User want to continue timing
activarFalta();
activarPerdida();
activarTO();
activarPuntos();
correrContinuacion();
}
}
}
/// <summary>
/// Sucede cuando el usuario realiza un Tiempo Muerto para el LOCAL
/// </summary>
private void LocalTO_Click(object sender, EventArgs e)
{
// Cambia la interfaz del usuario
// Parar reloj y dejarlo a disposición del usuario
activarContinuacion();
activarCambio();
// Desactiva los controles no disponibles
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarLibreLocal();
desactivarRebotes();
// Asigna los tiempos muertos
local.TiemposMuertosRestantes--;
this.label_LTO_restante.Text = local.TiemposMuertosRestantes.ToString();
if (local.TiemposMuertosRestantes == 0)
this.LocalTO.Enabled = false;
if (procesoFalta) {
localTeamShoot = true;
}
}
/// <summary>
/// Sucede cuando el usuario realiza un Tiempo Muerto para el VISITANTE
/// </summary>
private void VisitorTO_Click(object sender, EventArgs e)
{
// Cambia la interfaz del usuario
// Parar reloj y dejarlo a disposición del usuario
activarContinuacion();
activarCambio();
// Desactiva los controles no disponibles
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarLibreVisitante();
desactivarRebotes();
// Asigna los tiempos muertos
visitor.TiemposMuertosRestantes--;
this.label_VTO_restante.Text = visitor.TiemposMuertosRestantes.ToString();
if (visitor.TiemposMuertosRestantes == 0)
this.VisitorTO.Enabled = false;
}
/// <summary>
/// Sucede cuando el usuario quiere realizar un cambio del LOCAL
/// </summary>
private void button2_Click(object sender, EventArgs e)
{
if (listBox_LocalRoster.SelectedItem != null && comboBox_LocalSubs.SelectedItem != null)
{
Player p = (Player)listBox_LocalRoster.SelectedItem;
p.Starter = false;
p = (Player)comboBox_LocalSubs.SelectedItem;
p.Starter = true;
// Actualizar
cargarTitulares();
}
}
/// <summary>
/// Sucede cuando el usuario quiere realizar un cambio del VISITANTE
/// </summary>
private void button3_Click(object sender, EventArgs e)
{
if (listBox_VisitorRoster.SelectedItem != null && comboBox_VisitorSubs.SelectedItem != null)
{
Player p = (Player)listBox_VisitorRoster.SelectedItem;
p.Starter = false;
p = (Player)comboBox_VisitorSubs.SelectedItem;
p.Starter = true;
// Actualizar
cargarVisitantes();
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL comete una falta
/// </summary>
private void button_faltaL_Click(object sender, EventArgs e)
{
congelarContinuacion();
desactivarFalta();
desactivarPerdida();
desactivarTOLocal();
activarTOVisitante();
if (listBox_LocalRoster.SelectedItem != null)
{
// Agrega la Falta al Jugador y Registra el evento
Player p = (Player)listBox_LocalRoster.SelectedItem;
p.FaltasCometidas++;
registrarFalta(p.CompleteName);
// Fire player from game if reached limit of faults committed
if (p.FaltasCometidas == maxFaltas)
listBox_LocalRoster.Items.Remove(p);
// Check if player was shooting while received the fault
DialogResult userResponce = MessageBox.Show("El jugador estaba en posicion de Tiro?",
"Posicion de tiro",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (userResponce == DialogResult.Yes)
{
//desactivarTO();
procesoFalta = true; // Activa el proceso falta
desactivarDoblesLocal();
desactivarTriplesLocal();
}
else // Saque desde el costado
{
desactivarPuntos();
desactivarRebotes();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
else // No se conoce el jugador que realizo la falta
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
button_faltaL_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE comete una falta
/// </summary>
private void button_faltaV_Click(object sender, EventArgs e)
{
congelarContinuacion();
desactivarFalta();
desactivarPerdida();
desactivarTOVisitante();
activarTOLocal();
if (listBox_VisitorRoster.SelectedItem != null)
{
// Agrega la Falta al Jugador y Registra el evento
Player p = (Player)listBox_VisitorRoster.SelectedItem;
p.FaltasCometidas++;
registrarFalta(p.CompleteName);
// Fire player from game if reached limit of faults committed
if (p.FaltasCometidas == maxFaltas)
listBox_VisitorRoster.Items.Remove(p);
// Check if player was shooting while received the fault
DialogResult userResponce = MessageBox.Show("El jugador estaba en posicion de Tiro?",
"Posicion de tiro",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (userResponce == DialogResult.Yes)
{
//desactivarTO();
procesoFalta = true; // Activa el proceso falta
desactivarDoblesVisitante();
desactivarTriplesVisitante();
}
else // Saque desde el costado
{
desactivarPuntos();
desactivarRebotes();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
else // No se conoce el jugador que realizo la falta
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
button_faltaV_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesta un DOBLE
/// </summary>
private void btn_DobleEns_L_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(2, aux);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarPuntos();
// Tira 1 tiro libre al recibir falta en zona de 2 punto
tirosLibresDisponibles = 1;
//TODO
// Muestra el Estado
//toolStripStatusLabel1.Text = ""
}
else
{
desactivarTOLocal();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleEns_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesta un DOBLE
/// </summary>
private void btn_dobleEncestado_V_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(2, aux, false);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz gráfica
activarTOVisitante();
activarLibreVisitante();
desactivarPuntos();
// Tira 1 tiro libre al recibir falta en zona de 2 punto
// Tira 1 tiro libre
tirosLibresDisponibles = 1;
}
else
{
desactivarTOVisitante();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesta un TRIPLE
/// </summary>
private void btn_tripleEncestado_L_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(3, aux);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarPuntos();
// Jugada de 4 puntos!! oh yeah!
tirosLibresDisponibles = 1; // Tira 1 tiro libre
}
else
{
desactivarTOLocal();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleEns_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesta un TRIPLE
/// </summary>
private void btn_tripleEncestado_V_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(3, aux, false);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarPuntos();
// Jugada de 4 puntos!! oh yeah!
tirosLibresDisponibles = 1; // Tira 1 tiro libre
}
else
{
desactivarTOVisitante();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_tripleEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un DOBLE
/// </summary>
private void btn_DobleErrado_L_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarFalta();
desactivarPerdida();
// Tirara 2 tiros libres
tirosLibresDisponibles = 2;
}
else
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(2, aux);
// Change UI state
activarRebotes(false);
desactivarTOVisitante();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleErrado_L_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un DOBLE
/// </summary>
private void btn_dobleErrado_V_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarFalta();
desactivarPerdida();
// Tirara 2 tiros libres
tirosLibresDisponibles = 2;
}
else
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(2, aux);
// Change UI state
activarRebotes();
desactivarTOLocal();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleErrado_V_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un TRIPLE
/// </summary>
private void btn_tripleErrado_L_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarFalta();
desactivarPerdida();
// Tirara 3 tiros libres
tirosLibresDisponibles = 3;
}
else
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(3, aux);
// Change UI state
activarRebotes(false);
desactivarTOVisitante();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleErrado_L_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un TRIPLE
/// </summary>
private void btn_tripleErrado_V_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarFalta();
desactivarPerdida();
// Tirara 3 tiros libres
tirosLibresDisponibles = 3;
}
else
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(3, aux);
// Change UI state
activarRebotes();
desactivarTOLocal();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleErrado_V_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL logra un rebote OFENSIVO
/// </summary>
private void btn_rebote_L_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if(aux != null)
{
// Registra el rebote
aux.RebotesOfensivos++;
registrarRebote(aux.CompleteName, true);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE logra un rebote OFENSIVO
/// </summary>
private void btn_rebote_Ofensivo_V_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesOfensivos++;
registrarRebote(aux.CompleteName, true);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Ofensivo_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL logra un rebote DEFENSIVO
/// </summary>
private void btn_rebote_Defensivo_L_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesDefensivos++;
registrarRebote(aux.CompleteName);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Defensivo_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE logra un rebote DEFENSIVO
/// </summary>
private void btn_rebote_Defensivo_V_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesDefensivos++;
registrarRebote(aux.CompleteName);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Defensivo_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesto un Tiro Libre
/// </summary>
private void btn_libreEncestado_L_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(1, aux);
if (tirosLibresDisponibles == 0)
{
// Cambia el tiempo muerto de mando
activarTO();
desactivarTOLocal();
// Desactiva los tiros libres
desactivarLibreLocal();
activarContinuacion();
procesoFalta = false;
}
}
else
{
// Selecciona el jugador LOCAL que ENCESTO el tiro
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreEncestado_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesto un Tiro Libre
/// </summary>
private void btn_libreEncestado_V_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(1, aux, false);
if (tirosLibresDisponibles == 0)
{
// Cambia el tiempo muerto de mando
activarTO();
desactivarTOVisitante();
desactivarLibreVisitante();
activarContinuacion();
procesoFalta = false;
}
}
else
{
// Selecciona el jugador VISITANTE que ENCESTO el tiro
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un tiro libre
/// </summary>
private void btn_libreErrado_L_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(1, aux);
if (tirosLibresDisponibles == 0)
{
desactivarLibreLocal();
correrContinuacion();
procesoFalta = false;
// Se encienden los rebotes
activarRebotes(false);
}
}
else
{
// Selecciona el jugador LOCAL que FALLO el tiro
SelectPlayer window = new SelectPlayer(local.Players);
window.ShowDialog();
this.listBox_LocalRoster.SelectedItem = window.JugadorSeleccionado;
btn_libreErrado_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un tiro libre
/// </summary>
private void btn_libreErrado_V_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(1, aux);
if (tirosLibresDisponibles == 0)
{
desactivarLibreVisitante();
correrContinuacion();
procesoFalta = false;
// Se encienden los rebotes
activarRebotes(false);
}
}
else
{
// Selecciona el jugador LOCAL que FALLO el tiro
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreErrado_V_Click(sender, e);
}
}
/// <summary>
/// Abre un dialogo pidiendo confirmación al usuario para salir del programa
/// </summary>
private void partido_FormClosing(object sender, FormClosingEventArgs e)
{
if (!closeWindow)
{
DialogResult userResponce = MessageBox.Show("Esta seguro que desea cerrar la ventana?\n"+
"Los datos no seran guardados.",
"Cerrar ventana",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
if (userResponce == System.Windows.Forms.DialogResult.No)
e.Cancel = true;
}
}
private void button_perdidaL_Click(object sender, EventArgs e)
{
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
private void button_perdidaV_Click(object sender, EventArgs e)
{
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
}
| CLN-Group/Time-Out | Time Out/partido.cs | C# | mit | 41,256 |
#include "V3DResourceMemory.h"
#include "V3DDevice.h"
#include "V3DBuffer.h"
#include "V3DImage.h"
#include "V3DAdapter.h"
/******************************/
/* public - V3DResourceMemory */
/******************************/
V3DResourceMemory* V3DResourceMemory::Create()
{
return V3D_NEW_T(V3DResourceMemory);
}
V3D_RESULT V3DResourceMemory::Initialize(IV3DDevice* pDevice, V3DFlags propertyFlags, uint64_t size, const wchar_t* pDebugName)
{
V3D_ASSERT(pDevice != nullptr);
V3D_ASSERT(propertyFlags != 0);
V3D_ASSERT(size != 0);
m_pDevice = V3D_TO_ADD_REF(static_cast<V3DDevice*>(pDevice));
V3D_ADD_DEBUG_MEMORY_OBJECT(this, V3D_DEBUG_OBJECT_TYPE_RESOURCE_MEMORY, V3D_SAFE_NAME(this, pDebugName));
m_Source.memoryPropertyFlags = ToVkMemoryPropertyFlags(propertyFlags);
// ----------------------------------------------------------------------------------------------------
// ðmÛ
// ----------------------------------------------------------------------------------------------------
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.pNext = nullptr;
allocInfo.allocationSize = size;
allocInfo.memoryTypeIndex = m_pDevice->GetInternalAdapterPtr()->Vulkan_GetMemoryTypeIndex(m_Source.memoryPropertyFlags);
VkResult vkResult = vkAllocateMemory(m_pDevice->GetSource().device, &allocInfo, nullptr, &m_Source.deviceMemory);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
m_Source.memoryMappedRange.memory = m_Source.deviceMemory;
V3D_ADD_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory, V3D_SAFE_NAME(this, pDebugName));
// ----------------------------------------------------------------------------------------------------
// LqðÝè
// ----------------------------------------------------------------------------------------------------
m_Desc.propertyFlags = propertyFlags;
m_Desc.size = size;
// ----------------------------------------------------------------------------------------------------
return V3D_OK;
}
V3D_RESULT V3DResourceMemory::Initialize(IV3DDevice* pDevice, V3DFlags propertyFlags, uint32_t resourceCount, IV3DResource** ppResources, const wchar_t* pDebugName)
{
V3D_ASSERT(pDevice != nullptr);
V3D_ASSERT(propertyFlags != 0);
V3D_ASSERT(resourceCount != 0);
V3D_ASSERT(ppResources != nullptr);
m_pDevice = V3D_TO_ADD_REF(static_cast<V3DDevice*>(pDevice));
V3D_ADD_DEBUG_MEMORY_OBJECT(this, V3D_DEBUG_OBJECT_TYPE_RESOURCE_MEMORY, V3D_SAFE_NAME(this, pDebugName));
// ----------------------------------------------------------------------------------------------------
// \[XðACgÌå«¢É\[g
// ----------------------------------------------------------------------------------------------------
STLVector<IV3DResource*> resources;
resources.reserve(resourceCount);
for (uint32_t i = 0; i < resourceCount; i++)
{
#ifdef V3D_DEBUG
switch (ppResources[i]->GetResourceDesc().type)
{
case V3D_RESOURCE_TYPE_BUFFER:
if (static_cast<V3DBuffer*>(ppResources[i])->CheckBindMemory() == true)
{
V3D_LOG_PRINT_ERROR(Log_Error_AlreadyBindResourceMemory, V3D_SAFE_NAME(this, pDebugName), V3D_LOG_TYPE(ppResources), i, static_cast<V3DBuffer*>(ppResources[i])->GetDebugName());
return V3D_ERROR_FAIL;
}
break;
case V3D_RESOURCE_TYPE_IMAGE:
if (static_cast<IV3DImageBase*>(ppResources[i])->CheckBindMemory() == true)
{
V3D_LOG_PRINT_ERROR(Log_Error_AlreadyBindResourceMemory, V3D_SAFE_NAME(this, pDebugName), V3D_LOG_TYPE(ppResources), i, static_cast<IV3DImageBase*>(ppResources[i])->GetDebugName());
return V3D_ERROR_FAIL;
}
break;
}
#endif //V3D_DEBUG
resources.push_back(ppResources[i]);
}
std::sort(resources.begin(), resources.end(), [](const IV3DResource* lh, const IV3DResource* rh) { return lh->GetResourceDesc().memoryAlignment > rh->GetResourceDesc().memoryAlignment; });
// ----------------------------------------------------------------------------------------------------
// ACgðCɵÂÂAÌTCYðßé
// ----------------------------------------------------------------------------------------------------
uint64_t vkMinAlignment = m_pDevice->GetSource().deviceProps.limits.minMemoryMapAlignment;
VkDeviceSize vkAllocSize = 0;
STLVector<VkDeviceSize> vkOffsets;
vkOffsets.resize(resourceCount);
for (uint32_t i = 0; i < resourceCount; i++)
{
const V3DResourceDesc& resourceDesc = ppResources[i]->GetResourceDesc();
VkDeviceSize vkAlignment = V3D_MAX(vkMinAlignment, resourceDesc.memoryAlignment);
if (vkAllocSize % vkAlignment)
{
vkAllocSize = (vkAllocSize / vkAlignment) * vkAlignment + vkAlignment;
}
vkOffsets[i] = vkAllocSize;
vkAllocSize += resourceDesc.memorySize;
}
// ----------------------------------------------------------------------------------------------------
// ðì¬
// ----------------------------------------------------------------------------------------------------
m_Source.memoryPropertyFlags = ToVkMemoryPropertyFlags(propertyFlags);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.pNext = nullptr;
allocInfo.allocationSize = vkAllocSize;
allocInfo.memoryTypeIndex = m_pDevice->GetInternalAdapterPtr()->Vulkan_GetMemoryTypeIndex(m_Source.memoryPropertyFlags);
VkResult vkResult = vkAllocateMemory(m_pDevice->GetSource().device, &allocInfo, nullptr, &m_Source.deviceMemory);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
m_Source.memoryMappedRange.memory = m_Source.deviceMemory;
V3D_ADD_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory, V3D_SAFE_NAME(this, pDebugName));
// ----------------------------------------------------------------------------------------------------
// LqðÝè
// ----------------------------------------------------------------------------------------------------
m_Desc.propertyFlags = propertyFlags;
m_Desc.size = vkAllocSize;
// ----------------------------------------------------------------------------------------------------
// \[XðoCh
// ----------------------------------------------------------------------------------------------------
V3D_RESULT result = V3D_ERROR_FAIL;
for (uint32_t i = 0; i < resourceCount; i++)
{
IV3DResource* pResource = ppResources[i];
switch (pResource->GetResourceDesc().type)
{
case V3D_RESOURCE_TYPE_BUFFER:
result = static_cast<V3DBuffer*>(pResource)->BindMemory(this, vkOffsets[i]);
if (result != V3D_OK)
{
return result;
}
break;
case V3D_RESOURCE_TYPE_IMAGE:
result = static_cast<V3DImage*>(pResource)->BindMemory(this, vkOffsets[i]);
if (result != V3D_OK)
{
return result;
}
break;
}
}
// ----------------------------------------------------------------------------------------------------
return V3D_OK;
}
const V3DResourceMemory::Source& V3DResourceMemory::GetSource() const
{
return m_Source;
}
V3D_RESULT V3DResourceMemory::Map(uint64_t offset, uint64_t size, void** ppMemory)
{
if (m_Desc.size < (offset + size))
{
return V3D_ERROR_FAIL;
}
if (m_pMemory != nullptr)
{
*ppMemory = m_pMemory + offset;
return V3D_OK;
}
if (m_Source.memoryMappedRange.size != 0)
{
return V3D_ERROR_FAIL;
}
VkResult vkResult = vkMapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, offset, size, 0, ppMemory);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
m_Source.memoryMappedRange.offset = offset;
m_Source.memoryMappedRange.size = size;
if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
vkResult = vkInvalidateMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
}
return V3D_OK;
}
V3D_RESULT V3DResourceMemory::Unmap()
{
if (m_pMemory != nullptr)
{
return V3D_OK;
}
if (m_Source.memoryMappedRange.size == 0)
{
return V3D_ERROR_FAIL;
}
V3D_RESULT result = V3D_OK;
if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
VkResult vkResult = vkFlushMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange);
if (vkResult != VK_SUCCESS)
{
result = ToV3DResult(vkResult);
}
}
m_Source.memoryMappedRange.offset = 0;
m_Source.memoryMappedRange.size = 0;
vkUnmapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory);
return result;
}
#ifdef V3D_DEBUG
bool V3DResourceMemory::Debug_CheckMemory(uint64_t offset, uint64_t size)
{
return (m_Desc.size >= (offset + size));
}
#endif //V3D_DEBUG
/****************************************/
/* public override - IV3DResourceMemory */
/****************************************/
const V3DResourceMemoryDesc& V3DResourceMemory::GetDesc() const
{
return m_Desc;
}
V3D_RESULT V3DResourceMemory::BeginMap()
{
if (m_Source.memoryMappedRange.size != 0)
{
return V3D_ERROR_FAIL;
}
VkResult vkResult = vkMapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, 0, m_Desc.size, 0, reinterpret_cast<void**>(&m_pMemory));
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
m_Source.memoryMappedRange.offset = 0;
m_Source.memoryMappedRange.size = m_Desc.size;
if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
vkResult = vkInvalidateMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
}
return V3D_OK;
}
V3D_RESULT V3DResourceMemory::EndMap()
{
if (m_Source.memoryMappedRange.size == 0)
{
return V3D_ERROR_FAIL;
}
V3D_RESULT result = V3D_OK;
if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
VkResult vkResult = vkFlushMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange);
if (vkResult != VK_SUCCESS)
{
result = ToV3DResult(vkResult);
}
}
m_Source.memoryMappedRange.offset = 0;
m_Source.memoryMappedRange.size = 0;
vkUnmapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory);
m_pMemory = nullptr;
return result;
}
/*************************************/
/* public override - IV3DDeviceChild */
/*************************************/
void V3DResourceMemory::GetDevice(IV3DDevice** ppDevice)
{
(*ppDevice) = V3D_TO_ADD_REF(m_pDevice);
}
/********************************/
/* public override - IV3DObject */
/********************************/
int64_t V3DResourceMemory::GetRefCount() const
{
return m_RefCounter;
}
void V3DResourceMemory::AddRef()
{
V3D_REF_INC(m_RefCounter);
}
void V3DResourceMemory::Release()
{
if (V3D_REF_DEC(m_RefCounter))
{
V3D_REF_FENCE();
V3D_DELETE_THIS_T(this, V3DResourceMemory);
}
}
/*******************************/
/* private - V3DResourceMemory */
/*******************************/
V3DResourceMemory::V3DResourceMemory() :
m_RefCounter(1),
m_pDevice(nullptr),
m_Desc({}),
m_Source({}),
m_pMemory(nullptr)
{
m_Source.deviceMemory = VK_NULL_HANDLE;
m_Source.memoryMappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
m_Source.memoryMappedRange.pNext = nullptr;
}
V3DResourceMemory::~V3DResourceMemory()
{
if (m_pDevice != nullptr)
{
m_pDevice->NotifyReleaseResourceMemory();
}
if (m_Source.deviceMemory != VK_NULL_HANDLE)
{
vkFreeMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, nullptr);
V3D_REMOVE_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory);
}
V3D_REMOVE_DEBUG_MEMORY_OBJECT(this);
V3D_RELEASE(m_pDevice);
}
| mixberry8/v3d | build/runtime/source/V3DResourceMemory.cpp | C++ | mit | 12,042 |
<?php
namespace Peridot\Leo\Interfaces;
use Peridot\Leo\Assertion;
use Peridot\Leo\Interfaces\Assert\CollectionAssertTrait;
use Peridot\Leo\Interfaces\Assert\ObjectAssertTrait;
use Peridot\Leo\Interfaces\Assert\TypeAssertTrait;
use Peridot\Leo\Leo;
/**
* Assert is a non-chainable, object oriented interface
* on top of a Leo Assertion.
*
* @method instanceOf() instanceOf(object $actual, string $expected, string $message = "") Perform an instanceof assertion.
* @method include() include(array $haystack, string $expected, string $message = "") Perform an inclusion assertion.
*
* @package Peridot\Leo\Interfaces
*/
class Assert
{
use TypeAssertTrait;
use ObjectAssertTrait;
use CollectionAssertTrait;
/**
* An array of operators mapping to assertions.
*
* @var array
*/
public static $operators = [
'==' => 'loosely->equal',
'===' => 'equal',
'>' => 'above',
'>=' => 'least',
'<' => 'below',
'<=' => 'most',
'!=' => 'not->loosely->equal',
'!==' => 'not->equal',
];
/**
* @var Assertion
*/
protected $assertion;
/**
* @param Assertion $assertion
*/
public function __construct(Assertion $assertion = null)
{
if ($assertion === null) {
$assertion = Leo::assertion();
}
$this->assertion = $assertion;
}
/**
* Perform an a loose equality assertion.
*
* @param mixed $actual
* @param mixed $expected
* @param string $message
*/
public function equal($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->loosely->equal($expected, $message);
}
/**
* Perform a negated loose equality assertion.
*
* @param mixed $actual
* @param mixed $expected
* @param string $message
*/
public function notEqual($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->not->equal($expected, $message);
}
/**
* Performs a throw assertion.
*
* @param callable $fn
* @param $exceptionType
* @param string $exceptionMessage
* @param string $message
*/
public function throws(callable $fn, $exceptionType, $exceptionMessage = '', $message = '')
{
$this->assertion->setActual($fn);
return $this->assertion->to->throw($exceptionType, $exceptionMessage, $message);
}
/**
* Performs a negated throw assertion.
*
* @param callable $fn
* @param $exceptionType
* @param string $exceptionMessage
* @param string $message
*/
public function doesNotThrow(callable $fn, $exceptionType, $exceptionMessage = '', $message = '')
{
$this->assertion->setActual($fn);
return $this->assertion->not->to->throw($exceptionType, $exceptionMessage, $message);
}
/**
* Perform an ok assertion.
*
* @param mixed $object
* @param string $message
*/
public function ok($object, $message = '')
{
$this->assertion->setActual($object);
return $this->assertion->to->be->ok($message);
}
/**
* Perform a negated assertion.
*
* @param mixed $object
* @param string $message
*/
public function notOk($object, $message = '')
{
$this->assertion->setActual($object);
return $this->assertion->to->not->be->ok($message);
}
/**
* Perform a strict equality assertion.
*
* @param mixed $actual
* @param mixed $expected
* @param string $message
*/
public function strictEqual($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->equal($expected, $message);
}
/**
* Perform a negated strict equality assertion.
*
* @param mixed $actual
* @param mixed $expected
* @param string $message
*/
public function notStrictEqual($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->not->equal($expected, $message);
}
/**
* Perform a pattern assertion.
*
* @param string $value
* @param string $pattern
* @param string $message
*/
public function match($value, $pattern, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->match($pattern, $message);
}
/**
* Perform a negated pattern assertion.
*
* @param string $value
* @param string $pattern
* @param string $message
*/
public function notMatch($value, $pattern, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->not->match($pattern, $message);
}
/**
* Compare two values using the given operator.
*
* @param mixed $left
* @param string $operator
* @param mixed $right
* @param string $message
*/
public function operator($left, $operator, $right, $message = '')
{
if (!isset(static::$operators[$operator])) {
throw new \InvalidArgumentException("Invalid operator $operator");
}
$this->assertion->setActual($left);
return $this->assertion->{static::$operators[$operator]}($right, $message);
}
/**
* Defined to allow use of reserved words for methods.
*
* @param $method
* @param $args
*/
public function __call($method, $args)
{
switch ($method) {
case 'instanceOf':
return call_user_func_array([$this, 'isInstanceOf'], $args);
case 'include':
return call_user_func_array([$this, 'isIncluded'], $args);
default:
throw new \BadMethodCallException("Call to undefined method $method");
}
}
}
| peridot-php/leo | src/Interfaces/Assert.php | PHP | mit | 6,019 |
black = '#202427';
red = '#EB6A58'; // red
green = '#49A61D'; // green
yellow = '#959721'; // yellow
blue = '#798FB7'; // blue
magenta = '#CD7B7E'; // pink
cyan = '#4FA090'; // cyan
white = '#909294'; // light gray
lightBlack = '#292B35'; // medium gray
lightRed = '#DB7824'; // red
lightGreen = '#09A854'; // green
lightYellow = '#AD8E4B'; // yellow
lightBlue = '#309DC1'; // blue
lightMagenta= '#C874C2'; // pink
lightCyan = '#1BA2A0'; // cyan
lightWhite = '#8DA3B8'; // white
t.prefs_.set('color-palette-overrides',
[ black , red , green , yellow,
blue , magenta , cyan , white,
lightBlack , lightRed , lightGreen , lightYellow,
lightBlue , lightMagenta , lightCyan , lightWhite ]);
t.prefs_.set('cursor-color', lightWhite);
t.prefs_.set('foreground-color', lightWhite);
t.prefs_.set('background-color', black);
| iamruinous/dotfiles | blink/themes/tempus_winter.js | JavaScript | mit | 966 |
import cuid from "cuid";
import Result, { isError } from "../../common/Result";
import assert from "assert";
import { di, singleton, diKey } from "../../common/di";
import { ILocalFiles, ILocalFilesKey } from "../../common/LocalFiles";
import { IStoreDB, IStoreDBKey, MergeEntity } from "../../common/db/StoreDB";
import {
ApplicationDto,
applicationKey,
CanvasDto,
DiagramDto,
DiagramInfoDto,
DiagramInfoDtos,
FileDto,
} from "./StoreDtos";
import { LocalEntity } from "../../common/db/LocalDB";
import { RemoteEntity } from "../../common/db/RemoteDB";
export interface Configuration {
onRemoteChanged: (keys: string[]) => void;
onSyncChanged: (isOK: boolean, error?: Error) => void;
isSyncEnabled: boolean;
}
export const IStoreKey = diKey<IStore>();
export interface IStore {
configure(config: Partial<Configuration>): void;
triggerSync(): Promise<Result<void>>;
openNewDiagram(): DiagramDto;
tryOpenMostResentDiagram(): Promise<Result<DiagramDto>>;
tryOpenDiagram(diagramId: string): Promise<Result<DiagramDto>>;
setDiagramName(name: string): void;
exportDiagram(): DiagramDto; // Used for print or export
getRootCanvas(): CanvasDto;
getCanvas(canvasId: string): CanvasDto;
writeCanvas(canvas: CanvasDto): void;
getMostResentDiagramId(): Result<string>;
getRecentDiagrams(): DiagramInfoDto[];
deleteDiagram(diagramId: string): void;
saveDiagramToFile(): void;
loadDiagramFromFile(): Promise<Result<string>>;
saveAllDiagramsToFile(): Promise<void>;
}
const rootCanvasId = "root";
const defaultApplicationDto: ApplicationDto = { diagramInfos: {} };
const defaultDiagramDto: DiagramDto = { id: "", name: "", canvases: {} };
@singleton(IStoreKey)
export class Store implements IStore {
private currentDiagramId: string = "";
private config: Configuration = {
onRemoteChanged: () => {},
onSyncChanged: () => {},
isSyncEnabled: false,
};
constructor(
// private localData: ILocalData = di(ILocalDataKey),
private localFiles: ILocalFiles = di(ILocalFilesKey),
private db: IStoreDB = di(IStoreDBKey)
) {}
public configure(config: Partial<Configuration>): void {
this.config = { ...this.config, ...config };
this.db.configure({
onConflict: (local: LocalEntity, remote: RemoteEntity) =>
this.onEntityConflict(local, remote),
...config,
onRemoteChanged: (keys: string[]) => this.onRemoteChange(keys),
});
}
public triggerSync(): Promise<Result<void>> {
return this.db.triggerSync();
}
public openNewDiagram(): DiagramDto {
const now = Date.now();
const id = cuid();
const name = this.getUniqueName();
console.log("new diagram", id, name);
const diagramDto: DiagramDto = {
id: id,
name: name,
canvases: {},
};
const applicationDto = this.getApplicationDto();
applicationDto.diagramInfos[id] = {
id: id,
name: name,
accessed: now,
};
this.db.monitorRemoteEntities([id, applicationKey]);
this.db.writeBatch([
{ key: applicationKey, value: applicationDto },
{ key: id, value: diagramDto },
]);
this.currentDiagramId = id;
return diagramDto;
}
public async tryOpenMostResentDiagram(): Promise<Result<DiagramDto>> {
const id = this.getMostResentDiagramId();
if (isError(id)) {
return id as Error;
}
const diagramDto = await this.db.tryReadLocalThenRemote<DiagramDto>(id);
if (isError(diagramDto)) {
return diagramDto;
}
this.db.monitorRemoteEntities([id, applicationKey]);
this.currentDiagramId = id;
return diagramDto;
}
public async tryOpenDiagram(id: string): Promise<Result<DiagramDto>> {
const diagramDto = await this.db.tryReadLocalThenRemote<DiagramDto>(id);
if (isError(diagramDto)) {
return diagramDto;
}
this.db.monitorRemoteEntities([id, applicationKey]);
this.currentDiagramId = id;
// Too support most recently used diagram feature, we update accessed time
const applicationDto = this.getApplicationDto();
const diagramInfo = applicationDto.diagramInfos[id];
applicationDto.diagramInfos[id] = { ...diagramInfo, accessed: Date.now() };
this.db.writeBatch([{ key: applicationKey, value: applicationDto }]);
return diagramDto;
}
public getRootCanvas(): CanvasDto {
return this.getCanvas(rootCanvasId);
}
public getCanvas(canvasId: string): CanvasDto {
const diagramDto = this.getDiagramDto();
const canvasDto = diagramDto.canvases[canvasId];
assert(canvasDto);
return canvasDto;
}
public writeCanvas(canvasDto: CanvasDto): void {
const diagramDto = this.getDiagramDto();
const id = diagramDto.id;
diagramDto.canvases[canvasDto.id] = canvasDto;
this.db.writeBatch([{ key: id, value: diagramDto }]);
}
public getRecentDiagrams(): DiagramInfoDto[] {
return Object.values(this.getApplicationDto().diagramInfos).sort((i1, i2) =>
i1.accessed < i2.accessed ? 1 : i1.accessed > i2.accessed ? -1 : 0
);
}
// For printing/export
public exportDiagram(): DiagramDto {
return this.getDiagramDto();
}
public deleteDiagram(id: string): void {
console.log("Delete diagram", id);
const applicationDto = this.getApplicationDto();
delete applicationDto.diagramInfos[id];
this.db.writeBatch([{ key: applicationKey, value: applicationDto }]);
this.db.removeBatch([id]);
}
public setDiagramName(name: string): void {
const diagramDto = this.getDiagramDto();
const id = diagramDto.id;
diagramDto.name = name;
const applicationDto = this.getApplicationDto();
applicationDto.diagramInfos[id] = {
...applicationDto.diagramInfos[id],
name: name,
accessed: Date.now(),
};
this.db.writeBatch([
{ key: applicationKey, value: applicationDto },
{ key: id, value: diagramDto },
]);
}
public async loadDiagramFromFile(): Promise<Result<string>> {
const fileText = await this.localFiles.loadFile();
const fileDto: FileDto = JSON.parse(fileText);
// if (!(await this.sync.uploadDiagrams(fileDto.diagrams))) {
// // save locally
// fileDto.diagrams.forEach((d: DiagramDto) => this.local.writeDiagram(d));
// }
//fileDto.diagrams.forEach((d: DiagramDto) => this.local.writeDiagram(d));
const firstDiagramId = fileDto.diagrams[0]?.id;
if (!firstDiagramId) {
return new Error("No valid diagram in file");
}
return firstDiagramId;
}
public saveDiagramToFile(): void {
const diagramDto = this.getDiagramDto();
const fileDto: FileDto = { diagrams: [diagramDto] };
const fileText = JSON.stringify(fileDto, null, 2);
this.localFiles.saveFile(`${diagramDto.name}.json`, fileText);
}
public async saveAllDiagramsToFile(): Promise<void> {
// let diagrams = await this.sync.downloadAllDiagrams();
// if (!diagrams) {
// // Read from local
// diagrams = this.local.readAllDiagrams();
// }
// let diagrams = this.local.readAllDiagrams();
// const fileDto = { diagrams: diagrams };
// const fileText = JSON.stringify(fileDto, null, 2);
// this.localFiles.saveFile(`diagrams.json`, fileText);
}
public getMostResentDiagramId(): Result<string> {
const resentDiagrams = this.getRecentDiagrams();
if (resentDiagrams.length === 0) {
return new RangeError("not found");
}
return resentDiagrams[0].id;
}
public getApplicationDto(): ApplicationDto {
return this.db.readLocal<ApplicationDto>(
applicationKey,
defaultApplicationDto
);
}
private onRemoteChange(keys: string[]) {
this.config.onRemoteChanged(keys);
}
private onEntityConflict(
local: LocalEntity,
remote: RemoteEntity
): MergeEntity {
if ("diagramInfos" in local.value) {
return this.onApplicationConflict(local, remote);
}
return this.onDiagramConflict(local, remote);
}
private onApplicationConflict(
local: LocalEntity,
remote: RemoteEntity
): MergeEntity {
console.warn("Application conflict", local, remote);
const mergeDiagramInfos = (
newerDiagrams: DiagramInfoDtos,
olderDiagrams: DiagramInfoDtos
): DiagramInfoDtos => {
let mergedDiagrams = { ...olderDiagrams, ...newerDiagrams };
Object.keys(newerDiagrams).forEach((key) => {
if (!(key in newerDiagrams)) {
delete mergedDiagrams[key];
}
});
return mergedDiagrams;
};
if (local.version >= remote.version) {
// Local entity has more edits, merge diagram infos, but priorities remote
const applicationDto: ApplicationDto = {
diagramInfos: mergeDiagramInfos(
local.value.diagramInfos,
remote.value.diagramInfos
),
};
return {
key: local.key,
value: applicationDto,
version: local.version,
};
}
// Remote entity since that has more edits, merge diagram infos, but priorities local
const applicationDto: ApplicationDto = {
diagramInfos: mergeDiagramInfos(
remote.value.diagramInfos,
local.value.diagramInfos
),
};
return {
key: remote.key,
value: applicationDto,
version: remote.version,
};
}
private onDiagramConflict(
local: LocalEntity,
remote: RemoteEntity
): MergeEntity {
console.warn("Diagram conflict", local, remote);
if (local.version >= remote.version) {
// use local since it has more edits
return {
key: local.key,
value: local.value,
version: local.version,
};
}
// Use remote entity since that has more edits
return {
key: remote.key,
value: remote.value,
version: remote.version,
};
}
private getDiagramDto(): DiagramDto {
return this.db.readLocal<DiagramDto>(
this.currentDiagramId,
defaultDiagramDto
);
}
private getUniqueName(): string {
const diagrams = Object.values(this.getApplicationDto().diagramInfos);
for (let i = 0; i < 99; i++) {
const name = "Name" + (i > 0 ? ` (${i})` : "");
if (!diagrams.find((d) => d.name === name)) {
return name;
}
}
return "Name";
}
}
| michael-reichenauer/Dependinator | Web/src/application/diagram/Store.ts | TypeScript | mit | 10,268 |
var createSubmit = function(name, primus, keyDict) {
return function(event) {
var message = $('#message').val();
if (message.length === 0) {
event.preventDefault();
return;
}
$('#message').val('');
$('#message').focus();
var BigInteger = forge.jsbn.BigInteger;
var data = JSON.parse(sessionStorage[name]);
var pem = data.pem;
var privateKey = forge.pki.privateKeyFromPem(pem);
var ownPublicKey = forge.pki.setRsaPublicKey(new BigInteger(data.n), new BigInteger(data.e));
var keys = [];
var iv = forge.random.getBytesSync(16);
var key = forge.random.getBytesSync(16);
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(message, 'utf8'));
cipher.finish();
var encryptedMessage = cipher.output.getBytes();
var encryptedKey = ownPublicKey.encrypt(key, 'RSA-OAEP');
keys.push({
'name': name,
'key': encryptedKey
});
var md = forge.md.sha1.create();
md.update(message, 'utf8');
var signature = privateKey.sign(md);
var recipients = $.map($("#recipients").tokenfield("getTokens"), function(o) {return o.value;});
var deferredRequests = [];
for (var i = 0; i < recipients.length; i++) {
(function (index) {
var retrieveKey = function(pk) {
if (pk === false) {
return;
}
if (keyDict[recipients[i]] === undefined) {
keyDict[recipients[i]] = pk;
}
var publicKey = forge.pki.setRsaPublicKey(new BigInteger(pk.n), new BigInteger(pk.e));
var encryptedKey = publicKey.encrypt(key, 'RSA-OAEP');
keys.push({
'name': recipients[index],
'key': encryptedKey
});
}
if (keyDict[recipients[i]] === undefined) {
deferredRequests.push($.post('/user/getpublickey', {'name' : recipients[i]}, retrieveKey));
} else {
retrieveKey(keyDict[recipients[i]]);
}
})(i);
}
$.when.apply(null, deferredRequests).done(function() {
primus.substream('messageStream').write({'message': encryptedMessage, 'keys': keys, 'iv': iv,
'signature': signature, 'recipients': recipients});
});
event.preventDefault();
};
};
| raytracer/CryptoGraph | src/client/stream/createSubmit.js | JavaScript | mit | 2,725 |
<?php
namespace action\sub;
use net\shawn_huang\pretty\Action;
class Index extends Action {
protected function run() {
$this->put([
'holy' => 'shit'
]);
}
} | Cretty/pretty-php | test/test_classes/action/sub/Index.class.php | PHP | mit | 195 |
<?php
namespace keeko\account\action;
use keeko\framework\foundation\AbstractAction;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use keeko\framework\domain\payload\Success;
/**
* User Widget
*
* This code is automatically created. Modifications will probably be overwritten.
*
* @author gossi
*/
class AccountWidgetAction extends AbstractAction {
/**
* Automatically generated run method
*
* @param Request $request
* @return Response
*/
public function run(Request $request) {
$prefs = $this->getServiceContainer()->getPreferenceLoader()->getSystemPreferences();
$translator = $this->getServiceContainer()->getTranslator();
return $this->responder->run($request, new Success([
'account_url' => $prefs->getAccountUrl(),
'destination' => $prefs->getAccountUrl() . '/' . $translator->trans('slug.login'),
'redirect' => $request->getUri(),
'login_label' => $prefs->getUserLogin()
]));
}
}
| keeko/account | src/action/AccountWidgetAction.php | PHP | mit | 978 |