repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
TaoPengFei/DashboardUI | JS/StoreOperation.js | 24544 | let StoreOperation = {};
/*-------------------------------------------------------------------------*
* StoreOperation functions && settings *
*-------------------------------------------------------------------------*/
StoreOperation.addCommas = ( nStr ) => {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
x2 = x2.slice(0,3);
return x1 + x2;
};
/*-------------------------------------------------------------------------*
* Chart Defaults *
*-------------------------------------------------------------------------*/
// Chart defaults for all bar charts
StoreOperation.defaultBarSettings = function(){
let cd = this.chartDefinition;
// general settings
cd.height = 330;
cd.xAxisLabel_textAngle = -0.1;
cd.legendShape = 'circle';
cd.selectable = true;
cd.hoverable = true;
cd.legendPosition = 'right';
cd.plotFrameVisible = false;
cd.orthoAxisGrid = true;
cd.orthoAxisTicks = false;
//cd.stacked = true;
// legend
// use series colors on legend labels
cd.legendLabel_textStyle = function(scene) {
var colorScale = this.panel.axes.color.scale;
return colorScale(this.getValue());
};
// xAxis
cd.xAxisLabel_textAlign = 'right';
cd.xAxisLabel_textBaseline = 'top';
cd.format = {
//number: "0.##A",
number: '#,#.00',
percent: "#.00%"
};
// extensionPoints
cd.extensionPoints = [
["xAxisRule_strokeStyle", "white"],
["yAxisRule_strokeStyle", "white"],
["y2AxisRule_strokeStyle", "white"]
];
cd.orthoAxisTickFormatter = function(v){
if( v < 1000000 && v >= 1000 ){
return sprintf('%d', v/1000) + 'K';
}else if( v >= 1000000 ){
return sprintf('%d', v/1000000) + 'M';
}else{
return sprintf('%d', v);
}
};
// tooltips
cd.tooltipDelayIn = 20;
cd.tooltipDelayOut = 20;
cd.tooltipFade = false;
cd.tooltipGravity = 's';
cd.tooltipOpacity = 1;
cd.tooltipFollowMouse = true;
cd.tooltipFormat = function f(){
let series = this.getSeriesLabel(),
category = this.getCategory(),
value = StoreOperation.addCommas(this.getValue().toFixed(2));
return "<div class='tooltipContainer'>" +
"<div class='tooltipTitle'>" + category + "</div>" +
"<div class='tooltipLabel'>" + series + "</div>" +
"<div class='tooltipValue'>" + value + "</div>" +
"</div>";
}
// axis grids
//cd.orthoAxisTitle = '净利润';
cd.orthoAxisTitleFont = "lighter 16px TPF_Font_Thin";
cd.axisLabel_font = "lighter 16px TPF_Font_Thin";
cd.baseAxisLabel_textStyle = "#4d4d4d";
cd.baseAxisLabel_visible = function() {
if(this.index%2 == 0) return true;
else return false;
};
cd.baseAxisRule_visible = false;
cd.baseAxisTooltipEnabled = false;
cd.orthoAxisLabel_textStyle = "#999999";
cd.orthoAxisDesiredTickCount = 2;
cd.orthoAxisGrid = false;
cd.orthoAxisGrid_strokeStyle = function() {
return (this.index !== this.scene.parent.childNodes.length - 1) ? "#CCC" : "#CCC";
};
cd.orthoAxisGrid_lineWidth = function() {
return (this.index !== this.scene.parent.childNodes.length - 1) ? 1 : 1;
};;
cd.orthoAxisGrid_visible = true;
cd.valuesAnchor = 'top';
cd.valuesVisible = true;
cd.valuesFont = "lighter 15px TPF_Font_Thin";
//color
cd.colors = ['#0055B8','#FF9E16', '#D25459', '#009BFF','#009BDE','#71A087'];
};
// Chart defaults for all Pie charts
StoreOperation.defaultPieSettings = function(){
let cd = this.chartDefinition;
// general settings
//color
cd.colors = ['#0055B8','#FF9E16', '#D25459', '#009BFF','#009BDE','#71A087'];
cd.legendShape = 'circle';
cd.selectable = true;
cd.hoverable = true;
cd.valuesFont = "lighter 15px TPF_Font_Thin";
//cd.valueFormat
cd.format = {
//number: "0.##A",
number: '#,#.00',
percent: "#.00%"
};
// legend
cd.legendPosition = 'right';
// use series colors on legend labels
cd.legendLabel_textStyle = function(scene) {
var colorScale = this.panel.axes.color.scale;
return colorScale(this.getValue());
};
// tooltips
cd.tooltipDelayIn = 20;
cd.tooltipDelayOut = 20;
cd.tooltipFade = false;
cd.tooltipGravity = 's';
cd.tooltipOpacity = 1;
cd.tooltipFollowMouse = true;
cd.tooltipFormat = function f(){
let series = this.getSeriesLabel(),
category = this.getCategory(),
value = StoreOperation.addCommas(this.getValue().toFixed(2));
return "<div class='tooltipContainer'>" +
"<div class='tooltipTitle'>" + category + "</div>" +
"<div class='tooltipValue'>" + value + "</div>" +
"</div>";
}
};
/*-------------------------------------------------------------------------*
* Echarts && settings *
*-------------------------------------------------------------------------*/
function initEcahrts(){
let readJSONFile = function(url){
let jsonData;
$.ajax({
type : 'get',
url : url,
async : false,
dataType : 'json',
data : null,
success : function(response){
jsonData = response;
//alert(jsonData);
}
})
return jsonData;
};
/**
*
* 第一个图
*
**/
let url_gauge_1 = "/pentaho/plugin/cda/api/doQuery?path=/public/dashboard/StoreOperation/StoreOperation.cda&dataAccessId=GaugeEchartsQuery";
url_gauge_1 += '¶mstartDay=' + startDay + '¶mendDay=' + endDay + '¶mbrandParam=' + brandParam + '¶mplaceParam=' + placeParam + '¶marea1Param=' + area1Param + '¶marea2Param=' + area2Param + '¶marea3Param=' + area3Param + '¶mshopParam=' + shopParam + '¶moutletParam=' + outletParam;
let getFirstGaugeJSON_1 = readJSONFile(url_gauge_1).resultset;
let myChart_1 = echarts.init(document.getElementById('saleAmtGaugeDom_KPI'));
let FirstGaugeDataEncapsulation_1 = (function(){
let data = function(){
let tempArr = [];
for(let i = 0; i < getFirstGaugeJSON_1.length; i++){
tempArr.push({
'name' : getFirstGaugeJSON_1[i][0],
'value': getFirstGaugeJSON_1[i][1],
selected : true
})
}
return tempArr;
};
return {
getDatas : function(){
return data()
}
}
})();
let ShowFirstGaugeEcharts_1 = function(){
myChart_1.setOption({
//color: ['#0055B8','#FF9E16','#009BDE','#71A087'],
title: {
text: '', //标题文本内容
},
toolbox: { //可视化的工具箱
show: true,
feature: {
/* restore: { //重置
show: true
},
saveAsImage: {//保存图片
show: true
}*/
}
},
/*
tooltip: { //弹窗组件
formatter: "{a} <br/>{b} : {c}%"
},
*/
tooltip: {
trigger: 'item',
backgroundColor: '#ffffff',
transitionDuration : 0.4,
borderWidth: 1,
borderColor: '#ccc',
textStyle: {
color: '#4d4d4d',
fontFamily: 'TPF_Font_Thin',
fontSize: 14
},
axisPointer: {
type: 'cross'
}
},
series: [{
name: '营业额完成情况',
type: 'gauge',
min:0,
max:100,
splitNumber:5,
radius: '90%',
axisLine: { // 坐标轴线
lineStyle: { // 属性lineStyle控制线条样式 FF9E16 0055B8
color: [[0.2, '#0055B8'],[0.8, '#FF9E16'],[1, '#D25459']],
width: 14,
shadowColor : '#E7EBED', //默认透明
type: 'dotted',
shadowBlur: 20
}
},
axisLabel: { // 坐标轴小标记
textStyle: { // 属性lineStyle控制线条样式
fontWeight: 'bolder',
//color: '#fff',
shadowColor : '#fff', //默认透明
shadowBlur: 10
}
},
axisTick: { // 坐标轴小标记
show:false,
length :15, // 属性length控制线长
lineStyle: { // 属性lineStyle控制线条样式
color: 'auto',
shadowColor : '#fff', //默认透明
shadowBlur: 10
}
},
splitLine: { // 分隔线
show: false,
length :25, // 属性length控制线长
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
width:3,
color: '#fff',
shadowColor : '#fff', //默认透明
shadowBlur: 10
}
},
pointer: { // 分隔线
shadowColor : '#E7EBED', //默认透明
shadowBlur: 5
},
itemStyle: {
normal: {
color: 'auto',
borderColor: '#000',
borderWidth: 0,
borderType: 'solid',
//shadowBlur: ...,
//shadowColor: ...,
shadowOffsetX: 0,
shadowOffsetY: 0
//opacity: ...,
},
emphasis: {
//color: 自适应,
borderColor: '#000',
borderWidth: 0,
borderType: 'solid',
//shadowBlur: ...,
//shadowColor: ...,
shadowOffsetX: 0,
shadowOffsetY: 0
//opacity: ...,
}
},
detail: {formatter: '{value}%',
offsetCenter:[0,'65%'],
textStyle: {
fontSize: 20
}
},
data:[
{name:'完成率',
value:FirstGaugeDataEncapsulation_1.getDatas()[0].value}
]
}]
});
}();
window.addEventListener("resize",function(){
myChart_1.resize();
});
};
function initAreaOrEmpQtyEcahrts(){
let readJSONFile = function(url){
let jsonData;
$.ajax({
type : 'get',
url : url,
async : false,
dataType : 'json',
data : null,
success : function(response){
jsonData = response;
}
})
return jsonData;
};
/**
*
* 数组最小值
*
**/
Array.prototype.min = function() {
let min = this[0];
let len = this.length;
for (let i = 1; i < len; i++){
if (this[i] < min){
min = this[i];
}
}
return min;
}
/**
*
* 数组最大值
*
**/
Array.prototype.max = function() {
let max = this[0];
let len = this.length;
for (let i = 1; i < len; i++){
if (this[i] > max) {
max = this[i];
}
}
return max;
}
//http://localhost:8080/pentaho/plugin/cda/api/doQuery?path=/public/dashboard/StoreOperation/StoreOperation.cda&dataAccessId=areaOrEmpQtyEffectiveQuery¶mstartDay=startDay¶mendDay=endDay¶mbrandParam=brandParam¶mplaceParam=placeParam¶marea1Param=area1Param¶marea2Param=area2Param¶marea3Param=area3Param¶mshopParam=shopParam¶moutletParam=outletParam
let urlAreaOrEmpQty = "/pentaho/plugin/cda/api/doQuery?path=/public/dashboard/StoreOperation/StoreOperation.cda&dataAccessId=areaOrEmpQtyEffectiveQuery";
urlAreaOrEmpQty += '¶mstartDay=' + startDay + '¶mendDay=' + endDay + '¶mbrandParam=' + brandParam + '¶mplaceParam=' + placeParam + '¶marea1Param=' + area1Param + '¶marea2Param=' + area2Param + '¶marea3Param=' + area3Param + '¶mshopParam=' + shopParam + '¶moutletParam=' + outletParam;
let getAreaOrEmpQtyJSON = readJSONFile(urlAreaOrEmpQty).resultset;
let AreaOrEmpQtyChart = echarts.init(document.getElementById('areaOrEmpQtyEffectiveDom'));
let colors = ['#0055B8','#FF9E16','#009BDE','#71A087'];
let legends = ['门店总人效','门店总坪效'];
let ShowAreaOrEmpQtyEcharts = function(){
AreaOrEmpQtyChart.setOption({
color: colors,
/*
tooltip: {
trigger: 'item', // 触发类型,默认数据触发,见下图,可选为:'item' ¦ 'axis'
showDelay: 20, // 显示延迟,添加显示延迟可以避免频繁切换,单位ms
hideDelay: 100, // 隐藏延迟,单位ms
transitionDuration : 0.4, // 动画变换时间,单位s
backgroundColor: 'rgba(0,0,0,0.7)', // 提示背景颜色,默认为透明度为0.7的黑色
borderColor: '#333', // 提示边框颜色
borderRadius: 4, // 提示边框圆角,单位px,默认为4
borderWidth: 0, // 提示边框线宽,单位px,默认为0(无边框)
padding: 5, // 提示内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
axisPointer : { // 坐标轴指示器,坐标轴触发有效
type : 'line', // 默认为直线,可选为:'line' | 'shadow'
lineStyle : { // 直线指示器样式设置
color: '#48b',
width: 2,
type: 'solid'
},
shadowStyle : { // 阴影指示器样式设置
width: 'auto', // 阴影大小
color: 'rgba(150,150,150,0.3)' // 阴影颜色
}
},
textStyle: {
color: '#fff'
}
},
*/
tooltip: {
trigger: 'axis',
backgroundColor: '#ffffff',
transitionDuration : 0.4,
borderWidth: 1,
borderColor: '#ccc',
textStyle: {
color: '#4d4d4d',
fontFamily: 'TPF_Font_Thin',
fontSize: 14
},
axisPointer: {
type: 'cross'
}
},
grid: {
//right: '20%'
//x: 100,
//y1: 500,
//y2: 500
},
toolbox: {
show: true,
feature: {
dataZoom: {
yAxisIndex: 'none'
},
dataView: {show: false, readOnly: false},
magicType: {type: ['line', 'bar', 'stack', 'tiled']},
restore: {show: true},
saveAsImage: {show: true}
}
},
legend: {
data:legends.map((value, index, arr)=>{
let newArr = [];
newArr.push({
icon : 'circle',
name: value
});
//console.log(newArr[0]);
return newArr[0];
//return value[0];
}),
itemHeight:18,
itemWidth: 18,
itemGap: 5,
itemWidth: 10,
itemHeight: 10,
textStyle: {
fontWeight: 'lighter',
fontSize: 7,
fontFamily: 'TPF_Font_Thin'
//color:'#fff'
},
inactiveColor:'#aaa',
padding: [
5, // 上
10, // 右
35, // 下
10, // 左
],
shadowColor: 'rgba(0, 0, 0, 0.5)',
shadowBlur: 5,
zlevel: 100
},
xAxis: [
{
type: 'category',
axisTick: {
alignWithLabel: true
},
data: getAreaOrEmpQtyJSON.map((value, index, arr)=>{
return value[0];
})
}
],
yAxis: [
{
type: 'value',
name: legends[0],
min: 0,
max: getAreaOrEmpQtyJSON.map((value, index, arr)=>{
return value[2];
}).max(),
position: 'left',
interval: Math.ceil(getAreaOrEmpQtyJSON.map((value, index, arr)=>{
return value[2];
}).max() / 3),
axisLine: {
show: false,
lineStyle: {
color: colors[0]
}
},
axisTick : { // 轴标记
show:false,
length: 10,
lineStyle: {
color: 'green',
type: 'solid',
width: 2
}
},
splitLine : {
show:false,
lineStyle: {
color: '#483d8b',
type: 'dotted',
width: 2
}
},
axisLabel: {
//formatter: '{value}'
formatter: function (v) {
if( v < 1000000 && v >= 1000 ){
return Math.ceil(v/1000) + 'K';
}else if( v >= 1000000 ){
return Math.ceil(v/1000000) + 'M';
}else if( v < 1000 && v >= 0 ){
return (v/1000).toFixed(1) + 'K';
}
}
}
},
{
type: 'value',
name: legends[1],
min: 0,
max: getAreaOrEmpQtyJSON.map((value, index, arr)=>{
return value[1];
}).max(),
position: 'right',
interval: Math.ceil(getAreaOrEmpQtyJSON.map((value, index, arr)=>{
return value[1];
}).max() / 3),
axisLine: {
show: false,
lineStyle: {
color: colors[1]
}
},
axisTick : { // 轴标记
show:false,
length: 10,
lineStyle: {
color: 'green',
type: 'solid',
width: 2
}
},
splitLine : {
show:false,
lineStyle: {
color: '#483d8b',
type: 'dotted',
width: 2
}
},
axisLabel: {
formatter: function (v) {
if( v < 1000000 && v >= 1000 ){
return Math.ceil(v/1000) + 'K';
}else if( v >= 1000000 ){
return Math.ceil(v/1000000) + 'M';
}else if( v < 1000 && v >= 0 ){
return (v/1000).toFixed(1) + 'K';
}
}
}
}
],
series: [
{
name:legends[0],
type:'bar',
data: getAreaOrEmpQtyJSON.map((value, index, arr)=>{
return value[2];
})
},
{
name:legends[1],
type:'bar',
yAxisIndex: 1,
data: getAreaOrEmpQtyJSON.map((value, index, arr)=>{
return value[1];
})
}
]
})
}();
window.addEventListener("resize",function(){
AreaOrEmpQtyChart.resize();
});
} | mit |
0704681032/Java8InAction | 清华大学邓俊辉老师数据结构资料/dsa/src/_java/dsa/vector_array.java | 2145 | /******************************************************************************************
* Data Structures in C++
* ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3
* Junhui DENG, deng@tsinghua.edu.cn
* Computer Science & Technology, Tsinghua University
* Copyright (c) 2006-2013. All rights reserved.
******************************************************************************************/
/*
* »ùÓÚÊý×éµÄÏòÁ¿ÊµÏÖ
*/
package dsa;
public class Vector_Array implements Vector {
private final int N = 1024;//Êý×éµÄÈÝÁ¿
private int n = 0;//ÏòÁ¿µÄʵ¼Ê¹æÄ£
private Object[] A;//¶ÔÏóÊý×é
//¹¹Ô캯Êý
public Vector_Array() {
A = new Object[N];
n = 0;
}
//·µ»ØÏòÁ¿ÖÐÔªËØÊýÄ¿
public int getSize() { return n; }
//ÅжÏÏòÁ¿ÊÇ·ñΪ¿Õ
public boolean isEmpty() { return (0 == n) ? true : false; }
//È¡ÖÈΪrµÄÔªËØ
public Object getAtRank(int r)//O(1)
throws ExceptionBoundaryViolation {
if (0 > r || r >= n) throw new ExceptionBoundaryViolation("ÒâÍ⣺ÖÈÔ½½ç");
return A[r];
}
//½«ÖÈΪrµÄÔªËØÌæ»»Îªobj
public Object replaceAtRank(int r, Object obj)
throws ExceptionBoundaryViolation {
if (0 > r || r >= n) throw new ExceptionBoundaryViolation("ÒâÍ⣺ÖÈÔ½½ç");
Object bak = A[r];
A[r] = obj;
return bak;
}
//²åÈëobj£¬×÷ΪÖÈΪrµÄÔªËØ£»·µ»Ø¸ÃÔªËØ
public Object insertAtRank(int r, Object obj)
throws ExceptionBoundaryViolation {
if (0 > r || r > n) throw new ExceptionBoundaryViolation("ÒâÍ⣺ÖÈÔ½½ç");
if (n >= N) throw new ExceptionBoundaryViolation("ÒâÍ⣺Êý×éÒç³ö");
for (int i = n; i > r; i--) A[i] = A[i-1]; //ºóÐøÔªËØË³´ÎºóÒÆ
A[r] = obj;//²åÈë
n++;//¸üе±Ç°¹æÄ£
return obj;
}
//ɾ³ýÖÈΪrµÄÔªËØ
public Object removeAtRank(int r)
throws ExceptionBoundaryViolation {
if (0 > r || r >= n) throw new ExceptionBoundaryViolation("ÒâÍ⣺ÖÈÔ½½ç");
Object bak = A[r];
for (int i = r; i < n; i++) A[i] = A[i+1]; //ºóÐøÔªËØË³´ÎÇ°ÒÆ
n--;//¸üе±Ç°¹æÄ£
return bak;
}
} | mit |
dewanee-es/tipi | tipi/js/markdown/plugins/markdown-it-container.js | 5174 | /*! markdown-it-container 2.0.0 https://github.com//markdown-it/markdown-it-container @license MIT */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.markdownitContainer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// Process block-level custom containers
//
'use strict';
module.exports = function container_plugin(md, name, options) {
function validateDefault(params) {
return params.trim().split(' ', 2)[0] === name;
}
function renderDefault(tokens, idx, _options, env, self) {
// add a class to the opening tag
if (tokens[idx].nesting === 1) {
tokens[idx].attrPush([ 'class', name ]);
}
return self.renderToken(tokens, idx, _options, env, self);
}
options = options || {};
var min_markers = 3,
marker_str = options.marker || ':',
marker_char = marker_str.charCodeAt(0),
marker_len = marker_str.length,
validate = options.validate || validateDefault,
render = options.render || renderDefault;
function container(state, startLine, endLine, silent) {
var pos, nextLine, marker_count, markup, params, token,
old_parent, old_line_max,
auto_closed = false,
start = state.bMarks[startLine] + state.tShift[startLine],
max = state.eMarks[startLine];
// Check out the first character quickly,
// this should filter out most of non-containers
//
if (marker_char !== state.src.charCodeAt(start)) { return false; }
// Check out the rest of the marker string
//
for (pos = start + 1; pos <= max; pos++) {
if (marker_str[(pos - start) % marker_len] !== state.src[pos]) {
break;
}
}
marker_count = Math.floor((pos - start) / marker_len);
if (marker_count < min_markers) { return false; }
pos -= (pos - start) % marker_len;
markup = state.src.slice(start, pos);
params = state.src.slice(pos, max);
if (!validate(params)) { return false; }
// Since start is found, we can report success here in validation mode
//
if (silent) { return true; }
// Search for the end of the block
//
nextLine = startLine;
for (;;) {
nextLine++;
if (nextLine >= endLine) {
// unclosed block should be autoclosed by end of document.
// also block seems to be autoclosed by end of parent
break;
}
start = state.bMarks[nextLine] + state.tShift[nextLine];
max = state.eMarks[nextLine];
if (start < max && state.sCount[nextLine] < state.blkIndent) {
// non-empty line with negative indent should stop the list:
// - ```
// test
break;
}
if (marker_char !== state.src.charCodeAt(start)) { continue; }
if (state.sCount[nextLine] - state.blkIndent >= 4) {
// closing fence should be indented less than 4 spaces
continue;
}
for (pos = start + 1; pos <= max; pos++) {
if (marker_str[(pos - start) % marker_len] !== state.src[pos]) {
break;
}
}
// closing code fence must be at least as long as the opening one
if (Math.floor((pos - start) / marker_len) < marker_count) { continue; }
// make sure tail has spaces only
pos -= (pos - start) % marker_len;
pos = state.skipSpaces(pos);
if (pos < max) { continue; }
// found!
auto_closed = true;
break;
}
old_parent = state.parentType;
old_line_max = state.lineMax;
state.parentType = 'container';
// this will prevent lazy continuations from ever going past our end marker
state.lineMax = nextLine;
token = state.push('container_' + name + '_open', 'div', 1);
token.markup = markup;
token.block = true;
token.info = params;
token.map = [ startLine, nextLine ];
state.md.block.tokenize(state, startLine + 1, nextLine);
token = state.push('container_' + name + '_close', 'div', -1);
token.markup = state.src.slice(start, pos);
token.block = true;
state.parentType = old_parent;
state.lineMax = old_line_max;
state.line = nextLine + (auto_closed ? 1 : 0);
return true;
}
md.block.ruler.before('fence', 'container_' + name, container, {
alt: [ 'paragraph', 'reference', 'blockquote', 'list' ]
});
md.renderer.rules['container_' + name + '_open'] = render;
md.renderer.rules['container_' + name + '_close'] = render;
};
},{}]},{},[1])(1)
});
| mit |
stfalcon-studio/rock-events | src/AppBundle/Tests/Entity/RequestManagerTest.php | 2453 | <?php
namespace AppBundle\Tests\Entity;
use AppBundle\DBAL\Types\RequestManagerStatusType;
use AppBundle\Entity\RequestManager;
use AppBundle\Entity\RequestManagerGroup;
use Doctrine\Common\Collections\ArrayCollection;
/**
* RequestRightTest class
*
* @author Yevgeniy Zholkevskiy <blackbullet@i.ua>
*/
class RequestManagerTest extends \PHPUnit_Framework_TestCase
{
/**
* Test an empty Request Manager entity
*/
public function testEmptyRequestManager()
{
$requestManager = new RequestManager();
$this->assertNull($requestManager->getId());
$this->assertNull($requestManager->getRequestManagerGroups());
$this->assertNull($requestManager->getFullName());
$this->assertNull($requestManager->getPhone());
}
/**
* Test setter and getter for Text
*/
public function testSetGetText()
{
$text = 'Some text';
$requestManager = (new RequestManager())->setText($text);
$this->assertEquals($text, $requestManager->getText());
}
/**
* Test setter and getter for fullName
*/
public function testSetGetFullName()
{
$fullName = 'Some fullName';
$requestManager = (new RequestManager())->setFullName($fullName);
$this->assertEquals($fullName, $requestManager->getFullName());
}
/**
* Test setter and getter for Phone
*/
public function testSetGetPhone()
{
$phone = 'Some phone';
$requestManager = (new RequestManager())->setPhone($phone);
$this->assertEquals($phone, $requestManager->getPhone());
}
/**
* Test setter and getter for Status
*/
public function testSetGetStatus()
{
$status = RequestManagerStatusType::SENT;
$requestManager = (new RequestManager())->setStatus($status);
$this->assertEquals($status, $requestManager->getStatus());
}
/**
* Test getter for Request Manager Group collection
*/
public function testGetSetRequestManagerGroupCollection()
{
$requestManagerGroups = new ArrayCollection();
$requestManagerGroups->add(new RequestManagerGroup());
$requestManager = (new RequestManager())->setRequestManagerGroups($requestManagerGroups);
$this->assertEquals(1, $requestManager->getRequestManagerGroups()->count());
$this->assertEquals($requestManagerGroups, $requestManager->getRequestManagerGroups());
}
}
| mit |
hirtie-maxim/gulp-runner | lib/gulp-runner/gulp.rb | 590 | module GulpRunner
class Gulp
def self.list
`#{gulp} --cwd #{cwd} --tasks`
end
def self.run(task_name = "default")
`#{gulp} --cwd #{cwd} #{task_name}`
end
private
def self.gulp_file_path
GulpRunner.gulp_file_path
end
def self.cwd
GulpRunner.node_modules_path
end
def self.gulp
begin
gulp = CommandUtils.get_command('gulp')
rescue
$stderr.puts ["Gulp.js not found! You can install Gulp.js using Node and npm:",
"$ npm install gulp -g",
"For more info see http://gulpjs.com/"].join("\n")
end
end
end
end | mit |
PhilipDaniels/Lithogen | Lithogen.Examples/Gitcheatsheet/scripts/consoleshim.js | 742 | // Avoid `console` errors in browsers that lack a console.
(function () {
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
| mit |
garywong89/phase-0 | week-9/ruby-review-1/ruby-review.rb | 6401 | # Cipher Challenge
# I worked on this challenge by myself.
# I spent [3.5] hours on this challenge.
# 1. Solution
# Write your comments on what each thing is doing.
# If you have difficulty, go into IRB and play with the methods.
def dr_evils_cipher(coded_message)
input = coded_message.downcase.split("") # Check out this method in IRB to see how it works! Also refer to the Ruby docs. # Takes a string and converts them all to be lower case and splits in into individual chars to store into input
decoded_sentence = [] # Creates a blank array called decoded_sentence
# Uses the a hash to store every letter in the array to have the value of another letter
cipher = {"e" => "a", # This is technically a shift of four letters...Can you think of a way to automate this? Is a hash
"f" => "b", # the best data structure for this problem? What are the pros and cons of hashes? You can shift it by illterating though a function. Pros: you know what each value is immediately. Cons Having to enter each value individually.
"g" => "c",
"h" => "d",
"i" => "e",
"j" => "f",
"k" => "g",
"l" => "h",
"m" => "i",
"n" => "j",
"o" => "k",
"p" => "l",
"q" => "m",
"r" => "n",
"s" => "o",
"t" => "p",
"u" => "q",
"v" => "r",
"w" => "s",
"x" => "t",
"y" => "u",
"z" => "v",
"a" => "w",
"b" => "x",
"c" => "y",
"d" => "z"}
input.each do |x| # What is #each doing here? # #each is running through every index in the input array
found_match = false # Why would this be assigned to false from the outset? What happens when it's true? # Assigns a value of false as default to finding a match
cipher.each_key do |y| # What is #each_key doing here? # runs through each hash key inside cipher.
if x == y # What is this comparing? Where is it getting x? Where is it getting y? What are those variables really? # comparing to see if the x value in input is equal to the key in cipher. Those variables are the index inside the array and the hash comparer.
decoded_sentence << cipher[y] #push the y key value into decoded sentence
found_match = true # Makes value True
break # Why is it breaking here? #leves the cipher loop.
elsif x == "@" || x == "#" || x == "$" || x == "%"|| x == "^" || x == "&"|| x =="*" #What the heck is this doing? Checking to see if any of the special character is added in the secret code and replacing it as a space bar.
decoded_sentence << " "
found_match = true
break
elsif (0..9).to_a.include?(x) # Try this out in IRB. What does " (0..9).to_a " do?
decoded_sentence << x #Returns back the original value if the numbers 0 through 9 appear
found_match = true
break
end
end
if not found_match # What is this looking for? Checks to see if we decode the sentence and retrun the x into the array decoded_sentence
decoded_sentence << x
end
end
decoded_sentence = decoded_sentence.join("")
#What is this method returning? The method is returning the array of decoded_sentence that has been joined to make a string.
end
# Your Refactored Solution
def dr_evils_cipher(coded_message)
message = coded_message.downcase.split("") #[a,c,d,e,h]
decoded_sentence = []
cipher = {}
shift_down = 4 # "e" => "a",
shift_up = 22 # "a" => "w",
letterbase = 10
while letterbase <= 35
if letterbase < 14
new_letter = letterbase + shift_up
cipher[letterbase.to_s(36)] = new_letter.to_s(36)
else
new_letter = letterbase - shift_down
cipher[letterbase.to_s(36)] = new_letter.to_s(36)
end
letterbase += 1
end
message.each do |letter|
found_match = false
cipher.each do |convert_key, switch_value|
if letter == convert_key
decoded_sentence << switch_value
found_match = true
break
elsif letter.match /[@#$%^&*]/
decoded_sentence << " "
found_match = true
break
elsif letter.is_a? Integer
found_match = true
decoded_sentence << letter
break
end
end
if (found_match == false)
decoded_sentence << letter
end
end
decoded_sentence = decoded_sentence.join("")
end
# Driver Test Code:
p dr_evils_cipher("m^aerx%e&gsoi!")
p dr_evils_cipher("m^aerx%e&gsoi!") == "i want a coke!" #This is driver test code and should print true
# Find out what Dr. Evil is saying below and turn it into driver test code as well. Driver test code statements should always return "true."
p dr_evils_cipher("syv%ievpc#exxiqtxw&ex^e$xvegxsv#fieq#airx%xlvsykl$wizivep#tvitevexmsrw.#tvitevexmsrw#e*xlvsykl#k&aivi%e@gsqtpixi&jempyvi.
&fyx%rsa,$pehmiw@erh#kirxpiqir,%ai%jmreppc@lezi&e&asvomrk%xvegxsv#fieq,^almgl^ai^wlepp%gepp@tvitevexmsr^l")
p dr_evils_cipher("csy&wii,@m'zi@xyvrih$xli*qssr$mrxs&alex@m#pmoi%xs#gepp%e^hiexl#wxev.")
p dr_evils_cipher("qmrm#qi,*mj^m#iziv^pswx#csy#m^hsr'x%orsa^alex@m%asyph^hs.
@m'h%tvsfefpc%qszi$sr%erh*kix#ersxliv$gpsri@fyx*xlivi@asyph^fi@e^15&qmryxi@tivmsh%xlivi$alivi*m*asyph&nywx^fi$mrgsrwspefpi.")
p dr_evils_cipher("alc@qeoi*e$xvmppmsr^alir#ai*gsyph%qeoi...#fmppmsrw?")
# Reflection
# Keep your reflection limited to 10-15 minutes!
=begin
What concepts did you review in this challenge?
I reviewed how to convert letters into different characters. I reviewed how to use regex, and working with loops.
What is still confusing to you about Ruby?
Letter bases was confusing initially but working through this problem helped me understand it better.
The wording of the original code was confusing breaking each part down helped me find out which part was necessary or unnecessary.
What are you going to study to get more prepared for Phase 1?
I think reviewing this challenge helped me study a lot more than I was expecting.
This challenge was suppose to be optional pairing for but I did it as a solo and ended up taking stuck on it longer than I had wished.
It helped me understand which sections I understood well and also find other methods of converting letters.
=end | mit |
alChaCC/mongoid_sortable_tree | test/test_helper.rb | 1283 | # Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../test/dummy/config/environment.rb", __FILE__)
require "rails/test_help"
require 'mongoid'
require 'mongoid/tree'
require "minitest/rails"
require 'simplecov'
require "minitest/rails/capybara"
SimpleCov.start 'rails'
require "minitest/reporters"
Minitest::Reporters.use! [Minitest::Reporters::DefaultReporter.new(:color => true)]
# Filter out Minitest backtrace while allowing backtrace from other libraries
# to be shown.
Minitest.backtrace_filter = Minitest::BacktraceFilter.new
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
ActiveSupport::TestCase.fixtures :all
end
Mongoid.load!("test/dummy/config/mongoid.yml", Rails.env.to_sym)
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
class ActiveSupport::TestCase
include FactoryGirl::Syntax::Methods
teardown :clean_mongodb
def clean_mongodb
Mongoid.purge!
end
end | mit |
xnuter/java-spring-angular-material-seed | src/main/frontend/src/app/scripts/dashboard/controllers/ConversionController.js | 1342 | (function () {
'use strict';
angular
.module('app')
.controller('ConversionController', [
ConversionController
]);
function ConversionController() {
var ctrl = this;
// actually we need to request it from the server
// not in the scope of this template
var premium = 11;
ctrl.conversionChartData = [ {key: 'Premium', y: premium}, { key: 'Free', y: 100 - premium} ];
ctrl.chartOptions = {
chart: {
type: 'pieChart',
height: 270,
donut: true,
pie: {
startAngle: function (d) { return d.startAngle/2 -Math.PI/2 },
endAngle: function (d) { return d.endAngle/2 -Math.PI/2 }
},
x: function (d) { return d.key; },
y: function (d) { return d.y; },
valueFormat: (d3.format(".0f")),
color: ['#1976D2', '#B6B6B6'],
showLabels: false,
showLegend: false,
tooltips: false,
title: premium + '%',
titleOffset: 10,
duration: 1000,
margin: { top: 20, bottom: -140, right: -30, left: -30}
}
};
return ctrl;
}
})();
| mit |
baoky2/EQcoin | src/init.cpp | 43190 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013 eqcoin developers
// Copyright (c) 2014 EQcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#define GLOBALDEFINED
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "checkpoints.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
// Used to pass flags to the Bind() function
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1)
};
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
static CCoinsViewDB *pcoinsdbview;
void Shutdown()
{
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) return;
RenameThread("bitcoin-shutoff");
nTransactionsUpdated++;
StopRPCThreads();
bitdb.Flush(false);
StopNode();
{
LOCK(cs_main);
if (pwalletMain)
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
if (pblocktree)
pblocktree->Flush();
if (pcoinsTip)
pcoinsTip->Flush();
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pblocktree; pblocktree = NULL;
}
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
delete pwalletMain;
}
//
// Signal handlers are very limited in what they are allowed to do, so:
//
void DetectShutdownThread(boost::thread_group* threadGroup)
{
// Tell the main threads to shutdown.
while (!fRequestShutdown)
{
MilliSleep(200);
if (fRequestShutdown)
threadGroup->interrupt_all();
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
fillz();
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/eqcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to eqcoind / RPC client
std::string strUsage = _("EQcoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" eqcoind [options] " + "\n" +
" eqcoind [options] <command> [params] " + _("Send command to -server or eqcoind") + "\n" +
" eqcoind [options] help " + _("List commands") + "\n" +
" eqcoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "eqcoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !defined(WIN32)
fDaemon = GetBoolArg("-daemon");
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect eqcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: eqcoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: eqcoind.pid)") + "\n" +
" -gen " + _("Generate coins (default: 0)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 9007 or testnet: 19007)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 9008 or testnet: 19008)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
#ifndef QT_GUI
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
#endif
" -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" +
" -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" +
" -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" +
" -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the eqcoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("bitcoin-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
FILE *file = OpenBlockFile(pos, true);
if (!file)
break;
printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
printf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
printf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
printf("Importing %s...\n", path.string().c_str());
LoadExternalBlockFile(file);
}
}
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
{
return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
}
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
fTestNet = GetBoolArg("-testnet");
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
fBenchmark = GetBoolArg("-benchmark");
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", 0);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps");
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-mintxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
}
if (mapArgs.count("-minrelaytxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
{
if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
return InitError(_("Unable to sign checkpoint, wrong checkpointkey?"));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
// Make sure only a single eqcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. eqcoin is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("EQcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Using data directory %s\n", strDataDir.c_str());
printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "EQcoin server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
int64 nStart;
// ********************************************************* Step 5: verify wallet database integrity
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
return false;
}
if (filesystem::exists(GetDataDir() / "wallet.dat"))
{
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("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."), strDataDir.c_str());
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9070);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9070);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
bool fBound = false;
if (!fNoListen) {
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
#endif
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load block chain
fReindex = GetBoolArg("-reindex");
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = GetArg("-dbcache", 25) << 20;
if (nTotalCache < (1 << 22))
nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex)
pblocktree->WriteReindexing(true);
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (!VerifyDB()) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
return false;
}
} else {
return InitError(strLoadError);
}
}
}
if (mapArgs.count("-txindex") && fTxIndex != GetBoolArg("-txindex", false))
return InitError(_("You need to rebuild the databases using -reindex to change -txindex"));
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Step 8: load wallet
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet("wallet.dat");
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of EQcoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart EQcoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ConnectBestBlock(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
StartNode(threadGroup);
if (fServer)
StartRPCThreads();
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
return !fRequestShutdown;
}
| mit |
victorwins/techan.js | test/spec/bundle/_fixtures/data/atrtrailingstop.js | 581 | module.exports = {
plot: [
{ date: new Date("2014-03-05"), up: 2, down: null },
{ date: new Date("2014-03-06"), up: null, down: 3 }
],
input: require('./ohlc').facebook.slice(31, 50),
expected: [
{ date: new Date(2012, 6, 24), up: 25.20357142857143, down: null },
{ date: new Date(2012, 6, 25), up: 26.023316326530615, down: null },
{ date: new Date(2012, 6, 26), up: 26.023316326530615, down: null },
{ date: new Date(2012, 6, 27), up: null, down: 28.068416024573093 },
{ date: new Date(2012, 6, 30), up: null, down: 27.413529165675012 }
]
}; | mit |
totem/cluster-deployer | deployer/tasks/__init__.py | 109 | from deployer.celery import app
@app.task
def backend_cleanup():
app.tasks['celery.backend_cleanup']()
| mit |
xuru/pyvisdk | pyvisdk/do/host_parallel_scsi_hba.py | 1083 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def HostParallelScsiHba(vim, *args, **kwargs):
'''The ParallelScsiHba data object type describes a parallel SCSI host bus
adapter.'''
obj = vim.client.factory.create('ns0:HostParallelScsiHba')
# do some validation checking...
if (len(args) + len(kwargs)) < 4:
raise IndexError('Expected at least 5 arguments got: %d' % len(args))
required = [ 'bus', 'device', 'model', 'status' ]
optional = [ 'driver', 'key', 'pci', 'dynamicProperty', 'dynamicType' ]
for name, arg in zip(required+optional, args):
setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
| mit |
afton77/p2e-lib-dev | assets/angular-javantech/register.js | 2908 | 'use strict';
var myJavanTech = angular.module('myJavanTech', ['ui.bootstrap', 'ngFileUpload', 'ngDialog', 'ngRoute']);
/**
*
* @param int ID
* @param object form
*/
myJavanTech.factory("registerServicesJT", ['$http', function ($http) {
var serviceBase = 'http://localhost:7777/p2e-lib-dev/';
var obj = {};
/**
* Submit Register
* @param JSON data
* @returns JSON
*/
obj.submitRegister = function (data) {
return $http.post(serviceBase + 'register/register', data);
};
obj.checkEmail = function (data) {
return $http.post(serviceBase + 'register/check_email', data);
};
return obj;
}]);
/**
*
* @param int ID
* @param object form
*/
myJavanTech.controller('registerController', ['$scope', '$http', '$log', 'ngDialog', '$location', 'registerServicesJT', '$window', function ($scope, $http, $log, ngDialog, $location, registerServicesJT, $window) {
$scope.register = function (event) {
$scope.rRegister = "";
var data = {
fName: $scope.txtName || "",
lName: $scope.txtLastName || "",
email: $scope.txtEmail || "",
email2: $scope.txtEmail2 || "",
password: $scope.txtPassword || "",
instansi: $scope.txtInstansi || "",
address: $scope.txtAddress || ""
};
registerServicesJT.submitRegister(data).then(function (r) {
console.log(r);
// if (r.data.r) {
// $window.location = "http://localhost:7777/p2e-lib-dev/admins";
// } else {
// $scope.rRegister = "Maaf, email atau password Anda salah !";
// }
});
};
$scope.checkEmail = function (r) {
var data = {
email: $scope.txtEmail || ""
};
// console.log(data);
registerServicesJT.checkEmail(data).then(function (r) {
console.log(r.data.result);
if (r.data.result == false) {
$scope.validateEmail = "Surel/email Anda sudah terdaftar di sistem.";
} else {
$scope.validateEmail = "";
}
});
};
$scope.matchEmail = function (r){
if ($scope.txtEmail != $scope.txtEmail2){
$scope.validateMatchEMail = "Surel/email Anda tidak sama.";
} else {
$scope.validateMatchEMail = "";
}
}
$scope.eRegister = function (event) {
if (event.keyCode === 13) {
$scope.rRegister = "";
var data = {
email: $scope.txtEmail || "",
password: $scope.txtPassword || ""
};
registerServicesJT.submitRegister(data).then(function (r) {
if (r.data.r) {
$window.location = "http://localhost:7777/p2e-lib-dev/admins";
} else {
$scope.rRegister = "Maaf, email atau password Anda salah !";
}
});
}
};
$scope.reset = function (event) {
$scope.rRegister = "";
};
}]);
| mit |
jubianchi/neutron | lib/downloaders/local/release.js | 383 | import path from "path";
import fs from "fs";
export default class LocalReleaseDownloader {
constructor(dir) {
this.dir = dir;
}
async download(app, release, name) {
return async ctx => {
ctx.attachment("update.zip");
ctx.body = await fs.createReadStream(path.join(this.dir, app.name, release.version, name));
};
}
}
| mit |
yuxiang-zhou/MarketAnalysor | AngularJSClient/public/scripts/directives/header/header.js | 320 | 'use strict';
/**
* @ngdoc directive
* @name izzyposWebApp.directive:adminPosHeader
* @description
* # adminPosHeader
*/
angular.module('marketApp')
.directive('header',function(){
return {
templateUrl:'scripts/directives/header/header.html',
restrict: 'E',
replace: true,
}
});
| mit |
absunstar/isite | lib/routing.js | 52076 | module.exports = function init(____0) {
____0.on(____0.strings[4], (_) => {
if (!_) {
_0xrrxo.list = [];
}
});
let _0xrrxo = function () {};
_0xrrxo.list = [];
_0xrrxo.endResponse = function (req, res) {
let route = req.route;
if (route.empty) {
if (____0.options.help) {
res.set('help-error-message', 'route is empty');
}
res.end();
return;
}
if (route.parser.like('*html*') && route.content && route.content.length > 0) {
req.content = ____0.parser(req, res, ____0, route).html(route.content);
} else if (route.parser == 'css' && route.content && route.content.length > 0) {
req.content = ____0.parser(req, res, ____0, route).css(route.content);
} else if (route.parser == 'js' && route.content && route.content.length > 0) {
req.content = ____0.parser(req, res, ____0, route).js(route.content);
} else {
req.content = route.content;
}
if (route.compress) {
req.content = req.content.replace(/\r?\n|\r/g, ' ').replace(/\s+/g, ' ');
}
route.path = route.path || '';
let encode = ____0.getFileEncode(route.path);
// let hash = req.content ? ____0.x0md50x(req.content) : ____0.x0md50x('');
let last_modified = new Date().toUTCString();
if (route.stat) {
last_modified = new Date(route.stat.mtimeMs).toUTCString();
}
// if (req.headers['if-none-match'] == hash) {
// if (____0.options.help) {
// res.set('help-info-message', 'etag matched');
// }
// // res.status(304).end(null);
// // return;
// }
// if (____0.options.help) {
// res.set('help-info-etag', hash);
// }
// res.set('ETag', hash);
if (____0.options.cache.enabled) {
res.set('Last-Modified', last_modified);
}
if (route.headers) {
for (const property in route.headers) {
res.set(property, route.headers[property]);
}
}
if (route.path.endsWith('.css')) {
res.set(____0.strings[7], 'text/css');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.css);
res.end(req.content, encode);
} else if (route.path.endsWith('.js')) {
res.set(____0.strings[7], 'application/javascript');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.js);
res.end(req.content, encode);
} else if (route.path.endsWith('.html')) {
res.set(____0.strings[7], 'text/html');
if (____0.options.cache.enabled && route.cache) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.html);
res.end(req.content, encode);
} else if (route.path.endsWith('.txt')) {
res.set(____0.strings[7], 'text/plain');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.txt);
res.end(req.content, encode);
} else if (route.path.endsWith('.json')) {
res.set(____0.strings[7], 'application/json');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.json);
res.end(req.content, encode);
} else if (route.path.endsWith('.xml')) {
res.set(____0.strings[7], 'text/xml');
if (____0.options.cache.enabled) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.xml);
}
res.end(req.content, encode);
} else if (route.path.endsWith('.woff2')) {
res.set(____0.strings[7], 'application/font-woff2');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
res.end(req.content, encode);
} else if (route.path.endsWith('.woff')) {
res.set(____0.strings[7], 'application/font-woff');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
res.end(req.content, encode);
} else if (route.path.endsWith('.ttf')) {
res.set(____0.strings[7], 'application/font-ttf');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
res.end(req.content, encode);
} else if (route.path.endsWith('.otf')) {
res.set(____0.strings[7], 'application/font-otf');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
res.end(req.content, encode);
} else if (route.path.endsWith('.eot')) {
res.set(____0.strings[7], 'application/font-eot');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
res.end(req.content, encode);
} else if (route.path.endsWith('.gif')) {
res.set(____0.strings[7], 'image/gif');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
res.end(req.content, encode);
} else if (route.path.endsWith('.png')) {
res.set(____0.strings[7], 'image/png');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
res.end(req.content, encode);
} else if (route.path.endsWith('.jpg')) {
res.set(____0.strings[7], 'image/jpg');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
res.end(req.content, encode);
} else if (route.path.endsWith('.jpeg')) {
res.set(____0.strings[7], 'image/jpeg');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
res.end(req.content, encode);
} else if (route.path.endsWith('.ico')) {
res.set(____0.strings[7], 'image/ico');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
res.end(req.content, encode);
} else if (route.path.endsWith('.bmp')) {
res.set(____0.strings[7], 'image/bmp');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
res.end(req.content, encode);
} else if (route.path.endsWith('.svg')) {
res.set(____0.strings[7], 'image/svg+xml');
if (____0.options.cache.enabled) res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
res.end(req.content, encode);
} else {
if (typeof req.content == 'object') {
res.json(req.content);
} else {
res.end(req.content, encode);
}
}
};
_0xrrxo.defaultCallback = function (req, res) {
let route = req.route;
if (route.cache && route.content) {
if (____0.options.help) {
res.set('help-info-content', 'From Route Memory');
}
res.status(200);
_0xrrxo.endResponse(req, res);
return;
}
if (route.empty) {
res.status(404);
_0xrrxo.endResponse(req, res);
return;
}
if (!route.path && !route.content) {
if (____0.options.help) {
res.set('help-info-content', 'Route Not Set File Path');
}
res.status(200);
_0xrrxo.endResponse(req, res);
return;
} else if (route.content) {
if (____0.options.help) {
res.set('help-info-content', 'Content From Route init');
}
res.status(200);
_0xrrxo.endResponse(req, res);
}
if (typeof route.path == 'string') {
____0.readFile(route.path, function (err, data, file) {
if (!err) {
route.content = data.toString('utf8');
if (route.encript && route.encript === '123') {
route.content = ____0.f1(route.content);
}
route.stat = file.stat;
if (route.masterPage) {
for (var i = 0; i < ____0.masterPages.length; i++) {
if (route.masterPage == ____0.masterPages[i].name) {
route.content = ____0.readFileSync(____0.masterPages[i].header) + route.content + ____0.readFileSync(____0.masterPages[i].footer);
break;
}
}
}
if (____0.options.help) {
res.set('help-info-content', 'Route Read File');
}
res.status(200);
_0xrrxo.endResponse(req, res);
} else {
if (____0.options.help) {
res.set('help-error', 'Route Error Read File');
}
res.status(404);
route.empty = !0;
_0xrrxo.endResponse(req, res);
return;
}
});
} else if (typeof route.path == 'object') {
____0.readFiles(route.path, function (err, data) {
if (!err) {
if (____0.options.help) {
res.set('help-info-content', 'Route Read Files');
}
route.content = data.toString('utf8');
if (route.encript && route.encript === '123') {
route.content = ____0.f1(route.content);
}
res.status(200);
route.path = route.path.join('&&');
_0xrrxo.endResponse(req, res);
} else {
if (____0.options.help) {
res.set('help-error', 'Route Error Read Files');
}
res.status(404);
route.empty = !0;
_0xrrxo.endResponse(req, res);
return;
}
});
}
};
_0xrrxo.call = function (r, req, res, callback) {
callback =
callback ||
function (req, res) {
console.log('No CallBack set For : ', r);
res.end();
};
if (typeof r === 'string') {
r = {
name: r,
method: req.method,
};
}
let exists = false;
_0xrrxo.list.forEach((rr) => {
if (exists) {
return;
}
if (rr.name == r.name && rr.method == r.method) {
exists = true;
req.route = rr;
rr.callback(req, res);
}
});
if (!exists) {
callback(req, res);
}
};
_0xrrxo.off = function (r) {
if (!r) {
return;
}
if (typeof r == 'string') {
r = { name: r };
}
for (let i = _0xrrxo.list.length; i--; ) {
let r0 = _0xrrxo.list[i];
if (r.name && r.method && r0.name.like(r.name) && r0.method.like(r.method)) {
_0xrrxo.list.splice(i, 1);
____0.fsm.off(r0.path);
} else if (r.name && r0.name.like(r.name)) {
_0xrrxo.list.splice(i, 1);
____0.fsm.off('*' + r0.name.replace('/', '') + '*');
____0.fsm.off(r0.path);
} else if (r.method && r0.method.like(r.method)) {
_0xrrxo.list.splice(i, 1);
____0.fsm.off(r0.path);
}
}
};
_0xrrxo.add = function (r, callback) {
if (Array.isArray(r)) {
r.forEach((r2) => {
_0xrrxo.add(r2, callback);
});
return;
}
if (r && r.name && Array.isArray(r.name)) {
r.name.forEach((r2) => {
let r3 = Object.assign({}, r);
r3.name = r2;
_0xrrxo.onGET(r3, r.callback);
});
return;
}
let route = {};
if (typeof r == 'string') {
route.name = r.toLowerCase();
route.name0 = r;
route.public = ____0.options.public || false;
route.method = 'GET';
route.path = null;
route.parser = 'static';
route.parserDir = ____0.dir;
route.cache = !0;
route.hide = !1;
route.compress = !1;
route.content = null;
route.headers = null;
route.map = [];
route.callback = callback ?? _0xrrxo.defaultCallback;
if (route.public) {
route.require = {
features: [],
permissions: [],
};
} else {
route.require = ____0.options.requires;
route.default = ____0.options.defaults;
}
} else {
route.name = r.name.toLowerCase();
route.name0 = r.name;
route.public = r.public ?? (____0.options.public || false);
route.method = r.method || 'GET';
route.path = r.path || null;
route.content = r.content;
route.headers = r.headers;
route.parser = r.parser || 'static';
route.parserDir = r.parserDir || ____0.dir;
route.masterPage = r.masterPage || null;
route.cache = r.cache ?? !0;
route.hide = r.hide ?? !1;
route.encript = r.encript;
route.compress = r.compress ?? !1;
route.map = r.map || [];
route.callback = callback || r.callback || _0xrrxo.defaultCallback;
if (route.public) {
route.require = {
features: [],
permissions: [],
};
} else {
route.require = r.require ?? ____0.options.requires;
route.require.features = route.require.features ?? ____0.options.requires.features;
route.require.permissions = route.require.permissions ?? ____0.options.requires.permissions;
route.default = r.default ?? ____0.options.defaults;
route.default.features = route.default.features ?? ____0.options.defaults.features;
route.default.permissions = route.default.permissions ?? ____0.options.defaults.permissions;
}
}
if (!route.name.startsWith('/')) {
route.name = '/' + route.name;
route.name0 = '/' + route.name0;
}
route.name = route.name.replace('//', '/');
route.name0 = route.name0.replace('//', '/');
let arr = route.name.split('/');
let arr0 = route.name0.split('/');
for (var i = 0; i < arr.length; i++) {
var s = arr[i];
var s0 = arr0[i];
if (s.startsWith(':')) {
arr[i] = '*';
let name = s.replace(':', '');
let name0 = s0.replace(':', '');
route.map.push({
index: i,
name: name,
isLower: !1,
});
if (name !== name0) {
route.map.push({
index: i,
name: name0,
isLower: !0,
});
}
}
}
try {
route.name = arr.join('/');
if (typeof route.path == 'string' && ____0.fs.lstatSync(route.path).isDirectory()) {
____0.fs.readdir(route.path, (err, files) => {
files.forEach((file) => {
let r2 = { ...route };
if (route.name.endsWith('/')) {
r2.name = route.name + file;
} else {
r2.name = route.name + '/' + file;
}
r2.path = route.path + '/' + file;
r2.is_dynamic = !0;
_0xrrxo.add(r2);
});
});
} else {
if (!route.name.startsWith('/')) {
route.name = '/' + route.name;
}
let exist = !1;
_0xrrxo.list.forEach((rr) => {
if (rr.name == route.name && rr.method == route.method) {
exist = !0;
}
});
if (!exist) {
_0xrrxo.list.push(route);
} else {
if (route.name.like('*api/*')) {
____0.log('[ Duplicate API ] ' + route.name);
} else {
____0.log('[ Duplicate Route ] ' + route.name + ' || ' + route.path);
}
}
}
} catch (err) {
____0.log(err);
return null;
}
};
_0xrrxo.onREQUEST = function (type, r, callback) {
if (Array.isArray(r)) {
r.forEach((r2) => {
_0xrrxo.onREQUEST(type, r2, callback);
});
return;
}
let route = {};
if (typeof r == 'string') {
route = {
name: r,
method: type,
callback: callback || _0xrrxo.defaultCallback,
};
} else {
route = r;
if (Array.isArray(r.name)) {
r.name.forEach((n) => {
let sub_route = { ...route };
sub_route.name = n;
_0xrrxo.onREQUEST(type, sub_route, callback);
});
return;
}
route.callback = route.callback || callback || _0xrrxo.defaultCallback;
}
route.method = type;
_0xrrxo.add(route);
};
_0xrrxo.onGET = function (r, callback) {
_0xrrxo.onREQUEST('GET', r, callback);
};
_0xrrxo.onPOST = function (r, callback) {
_0xrrxo.onREQUEST('POST', r, callback);
};
_0xrrxo.onPUT = function (r, callback) {
_0xrrxo.onREQUEST('PUT', r, callback);
};
_0xrrxo.onDELETE = function (r, callback) {
_0xrrxo.onREQUEST('DELETE', r, callback);
};
_0xrrxo.onTEST = function (r, callback) {
_0xrrxo.onREQUEST('TEST', r, callback);
};
_0xrrxo.onVIEW = function (r, callback) {
_0xrrxo.onREQUEST('VIEW', r, callback);
};
_0xrrxo.onOPTIONS = function (r, callback) {
_0xrrxo.onREQUEST('OPTIONS', r, callback);
};
_0xrrxo.onPATCH = function (r, callback) {
_0xrrxo.onREQUEST('PATCH', r, callback);
};
_0xrrxo.onCOPY = function (r, callback) {
_0xrrxo.onREQUEST('COPY', r, callback);
};
_0xrrxo.onHEAD = function (r, callback) {
_0xrrxo.onREQUEST('HEAD', r, callback);
};
_0xrrxo.onLINK = function (r, callback) {
_0xrrxo.onREQUEST('LINK', r, callback);
};
_0xrrxo.onUNLINK = function (r, callback) {
_0xrrxo.onREQUEST('UNLINK', r, callback);
};
_0xrrxo.onPURGE = function (r, callback) {
_0xrrxo.onREQUEST('PURGE', r, callback);
};
_0xrrxo.onLOCK = function (r, callback) {
_0xrrxo.onREQUEST('LOCK', r, callback);
};
_0xrrxo.onUNLOCK = function (r, callback) {
_0xrrxo.onREQUEST('UNLOCK', r, callback);
};
_0xrrxo.onPROPFIND = function (r, callback) {
_0xrrxo.onREQUEST('PROPFIND', r, callback);
};
_0xrrxo.onALL = _0xrrxo.onANY = function (r, callback) {
_0xrrxo.onREQUEST('*', r, callback);
};
_0xrrxo.handleRoute = async function (req, res, route) {
if (!route.public) {
if (!route.name.like(____0.strings[15]) && route.require.features.length > 0) {
let ok = !0;
route.require.features.forEach((feature) => {
if (!req.hasFeature(feature)) {
ok = !1;
}
});
if (!ok) {
res.status(401);
if (route.name.contains(____0.strings[16])) {
return res.json({
done: !1,
error: ____0.strings[13],
features: route.require.features,
});
} else
return res.render(
____0.strings[11],
{
features: route.require.features.join(','),
html: ` ${____0.strings[13]} : ${route.require.features.join(',')}`,
},
{
parser: ____0.strings[17],
},
);
}
}
if (!route.name.like(____0.strings[15]) && route.require.permissions.length > 0) {
let ok = !0;
route.require.permissions.forEach((permission) => {
if (!____0.security.isUserHasPermissions(req, res, permission)) {
ok = !1;
}
});
if (!ok) {
res.status(401);
if (route.name.contains(____0.strings[16])) {
return res.json({
done: !1,
error: ____0.strings[14],
permissions: route.require.permissions,
});
} else {
return res.render(
____0.strings[12],
{
permissions: route.require.permissions.join(','),
html: `${____0.strings[14]} : ${route.require.permissions.join(',')}`,
},
{
parser: ____0.strings[17],
},
);
}
}
}
}
route.callback(req, res);
};
_0xrrxo.handleServer = async function (req, res) {
req.obj = {};
req.query = {};
req.queryRaw = {};
req.data = req.body = {};
req.bodyRaw = '';
req.params = {};
req.paramsRaw = {};
req.features = [];
req.addFeature = function (name) {
req.features.push(name);
};
req.hasFeature = function (name) {
return req.features.some((f) => f.like(name));
};
req.removeFeature = function (name) {
req.features.forEach((f, i) => {
if (f.like(name)) {
req.features.splice(i, 1);
}
});
};
res.code = null;
req.acceptEncoding = req.headers[____0.strings[5]] ? req.headers[____0.strings[5]] : '';
res.ip = req.ip = req.headers[____0.strings[6]] ? req.headers[____0.strings[6]] : req.socket.remoteAddress.replace('::ffff:', '');
res.ip2 = req.ip2 = req.socket.localAddress.replace('::ffff:', '');
res.port = req.port = req.socket.remotePort;
res.port2 = req.port2 = req.socket.localPort;
res.cookies = res.cookie = req.cookies = req.cookie = ____0.cookie(req, res, ____0);
req.urlRaw = req.url;
req.urlParserRaw = ____0.url.parse(req.urlRaw, !0);
req.urlParser = ____0.url.parse(req.urlRaw.toLowerCase(), !0);
res.set = (a, b, c) => {
if (res.writeHeadEnabled === !1 || res.finished === !0 || res.headersSent) {
return res;
}
if (typeof b == 'string') {
res.headers = res.headers || [];
res.headers[a] = b.toLowerCase();
}
res.setHeader(a, b, c);
return res;
};
res.delete = res.remove = res.removeHeader;
res.writeHead0 = res.writeHead;
res.writeHeadEnabled = !0;
res.writeHead = (code, obj) => {
if (res.writeHeadEnabled === !1 || res.finished === !0) {
return res;
}
res.cookie.write();
res.writeHeadEnabled = !1;
res.writeHead0(code, obj);
return res;
};
res.ending = (time, ...data) => {
if (!time) {
time = 0;
}
setTimeout(function () {
res.end(...data);
}, time);
};
res.end0 = res.end;
res.end = function (arg1, arg2, arg3, arg4) {
if (typeof arg1 === 'number') {
res.writeHead(arg1);
return res.end0();
} else {
if (
arg1 &&
res.headers &&
res.headers[____0.strings[7]] &&
(res.headers[____0.strings[7]].like('*text/css*') ||
res.headers[____0.strings[7]].like('*application/javascript*') ||
res.headers[____0.strings[7]].like('*text/html*') ||
res.headers[____0.strings[7]].like('*text/plain*') ||
res.headers[____0.strings[7]].like('*application/json*'))
) {
if (req.acceptEncoding.match(/\bdeflate\b/) && typeof arg1 === 'string') {
res.set(____0.strings[8], 'deflate');
res.set('Vary', ____0.strings[5]);
arg1 = ____0.zlib.deflateSync(Buffer.from(arg1));
} else if (req.acceptEncoding.match(/\bgzip\b/) && typeof arg1 === 'string') {
res.set(____0.strings[8], 'gzip');
res.set('Vary', ____0.strings[5]);
arg1 = ____0.zlib.gzipSync(Buffer.from(arg1));
} else {
// ____0.log(typeof arg1)
}
}
if (res.headers === undefined || res.headers[____0.strings[7]] === undefined) {
res.set(____0.strings[7], 'text/plain');
}
res.writeHead(res.code || res.statusCode || 200);
arg1 = arg1 || ' ';
return res.end0(arg1, arg2, arg3, arg4);
}
};
res.status = (code) => {
if (!res.code) {
res.code = code || 200;
}
return res;
};
res.error = (code) => {
res.status(code || 404).end();
};
res.download2 = (path, name) => {
if (____0.isFileExistsSync(path)) {
var stat = ____0.fileStatSync(path);
if (stat && stat.isFile()) {
res.writeHead(200, {
'Content-Type': ____0.getContentType(path),
'Content-Length': stat.size,
'Content-Disposition': 'attachment; filename=' + (name || ____0.path.basename(path)),
});
var readStream = ____0.fs.createReadStream(path);
readStream.on('end', function () {
readStream.close();
});
res.on(____0.strings[10], function () {
readStream.close();
});
readStream.pipe(res);
} else {
res.error();
}
} else {
res.error();
}
};
res.download = function (path, name) {
if (____0.isFileExistsSync(path)) {
const stat = ____0.fileStatSync(path);
if (stat && stat.isFile()) {
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = end - start + 1;
const readStream = ____0.fs.createReadStream(path, {
start,
end,
});
readStream.on('end', function () {
readStream.close();
});
res.on(____0.strings[10], function () {
readStream.close();
});
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': ____0.getContentType(path),
});
readStream.pipe(res);
} else {
const readStream = ____0.fs.createReadStream(path);
readStream.on('end', function () {
readStream.close();
});
res.on(____0.strings[10], function () {
readStream.close();
});
res.writeHead(200, {
'Content-Length': fileSize,
'Content-Type': ____0.getContentType(path),
'Content-Disposition': 'attachment; filename=' + (name || ____0.path.basename(path)),
});
____0.fs.createReadStream(path).pipe(res);
}
} else {
res.error();
}
} else {
res.error();
}
};
res.html = res.render = function (name, _data, options) {
____0.fsm.getContent(name, (content) => {
if (!content) {
if (_data && _data.html) {
return res.status(404).htmlContent(_data.html);
} else {
return res.status(404).end();
}
}
options = options || {};
req.content = content;
req.data = { ...req.data, ..._data };
req.route = req.route || {};
req.route = { ...req.route, ...options };
if (req.route.parser) {
req.content = ____0.parser(req, res, ____0, req.route).html(req.content);
}
res.status(200);
if (req.route.compress) {
req.content = req.content.replace(/\r?\n|\r/g, ' ').replace(/\s+/g, ' ');
}
if (name.endsWith('.css')) {
res.set(____0.strings[7], 'text/css');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.css);
}
} else if (name.endsWith('.js')) {
res.set(____0.strings[7], 'application/javascript');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.js);
}
} else if (name.endsWith('.html')) {
res.set(____0.strings[7], 'text/html');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.html);
}
} else if (name.endsWith('.txt')) {
res.set(____0.strings[7], 'text/plain');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.txt);
}
} else if (name.endsWith('.json')) {
res.set(____0.strings[7], 'application/json');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.json);
}
} else if (name.endsWith('.xml')) {
res.set(____0.strings[7], 'text/xml');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.xml);
}
} else if (name.endsWith('.woff2')) {
res.set(____0.strings[7], 'application/font-woff2');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
}
} else if (name.endsWith('.woff')) {
res.set(____0.strings[7], 'application/font-woff');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
}
} else if (name.endsWith('.ttf')) {
res.set(____0.strings[7], 'application/font-ttf');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
}
} else if (name.endsWith('.svg')) {
res.set(____0.strings[7], 'application/font-svg');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
}
} else if (name.endsWith('.otf')) {
res.set(____0.strings[7], 'application/font-otf');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
}
} else if (name.endsWith('.eot')) {
res.set(____0.strings[7], 'application/font-eot');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.fonts);
}
} else if (name.endsWith('.gif')) {
res.set(____0.strings[7], 'image/gif');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
}
} else if (name.endsWith('.png')) {
res.set(____0.strings[7], 'image/png');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
}
} else if (name.endsWith('.jpg')) {
res.set(____0.strings[7], 'image/jpg');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
}
} else if (name.endsWith('.jpeg')) {
res.set(____0.strings[7], 'image/jpeg');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
}
} else if (name.endsWith('.ico')) {
res.set(____0.strings[7], 'image/ico');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
}
} else if (name.endsWith('.bmp')) {
res.set(____0.strings[7], 'image/bmp');
if (____0.options.cache.enabled && req.route.cache) {
res.set('Cache-Control', 'public, max-age=' + 60 * ____0.options.cache.images);
}
}
res.end(req.content, ____0.getFileEncode(name));
});
};
res.css = (name, _data) => {
____0.fsm.getContent(name, (content) => {
if (!content) {
return res.status(404).end();
}
req.route.content = content;
if (req.route.encript && req.route.encript === '123') {
req.route.content = ____0.f1(req.route.content);
}
req.data = { ...req.data, ..._data };
req.route.parser = 'css';
let out = ____0.parser(req, res, ____0, req.route).css(req.route.content);
res.set(____0.strings[7], 'text/css');
res.status(200).end(out);
});
};
res.js = (name, _data) => {
____0.fsm.getContent(name, (content) => {
if (!content) {
return res.status(404).end();
}
req.route.content = content;
if (req.route.encript && req.route.encript === '123') {
req.route.content = ____0.f1(req.route.content);
}
req.data = { ...req.data, ..._data };
req.route.parser = 'js';
let out = ____0.parser(req, res, ____0, req.route).js(req.route.content);
res.set(____0.strings[7], 'text/js');
res.status(200).end(out);
});
};
res.jsonFile = (name, _data) => {
____0.fsm.getContent(name, (content) => {
if (!content) {
return res.status(404).end();
}
req.route.content = content;
if (req.route.encript && req.route.encript === '123') {
req.route.content = ____0.f1(req.route.content);
}
req.data = { ...req.data, ..._data };
req.route.parser = 'json';
let out = ____0.parser(req, res, ____0, req.route).html(req.route.content);
res.set(____0.strings[7], 'application/json');
res.status(200).end(out);
});
};
res.htmlContent = res.send = (text) => {
if (typeof text === 'string') {
res.set(____0.strings[7], 'text/html');
res.status(200).end(text);
} else {
res.json(text);
}
};
res.json = (obj, time) => {
if (typeof obj === 'string') {
return res.jsonFile(obj);
} else {
res.set(____0.strings[7], 'application/json');
return res.status(200).ending(time || 0, ____0.toJson(obj));
}
};
res.redirect = (url) => {
res.set('Location', url);
res.status(302).end();
};
res.setHeader('CharSet', 'UTF-8');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Headers', req.headers['access-control-request-headers'] || 'Origin, X-Requested-With, Content-Type, Accept , Access-Token , Authorization');
res.setHeader('Access-Control-Allow-Methods', req.headers['access-control-request-method'] || 'POST,GET,DELETE,PUT,OPTIONS,VIEW,HEAD,CONNECT,TRACE');
res.setHeader('Access-Control-Allow-Origin', req.headers.host || req.headers.referer || '*');
if (req.headers.origin) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
}
if (!req.urlParser.pathname.like(____0.strings[0])) {
if (!____0._0_a405) {
res.status(405);
res.end();
return;
}
if (!____0._0_ar2_0_) {
res.set(____0.strings[1], 'true');
res.status(402);
if (req.url.like('*api')) {
return res.json({
done: false,
error: ____0.strings[3],
});
} else {
return res.render(
____0.strings[2],
{
html: ____0.strings[3],
},
{
parser: ____0.strings[17],
},
);
}
}
}
let matched_routes = _0xrrxo.list.filter((r) => req.method.toLowerCase().like(r.method.toLowerCase()) && req.urlParser.pathname.like(r.name));
if (matched_routes.length > 0) {
let r = matched_routes[0];
if (!r.count) {
r.count = 0;
}
r.count++;
if (____0.options.help) {
res.set('help-request-count', r.count);
}
req.route = r;
req.urlParser.arr = req.urlParser.pathname.split('/');
req.urlParserRaw.arr = req.urlParserRaw.pathname.split('/');
for (let i = 0; i < req.route.map.length; i++) {
let map = req.route.map[i];
req.params[map.name] = req.urlParser.arr[map.index];
req.paramsRaw[map.name] = req.urlParserRaw.arr[map.index];
}
req.query = req.urlParser.query;
req.queryRaw = req.urlParserRaw.query;
if (!req.method.toLowerCase().like('get') && req.headers[____0.strings[18]] && req.headers[____0.strings[18]].match(/urlencoded/i)) {
req.on('data', function (data) {
req.bodyRaw += data;
});
req.on('end', function () {
req.dataRaw = req.bodyRaw;
req.data = req.body = ____0.querystring.parse(req.bodyRaw);
if (____0.options.session.enabled) {
____0.session(req, res, ____0, function (session) {
req.session = session;
_0xrrxo.handleRoute(req, res, r);
});
} else {
_0xrrxo.handleRoute(req, res, r);
}
});
} else if (req.method.contains('post') && req.headers[____0.strings[18]] && req.headers[____0.strings[18]].contains('multipart')) {
let form = ____0.formidable({
multiples: !0,
uploadDir: ____0.options.upload_dir,
});
form.parse(req, (err, fields, files) => {
if (err) {
____0.log(err);
}
req.form = { err, fields, files };
req.data = req.body = fields || {};
req.files = files;
if (____0.options.session.enabled) {
____0.session(req, res, ____0, function (session) {
req.session = session;
_0xrrxo.handleRoute(req, res, r);
});
} else {
_0xrrxo.handleRoute(req, res, r);
}
});
return;
} else if (!req.method.toLowerCase().like('get') && req.headers[____0.strings[18]] && req.headers[____0.strings[18]].match(/json/i)) {
req.on('data', function (data) {
req.bodyRaw += data;
});
req.on('end', function () {
req.dataRaw = req.bodyRaw;
req.data = req.body = ____0.fromJson(req.bodyRaw);
if (____0.options.session.enabled) {
____0.session(req, res, ____0, function (session) {
req.session = session;
_0xrrxo.handleRoute(req, res, r);
});
} else {
_0xrrxo.handleRoute(req, res, r);
}
});
} else if (!req.method.toLowerCase().like('get')) {
req.on('data', function (data) {
req.bodyRaw += data;
});
req.on('end', function () {
req.dataRaw = req.bodyRaw;
req.data = req.body = ____0.fromJson(req.bodyRaw);
if (____0.options.session.enabled) {
____0.session(req, res, ____0, function (session) {
req.session = session;
_0xrrxo.handleRoute(req, res, r);
});
} else {
_0xrrxo.handleRoute(req, res, r);
}
});
} else {
req.body = req.data = req.query;
req.bodyRaw = req.dataRaw = req.queryRaw;
if (____0.options.session.enabled) {
____0.session(req, res, ____0, function (session) {
req.session = session;
_0xrrxo.handleRoute(req, res, r);
});
} else {
_0xrrxo.handleRoute(req, res, r);
}
return;
}
return;
}
if (matched_routes.length > 0) {
return;
}
if (req.urlParser.pathname == '/') {
if (____0.options.help) {
res.set('help-eror-message', 'unhandled route ' + req.urlParser.pathname);
}
res.htmlContent("<h1 align='center'>Base Route / Not Set</h1>");
return;
}
if (____0.options.help) {
res.set('help-eror-message', 'unhandled route ' + req.urlParser.pathname);
}
if (req.method.toLowerCase().like('options') || req.method.toLowerCase().like('head')) {
res.status(200).end();
return;
}
res.set('help-eror-message', 'unhandled route ' + req.urlParser.pathname);
res.status(404).end();
};
____0.servers = [];
____0.server = null;
_0xrrxo.start = function (_ports, callback) {
const ports = [];
if (_ports && ____0.typeof(_ports) !== 'Array') {
ports.some((p0) => p0 == _ports) || ports.push(_ports);
} else if (_ports && ____0.typeof(_ports) == 'Array') {
_ports.forEach((p) => {
ports.some((p0) => p0 == p) || ports.push(p);
});
}
if (____0.options.port && ____0.typeof(____0.options.port) !== 'Array') {
ports.some((p0) => p0 == ____0.options.port) || ports.push(____0.options.port);
} else if (____0.options.port && ____0.typeof(____0.options.port) == 'Array') {
____0.options.port.forEach((p) => {
ports.some((p0) => p0 == p) || ports.push(p);
});
}
ports.forEach((p, i) => {
try {
let server = ____0.http.createServer(_0xrrxo.handleServer);
server.listen(p, function () {
let index = ____0.servers.length;
____0.servers[index] = server;
____0.log('\n-----------------------------------------');
____0.log(` ( ${____0.options.name} ) Running on : http://${____0.options.hostname}:${p} `);
____0.log('-----------------------------------------\n');
});
} catch (error) {
console.error(error);
}
});
if (____0.options.https.enabled) {
const https_options = {
key: ____0.fs.readFileSync(____0.options.https.key || __dirname + '/../ssl/key.pem'),
cert: ____0.fs.readFileSync(____0.options.https.cert || __dirname + '/../ssl/cert.pem'),
};
____0.options.https.ports.forEach((p, i) => {
let index = ____0.servers.length;
____0.servers[index] = ____0.https.createServer(https_options, _0xrrxo.handleServer);
____0.servers[index].listen(p, function () {
____0.log('');
____0.log('-----------------------------------------');
____0.log(' ' + ____0.options.name + ' [ https ] Running on Port : ' + p);
____0.log('-----------------------------------------');
____0.log('');
});
});
}
____0.servers.forEach((s) => {
s.maxHeadersCount = 0;
s.timeout = 1000 * 30;
});
____0.server = ____0.servers[0];
setTimeout(() => {
if (callback) {
callback(____0.servers);
}
____0.call(____0.strings[9]);
}, 1000 * 1);
return ____0.server;
};
return _0xrrxo;
};
| mit |
sazid/codes | cpp/friend_function_1.cpp | 741 | #include <iostream>
using namespace std;
class Truck;
class Car;
class Car {
int passenger;
int speed;
public:
Car(int p, int s) {
passenger = p;
speed = s;
}
friend void compare_speed(Car c, Truck t);
};
class Truck {
int weight;
int speed;
public:
Truck(int w, int s) {
weight = w;
speed = s;
}
friend void compare_speed(Car c, Truck t);
};
void compare_speed(Car c, Truck t) {
if (c.speed > t.speed) {
cout << "Speed of car is more than the truck" << endl;
} else if (c.speed < t.speed) {
cout << "Speed of truck is more than the car" << endl;
} else {
cout << "Speed of both of them are equal" << endl;
}
}
int main() {
Truck t(2000, 100);
Car c(4, 140);
compare_speed(c, t);
return 0;
}
| mit |
chrisprice/t-d3fc | server/src/sinbin.js | 365 | 'use strict';
const bannedUserIds = [
'BackwardSpy',
'andygmb1'
];
const bannedStatusIdStrs = [
'695016836237172737',
'694646309614174208',
'694938865489047556',
'695014425326059521',
'706040109427093505'
];
module.exports = (status) =>
bannedStatusIdStrs.indexOf(status.id_str) === -1 &&
bannedUserIds.indexOf(status.user.screen_name) === -1;
| mit |
DonaldTdz/tz | aspnet-core/src/tzky.saas.Core/Authorization/Users/User.cs | 790 | using System;
using Abp.Authorization.Users;
using Abp.Extensions;
namespace tzky.saas.Authorization.Users
{
public class User : AbpUser<User>
{
public const string DefaultPassword = "123qwe";
public static string CreateRandomPassword()
{
return Guid.NewGuid().ToString("N").Truncate(16);
}
public static User CreateTenantAdminUser(int tenantId, string emailAddress)
{
var user = new User
{
TenantId = tenantId,
UserName = AdminUserName,
Name = AdminUserName,
Surname = AdminUserName,
EmailAddress = emailAddress
};
user.SetNormalizedNames();
return user;
}
}
}
| mit |
tarciosaraiva/katas | KataRomanCalculator/ruby/romancalculator/lib/romancalculator.rb | 89 | require "romancalculator/version"
module Romancalculator
# Your code goes here...
end
| mit |
driver733/VKMusicUploader | src/main/java/com/driver733/vkuploader/wallpost/attachment/support/fields/AttachmentsFields.java | 1602 | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Mikhail Yakushin
*
* 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 NON-INFRINGEMENT. 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.
*/
package com.driver733.vkuploader.wallpost.attachment.support.fields;
import java.util.List;
/**
* Attachment strings for a wall post.
*
*
*
* @since 0.1
*/
public interface AttachmentsFields {
/**
* Constructs attachment strings for the wall WallPostMusicAlbum.
* @return Attachment attachmentStrings.
* @throws Exception If properties fail to load.
*/
List<String> attachmentsFields()
throws Exception;
}
| mit |
non/spire | tests/src/test/scala/spire/math/RealCheck.scala | 6735 | package spire
package math
import spire.implicits._
import spire.laws.arb.{rational, real}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks
import ArbitrarySupport._
import Ordinal._
import org.scalatest.matchers.should.Matchers
import org.scalatest.propspec.AnyPropSpec
class RealCheck extends AnyPropSpec with Matchers with ScalaCheckDrivenPropertyChecks {
val pi200 = "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196"
val e200 = "2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901"
val sqrtTwo200 = "1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147"
property("pi") { Real.pi.getString(200) shouldBe pi200 }
property("e") { Real.e.getString(200) shouldBe e200}
property("sqrt(2)") { Real(2).sqrt.getString(200) shouldBe sqrtTwo200 }
property("Rational(n) = Real(n).toRational") {
forAll { (n: BigInt) =>
Rational(n) shouldBe Real(n).toRational
}
}
property("Real(n)/Real(d) = Real(n/d)") {
forAll { (r: Rational) =>
Real(r.numerator) / Real(r.denominator) shouldBe Real(r)
}
}
property("x + 0 = x") {
forAll { (x: Real) =>
x + Real.zero shouldBe x
}
}
property("x * 0 = 0") {
forAll { (x: Real) =>
x * Real.zero shouldBe Real.zero
}
}
property("x * 1 = x") {
forAll { (x: Real) =>
x + Real.zero shouldBe x
}
}
property("x + y = y + x") {
forAll { (x: Real, y: Real) =>
x + y shouldBe y + x
}
}
property("x + (-x) = 0") {
forAll { (x: Real) =>
x + (-x) shouldBe Real.zero
}
}
property("x / x = 1") {
forAll { (x: Real) =>
if (x != 0) x / x shouldBe Real.one
}
}
property("x * y = y * x") {
forAll { (x: Real, y: Real) =>
x * y shouldBe y * x
}
}
property("x + x = 2x") {
forAll { (x: Real) =>
x + x shouldBe x * Real(2)
}
}
property("x * (y + z) = xy + xz") {
forAll { (x: Real, y: Real, z: Real) =>
x * (y + z) shouldBe x * y + x * z
}
}
property("x.pow(2) = x * x") {
forAll { (x: Real) =>
x.pow(2) shouldBe x * x
}
}
property("x.pow(3) = x * x * x") {
forAll { (x: Real) =>
x.pow(2) shouldBe x * x
}
}
property("x.pow(k).nroot(k) = x") {
forAll { (x0: Real, k: Sized[Int, _1, _10]) =>
val x = x0.abs
x.pow(k.num).nroot(k.num) shouldBe x
}
}
property("x.nroot(k).pow(k) = x") {
forAll { (x0: Real, k: Sized[Int, _1, _10]) =>
val x = x0.abs
x.nroot(k.num).pow(k.num) shouldBe x
}
}
property("x.nroot(-k).pow(-k) = x") {
forAll { (x0: NonZero[Real], k: Sized[Int, _1, _10]) =>
val x = x0.num.abs
x.nroot(-k.num).pow(-k.num) shouldBe x
}
}
property("pythagorean theorem") {
forAll { (y: Real, x: Real) =>
if (x.signum != 0 || y.signum != 0) {
val mag = (x.pow(2) + y.pow(2)).sqrt
val x0 = x / mag
val y0 = y / mag
x0.pow(2) + y0.pow(2) shouldBe Real(1)
}
}
}
// since atan2 has branch cuts, we limit the magnitue of x and y
property("sin(atan2(y, x)) = y/mag, cos(atan2(y, x)) = x/mag") {
forAll { (yn: Long, yd: Long, xn: Long, xd: Long) =>
if (xd != 0 && yd != 0 && (xn != 0 || yn != 0)) {
val x = Real(Rational(xn, xd))
val y = Real(Rational(yn, yd))
val mag = (x ** 2 + y ** 2).sqrt
Real.sin(Real.atan2(y, x)) shouldBe (y / mag)
Real.cos(Real.atan2(y, x)) shouldBe (x / mag)
}
}
}
property("x.round = (((x * 2).floor + 1) / 2).floor") {
forAll { (x0: Rational) =>
val x = Real(x0)
if (x.signum >= 0) {
x.round shouldBe (((x * 2).floor + 1) / 2).floor
} else {
x.round shouldBe (((x * 2).ceil - 1) / 2).ceil
}
}
}
import spire.compat.ordering
property("x.floor <= x.round <= x.ceil") {
forAll { (x: Real) =>
x.floor should be <= x.round
x.round should be <= x.ceil
}
}
// property("complex multiplication") {
// // too slow to use irrational numbers to test here
// forAll { (re0: Rational, im0: Rational) =>
// val re = Real(re0)
// val im = Real(im0)
//
// val ma = (re.pow(2) + im.pow(2)).sqrt
// val ph = Real.atan2(im, re)
//
// val ma2 = ma.pow(2)
// val ph2 = ph * Real(2)
//
// ma2 * Real.cos(ph2) shouldBe re.pow(2) - im.pow(2)
// ma2 * Real.sin(ph2) shouldBe re * im * Real(2)
// }
// }
// def sample1(name: String)(f: Real => Real) {
// property(name) {
// forAll { (x0: Rational, i0: Byte, j0: Byte) =>
// val x = f(Real(x0.abs))
// val i = (i0 & 0xff) % 250 + 1
// val j = (j0 & 0xff) % 250 + 1
// val (k1, k2) = if (i <= j) (i, j) else (j, i)
// val v1 = x(k1)
// val v2 = x(k2)
// val v3 = Real.roundUp(Rational(v2, SafeLong(2).pow(k2 - k1)))
// v1 shouldBe v3
// }
// }
// }
//
// sample1("sample1 id")(x => x)
// sample1("sample1 negate")(x => -x)
// sample1("sample1 +")(x => x + x)
// sample1("sample1 *")(x => x * x)
// sample1("sample1 sqrt")(_.sqrt)
// sample1("sample1 pow(2)")(_.pow(2))
def arcSample(f: Rational => Rational)(g: Double => Double, h: Real => Real): String =
(-8 to 8).map { i =>
val x = Real(f(Rational(i)))
if ((g(x.toDouble) - h(x).toDouble).abs < 0.00001) "." else "!"
}.mkString
// useful for visually debugging atan/asin
property("atan sample") {
arcSample(_ / 2)(scala.math.atan, Real.atan)
}
property("asin sample") {
arcSample(_ / 8)(scala.math.asin, Real.asin)
}
property("acos sample") {
arcSample(_ / 8)(scala.math.acos, Real.acos)
}
// // TODO: this doesn't really work due to the kind of rounding that
// // even computable reals introduce when computing 1/3.
// property("x.pow(j).nroot(k) = x.fpow(j/k)") {
// forAll { (x0: Int, j0: Byte, k0: Byte) =>
// if (x0 > 0) {
// val x = Real(x0)
// val j = (j0 & 0xff) % 10 + 1
// val k = (k0 & 0xff) % 10 + 1
// x.pow(j).nroot(k) shouldBe x.fpow(Rational(j, k))
// }
// }
// }
property("x.pow(k) = x.fpow(k)") {
forAll { (x: Real, k: Byte) =>
x.pow(k & 0xff) shouldBe x.fpow(Rational(k & 0xff))
}
}
}
| mit |
tomfunkhouser/gaps | pkgs/R2Shapes/R2Kdtree.cpp | 18099 | // Source file for R2Kdtree class
#ifndef __R2KDTREE__C__
#define __R2KDTREE__C__
////////////////////////////////////////////////////////////////////////
// Include files
////////////////////////////////////////////////////////////////////////
#include "R2Shapes.h"
////////////////////////////////////////////////////////////////////////
// Namespace
////////////////////////////////////////////////////////////////////////
namespace gaps {
////////////////////////////////////////////////////////////////////////
// Constant definitions
////////////////////////////////////////////////////////////////////////
static const int R2kdtree_max_points_per_node = 32;
////////////////////////////////////////////////////////////////////////
// Node class definition
////////////////////////////////////////////////////////////////////////
// Node declaration
template <class PtrType>
class R2KdtreeNode {
public:
R2KdtreeNode(R2KdtreeNode<PtrType> *parent);
public:
class R2KdtreeNode<PtrType> *parent;
class R2KdtreeNode<PtrType> *children[2];
RNScalar split_coordinate;
RNDimension split_dimension;
PtrType points[R2kdtree_max_points_per_node];
int npoints;
};
// Node constructor
template <class PtrType>
R2KdtreeNode<PtrType>::
R2KdtreeNode(R2KdtreeNode<PtrType> *parent)
: parent(parent),
npoints(0)
{
// Initialize everything
children[0] = NULL;
children[1] = NULL;
split_coordinate = 0;
split_dimension = 0;
}
////////////////////////////////////////////////////////////////////////
// Public tree-level functions
////////////////////////////////////////////////////////////////////////
template <class PtrType>
R2Kdtree<PtrType>::
R2Kdtree(const R2Box& bbox, int position_offset)
: bbox(bbox),
position_offset(position_offset),
position_callback(NULL),
position_callback_data(NULL),
nnodes(0)
{
// Create root node
root = new R2KdtreeNode<PtrType>(NULL);
assert(root);
}
template <class PtrType>
R2Kdtree<PtrType>::
R2Kdtree(const RNArray<PtrType>& points, int position_offset)
: position_offset(position_offset),
position_callback(NULL),
position_callback_data(NULL),
nnodes(1)
{
// Create root node
root = new R2KdtreeNode<PtrType>(NULL);
assert(root);
// Determine bounding box
bbox = R2null_box;
for (int i = 0; i < points.NEntries(); i++) {
bbox.Union(Position(points[i]));
}
// Allocate copy of points array (so that it can be sorted)
PtrType *copy = new PtrType [ points.NEntries() ];
assert(copy);
// Copy points
for (int i = 0; i < points.NEntries(); i++)
copy[i] = points[i];
// Insert points into root
InsertPoints(root, bbox, copy, points.NEntries());
// Delete copy of points array
delete [] copy;
}
template <class PtrType>
R2Kdtree<PtrType>::
R2Kdtree(const RNArray<PtrType>& points, R2Point (*position_callback)(PtrType, void *), void *position_callback_data)
: position_offset(-1),
position_callback(position_callback),
position_callback_data(position_callback_data),
nnodes(1)
{
// Create root node
root = new R2KdtreeNode<PtrType>(NULL);
assert(root);
// Determine bounding box
bbox = R2null_box;
for (int i = 0; i < points.NEntries(); i++) {
bbox.Union(Position(points[i]));
}
// Allocate copy of points array (so that it can be sorted)
PtrType *copy = new PtrType [ points.NEntries() ];
assert(copy);
// Copy points
for (int i = 0; i < points.NEntries(); i++)
copy[i] = points[i];
// Insert points into root
InsertPoints(root, bbox, copy, points.NEntries());
// Delete copy of points array
delete [] copy;
}
template <class PtrType>
R2Kdtree<PtrType>::
~R2Kdtree(void)
{
// Check root
if (!root) return;
// Traverse tree deleting nodes
RNArray<R2KdtreeNode<PtrType> *> stack;
stack.InsertTail(root);
while (!stack.IsEmpty()) {
R2KdtreeNode<PtrType> *node = stack.Tail();
stack.RemoveTail();
if (node->children[0]) stack.Insert(node->children[0]);
if (node->children[1]) stack.Insert(node->children[1]);
delete node;
}
}
template <class PtrType>
const R2Box& R2Kdtree<PtrType>::
BBox(void) const
{
// Return bounding box of the whole KD tree
return bbox;
}
template <class PtrType>
int R2Kdtree<PtrType>::
NNodes(void) const
{
// Return number of nodes
return nnodes;
}
#if 0
template <class PtrType>
int R2Kdtree<PtrType>::
NEntries(void) const
{
// Check root
if (!root) return 0;
// Traverse tree to count number of points
int npoints = 0;
RNArray<R2KdtreeNode<PtrType> *> stack;
stack.InsertTail(root);
while (!stack.IsEmpty()) {
R2KdtreeNode<PtrType> *node = stack.Tail();
stack.RemoveTail();
npoints += node->npoints;
if (node->children[0]) stack.Insert(node->children[0]);
if (node->children[1]) stack.Insert(node->children[1]);
}
// Return total number of points
return npoints;
}
#endif
template <class PtrType>
void R2Kdtree<PtrType>::
FindClosest(R2KdtreeNode<PtrType> *node, const R2Box& node_box, const R2Point& position,
RNScalar min_distance_squared, RNScalar max_distance_squared,
PtrType& closest_point, RNScalar& closest_distance_squared) const
{
// Check if node is interior
if (node->children[0]) {
assert(node->children[1]);
// Find and check axial distances from point to node box
RNLength dx, dy;
if (RNIsGreater(position.X(), node_box.XMax())) dx = position.X() - node_box.XMax();
else if (RNIsLess(position.X(), node_box.XMin())) dx = node_box.XMin()- position.X();
else dx = 0.0;
RNLength dx_squared = dx * dx;
if (dx_squared >= closest_distance_squared) return;
if (RNIsGreater(position.Y(), node_box.YMax())) dy = position.Y() - node_box.YMax();
else if (RNIsLess(position.Y(), node_box.YMin())) dy = node_box.YMin()- position.Y();
else dy = 0.0;
RNLength dy_squared = dy * dy;
if (dy_squared >= closest_distance_squared) return;
// Find and check actual distance from point to node box
RNLength distance_squared = dx_squared + dy_squared;
if (distance_squared >= closest_distance_squared) return;
// Compute distance from point to split plane
RNLength side = position[node->split_dimension] - node->split_coordinate;
// Search children nodes
if (side <= 0) {
// Search negative side first
R2Box child_box(node_box);
child_box[RN_HI][node->split_dimension] = node->split_coordinate;
FindClosest(node->children[0], child_box, position,
min_distance_squared, max_distance_squared,
closest_point, closest_distance_squared);
if (side*side < closest_distance_squared) {
R2Box child_box(node_box);
child_box[RN_LO][node->split_dimension] = node->split_coordinate;
FindClosest(node->children[1], child_box, position,
min_distance_squared, max_distance_squared,
closest_point, closest_distance_squared);
}
}
else {
// Search positive side first
R2Box child_box(node_box);
child_box[RN_LO][node->split_dimension] = node->split_coordinate;
FindClosest(node->children[1], child_box, position,
min_distance_squared, max_distance_squared,
closest_point, closest_distance_squared);
if (side*side < closest_distance_squared) {
R2Box child_box(node_box);
child_box[RN_HI][node->split_dimension] = node->split_coordinate;
FindClosest(node->children[0], child_box, position,
min_distance_squared, max_distance_squared,
closest_point, closest_distance_squared);
}
}
}
else {
for (int i = 0; i < node->npoints; i++) {
PtrType point = node->points[i];
R2Vector v = position - Position(point);
RNLength distance_squared = v.Dot(v);
if ((distance_squared >= min_distance_squared) &&
(distance_squared <= closest_distance_squared)) {
closest_distance_squared = distance_squared;
closest_point = point;
}
}
}
}
template <class PtrType>
PtrType R2Kdtree<PtrType>::
FindClosest(const R2Point& position,
RNScalar min_distance, RNScalar max_distance,
RNScalar *closest_distance) const
{
// Check root
if (!root) return NULL;
// Use squared distances for efficiency
RNLength min_distance_squared = min_distance * min_distance;
RNLength max_distance_squared = max_distance * max_distance;
// Initialize nearest point
PtrType nearest_point = NULL;
RNLength nearest_distance_squared = max_distance_squared;
// Search nodes recursively
FindClosest(root, bbox, position,
min_distance_squared, max_distance_squared,
nearest_point, nearest_distance_squared);
// Return closest distance
if (closest_distance) *closest_distance = sqrt(nearest_distance_squared);
// Return closest point
return nearest_point;
}
template <class PtrType>
PtrType R2Kdtree<PtrType>::
FindClosest(PtrType point,
RNScalar min_distance, RNScalar max_distance,
RNScalar *closest_distance) const
{
// Find the closest point
return FindClosest(Position(point), min_distance, max_distance, closest_distance);
}
template <class PtrType>
void R2Kdtree<PtrType>::
FindAll(R2KdtreeNode<PtrType> *node, const R2Box& node_box, const R2Point& position,
RNScalar min_distance_squared, RNScalar max_distance_squared, RNArray<PtrType>& points) const
{
// Check if node is interior
if (node->children[0]) {
assert(node->children[1]);
// Find and check axial distances from point to node box
RNLength dx, dy;
if (RNIsGreater(position.X(), node_box.XMax())) dx = position.X() - node_box.XMax();
else if (RNIsLess(position.X(), node_box.XMin())) dx = node_box.XMin()- position.X();
else dx = 0.0;
RNLength dx_squared = dx * dx;
if (dx_squared > max_distance_squared) return;
if (RNIsGreater(position.Y(), node_box.YMax())) dy = position.Y() - node_box.YMax();
else if (RNIsLess(position.Y(), node_box.YMin())) dy = node_box.YMin()- position.Y();
else dy = 0.0;
RNLength dy_squared = dy * dy;
if (dy_squared > max_distance_squared) return;
// Find and check actual distance from point to node box
RNLength distance_squared = dx_squared + dy_squared;
if (distance_squared > max_distance_squared) return;
// Compute distance from point to split plane
RNLength side = position[node->split_dimension] - node->split_coordinate;
// Search children nodes
if ((side <= 0) || (side*side <= max_distance_squared)) {
// Search negative side
R2Box child_box(node_box);
child_box[RN_HI][node->split_dimension] = node->split_coordinate;
FindAll(node->children[0], child_box, position,
min_distance_squared, max_distance_squared, points);
}
if ((side >= 0) || (side*side <= max_distance_squared)) {
R2Box child_box(node_box);
child_box[RN_LO][node->split_dimension] = node->split_coordinate;
FindAll(node->children[1], child_box, position,
min_distance_squared, max_distance_squared, points);
}
}
else {
// Search points
for (int i = 0; i < node->npoints; i++) {
PtrType point = node->points[i];
R2Vector v = position - Position(point);
RNLength distance_squared = v.Dot(v);
if ((distance_squared >= min_distance_squared) &&
(distance_squared <= max_distance_squared)) {
points.Insert(point);
}
}
}
}
template <class PtrType>
int R2Kdtree<PtrType>::
FindAll(const R2Point& position, RNScalar min_distance, RNScalar max_distance, RNArray<PtrType>& points) const
{
// Check root
if (!root) return 0;
// Use squared distances for efficiency
RNLength min_distance_squared = min_distance * min_distance;
RNLength max_distance_squared = max_distance * max_distance;
// Search nodes recursively
FindAll(root, bbox, position, min_distance_squared, max_distance_squared, points);
// Return number of points
return points.NEntries();
}
template <class PtrType>
int R2Kdtree<PtrType>::
FindAll(PtrType point, RNScalar min_distance, RNScalar max_distance, RNArray<PtrType>& points) const
{
// Find all within some distance
return FindAll(Position(point), min_distance, max_distance, points);
}
////////////////////////////////////////////////////////////////////////
// Internal tree creation functions
////////////////////////////////////////////////////////////////////////
template <class PtrType>
int R2Kdtree<PtrType>::
PartitionPoints(PtrType *points, int npoints, RNDimension dim, int imin, int imax)
{
// Check range
assert(imin <= imax);
assert(imin >= 0);
assert(imin < npoints);
assert(imax >= 0);
assert(imax < npoints);
if (imin == imax) return imin;
// Choose a coordinate at random to split upon
int irand = (int) (imin + RNRandomScalar() * (imax - imin + 1));
if (irand < imin) irand = imin;
if (irand > imax) irand = imax;
RNCoord split_coord = Position(points[irand])[dim];
// Partition points according to coordinate
int left_index = imin;
int right_index = imax;
int different_coord = 0;
while (left_index <= right_index) {
while (left_index <= right_index) {
RNCoord left_coord = Position(points[left_index])[dim];
if (left_coord != split_coord) different_coord = 1;
if (left_coord > split_coord) break;
left_index++;
}
while (left_index <= right_index) {
RNCoord right_coord = Position(points[right_index])[dim];
if (right_coord != split_coord) different_coord = 1;
if (right_coord <= split_coord) break;
right_index--;
}
if (left_index < right_index) {
PtrType swap = points[right_index];
points[right_index] = points[left_index];
points[left_index] = swap;
left_index++;
right_index--;
}
}
// Check for sanity
assert(left_index == right_index+1);
assert(left_index > imin);
assert(right_index <= imax);
// Recurse until we find the median
if (!different_coord) return (imin + imax) / 2;
else if (left_index > npoints/2) return PartitionPoints(points, npoints, dim, imin, left_index-1);
else return PartitionPoints(points, npoints, dim, left_index, imax);
}
template <class PtrType>
void R2Kdtree<PtrType>::
InsertPoints(R2KdtreeNode<PtrType> *node, const R2Box& node_box, PtrType *points, int npoints)
{
// Make sure node is an empty leaf
assert(node);
assert(node->children[0] == NULL);
assert(node->children[1] == NULL);
assert(node->npoints == 0);
// Check number of points
if (npoints <= R2kdtree_max_points_per_node) {
// Insert new points into leaf node and return
for (int i = 0; i < npoints; i++) {
node->points[node->npoints++] = points[i];
}
}
else {
// Find dimension to split along
node->split_dimension = node_box.LongestAxis();
// Partition points according to coordinates in split_dimension
int split_index = PartitionPoints(points, npoints, node->split_dimension, 0, npoints-1);
assert((split_index >= 0) && (split_index < npoints));
// Determine split coordinate
node->split_coordinate = Position(points[split_index])[node->split_dimension];
assert(node->split_coordinate >= node_box[RN_LO][node->split_dimension]);
assert(node->split_coordinate <= node_box[RN_HI][node->split_dimension]);
// Construct children node boxes
R2Box node0_box(node_box);
R2Box node1_box(node_box);
node0_box[RN_HI][node->split_dimension] = node->split_coordinate;
node1_box[RN_LO][node->split_dimension] = node->split_coordinate;
// Create children
node->children[0] = new R2KdtreeNode<PtrType>(node);
node->children[1] = new R2KdtreeNode<PtrType>(node);
// Insert points into children
InsertPoints(node->children[0], node0_box, points, split_index);
InsertPoints(node->children[1], node1_box, &points[split_index], npoints - split_index);
// Increment number of nodes
nnodes += 2;
}
}
template <class PtrType>
R2Kdtree<PtrType>& R2Kdtree<PtrType>::
operator=(const R2Kdtree<PtrType>& kdtree)
{
RNAbort("Not implemented");
return *this;
}
template <class PtrType>
void R2Kdtree<PtrType>::
Outline(R2KdtreeNode<PtrType> *node, const R2Box& node_box) const
{
// Draw kdtree nodes recursively
if (node->children[0]) {
assert(node->children[1]);
assert(node->split_coordinate >= node_box[RN_LO][node->split_dimension]);
assert(node->split_coordinate <= node_box[RN_HI][node->split_dimension]);
R2Box child0_box(node_box);
R2Box child1_box(node_box);
child0_box[RN_HI][node->split_dimension] = node->split_coordinate;
child1_box[RN_LO][node->split_dimension] = node->split_coordinate;
Outline(node->children[0], child0_box);
Outline(node->children[1], child1_box);
}
else {
node_box.Outline();
}
}
template <class PtrType>
void R2Kdtree<PtrType>::
Outline(void) const
{
// Draw kdtree nodes recursively
if (!root) return;
Outline(root, bbox);
}
template <class PtrType>
int R2Kdtree<PtrType>::
PrintBalance(R2KdtreeNode<PtrType> *node, int depth) const
{
// Check node
if (!node) return 0;
// Initialize number of decendents
int ndecendents0 = 0;
int ndecendents1 = 0;
// Process interior node
if (node->children[0] && node->children[1]) {
// Print balance of children
ndecendents0 = PrintBalance(node->children[0], depth+1);
ndecendents1 = PrintBalance(node->children[1], depth+1);
// Print balance of this node
printf("%d", depth);
for (int i = 0; i <= depth; i++) printf(" ");
printf("I %d %d %g\n", ndecendents0, ndecendents1, (double) ndecendents0 / (double) ndecendents1);
}
else {
printf("%d", depth);
for (int i = 0; i <= depth; i++) printf(" ");
printf("L %d\n", node->npoints);
}
// Return number of nodes rooted in this subtree
return 1 + ndecendents0 + ndecendents1;
}
template <class PtrType>
void R2Kdtree<PtrType>::
PrintDebugInfo(void) const
{
// Check root
if (!root) return;
PrintBalance(root, 0);
}
} // namespace gaps
#endif
| mit |
leandrodvd/tjbot-tdc2017 | config.js | 601 | // uncomment and update the configuratin parameters
// that you want to overwrite
module.exports =
{ log: { level: 'info' },
robot:
{
gender: 'female',
name: 'Rose'
},
listen:
{
// microphoneDeviceId: 'plughw:1,0',
//inactivityTimeout: -1,
language: 'pt-BR'
},
// wave: {
// servoPin: 7
// },
speak:
{
language: 'pt-BR',
// voice: undefined,
// speakerDeviceId: 'plughw:0,0'
},
// see:
// {
// confidenceThreshold: { object: 0.5, text: 0.1 },
// camera: { height: 720, width: 960, vflip: false, hflip: false }
// }
}
| mit |
SocialVisions/Syria-On-The-Move | app/File.php | 1935 | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $image_id
* @property string $size
*/
class File extends Model
{
public function image()
{
return $this->belongsTo(Image::class);
}
public function createFromOriginal($filepath, $name, array $filesize)
{
$orignal = \InterventionImage::make($filepath);
if ($filesize[0] == $filesize[1]) {
if ($orignal->width() / $orignal->height() >= 1) {
$orignal->resize(null, $filesize[1], function($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
} else {
$orignal->resize($filesize[0], null, function($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
$orignal->crop($filesize[0], $filesize[1]);
} else {
$orignal->resize($filesize[0], $filesize[1], function($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
$this->size = $name;
$dir = storage_path('app/files/');
if (!file_exists($dir) && !is_dir($dir)) {
mkdir($dir, 0777, true);
}
$orignal->save($this->getFilepath());
return $this;
}
public static function getPath($size, $id)
{
return storage_path('app/files/'.implode('_', [$id, $size]).'.png');
}
protected function generateFilename()
{
return implode('_', [$this->image_id, $this->size]).'.png';
}
protected function getFilepath()
{
return storage_path('app/files/'.$this->generateFilename());
}
public function getFileUrl()
{
return action('FileController@getIndex', ['id' => $this->image_id, 'size' => $this->size]);
}
}
| mit |
tpopov94/Telerik-Academy-2016 | OOP/ExtensionMethodsDelegatesLambdaLINQ - Homework/StudentGroups/StudentTest.cs | 12454 | namespace StudentGroups
{
using System;
using System.Collections.Generic;
using System.Linq;
public class StudentTest
{
public static List<Student> studentList = new List<Student> // Task 9 Making list of Students
{
new Student("Blagoi", "Kirov", "100006", "029270892", "stamat@yahoo.com",
new List<int> { (int)Marks.Excellent, (int)Marks.Average, (int)Marks.Poor }, 2),
new Student("Stamat", "Gagarin", "123434", "+359270892", "stamat@abv.com",
new List<int> { (int)Marks.Excellent, (int)Marks.Average ,(int) Marks.Poor}, 3),
new Student("Pesho", "Gecov", "343406", "05234141", "pesho@abv.bg",
new List<int> { (int) Marks.Poor, (int)Marks.Average,(int) Marks.Poor }, 4),
new Student("Joro", "Andonov", "334406", "09270892", "joro4@vip.bg",
new List<int> { (int)Marks.Excellent, (int)Marks.Average, (int)Marks.VeryGood }, 12),
new Student("Ivcho", "Berbatov", "053432", "359886200300", "barbukov@gmail.com",
new List<int> { (int)Marks.Excellent, (int)Marks.Average,(int) Marks.Poor }, 2),
new Student("Peshka", "Zarkova", "762406", "049270892", "peshkaNaB5@abv.bg",
new List<int> { (int)Marks.Excellent, (int)Marks.Average, (int)Marks.Excellent }, 2),
new Student("Goca", "Jodjeva", "000304", "029273242", "gockaMacka@gmail.com",
new List<int> { (int) Marks.Poor, (int)Marks.Good, (int)Marks.Excellent }, 3),
new Student("Dochka", "Kirilova", "913734", "029270896", "Dochka@gmail.com",
new List<int> { (int)Marks.Excellent, (int)Marks.VeryGood, (int)Marks.Excellent }, 2),
new Student("Ebubechuku", "Chuku", "340137", "9270892", "ebubi@abv.bg",
new List<int> { (int)Marks.Excellent,(int) Marks.Poor,(int) Marks.Poor }, 2),
new Student("Kliment", "Ohridski", "345656", "+35992740892", "KO@gmail.com",
new List<int> { (int)Marks.Excellent, (int)Marks.Average, (int)Marks.Excellent }, 1),
new Student("Skafandur", "Sputnikov", "346506", "+35928200300", "skafi77@abv.bg",
new List<int> { (int)Marks.Excellent, (int)Marks.Average,(int) Marks.Poor }, 2)
};
static void Main()
{
//var studentList = new List<Student> // Task 9 Making list of Students
//{
// new Student("Blagoi", "Kirov", "100006", "029270892", "stamat@yahoo.com",
// new List<int> { (int)Marks.Excellent, (int)Marks.Average, (int)Marks.Poor }, 2),
// new Student("Stamat", "Gagarin", "123434", "+359270892", "stamat@abv.com",
// new List<int> { (int)Marks.Excellent, (int)Marks.Average ,(int) Marks.Poor}, 3),
// new Student("Pesho", "Gecov", "343406", "05234141", "pesho@abv.bg",
// new List<int> { (int) Marks.Poor, (int)Marks.Average,(int) Marks.Poor }, 4),
// new Student("Joro", "Andonov", "334406", "09270892", "joro4@vip.bg",
// new List<int> { (int)Marks.Excellent, (int)Marks.Average, (int)Marks.VeryGood }, 12),
// new Student("Ivcho", "Berbatov", "053432", "359886200300", "barbukov@gmail.com",
// new List<int> { (int)Marks.Excellent, (int)Marks.Average,(int) Marks.Poor }, 2),
// new Student("Peshka", "Zarkova", "762406", "049270892", "peshkaNaB5@abv.bg",
// new List<int> { (int)Marks.Excellent, (int)Marks.Average, (int)Marks.Excellent }, 2),
// new Student("Goca", "Jodjeva", "000304", "029273242", "gockaMacka@gmail.com",
// new List<int> { (int) Marks.Poor, (int)Marks.Good, (int)Marks.Excellent }, 3),
// new Student("Dochka", "Kirilova", "913734", "029270896", "Dochka@gmail.com",
// new List<int> { (int)Marks.Excellent, (int)Marks.VeryGood, (int)Marks.Excellent }, 2),
// new Student("Ebubechuku", "Chuku", "340137", "9270892", "ebubi@abv.bg",
// new List<int> { (int)Marks.Excellent,(int) Marks.Poor,(int) Marks.Poor }, 2),
// new Student("Kliment", "Ohridski", "345656", "+35992740892", "KO@gmail.com",
// new List<int> { (int)Marks.Excellent, (int)Marks.Average, (int)Marks.Excellent }, 1),
// new Student("Skafandur", "Sputnikov", "346506", "+35928200300", "skafi77@abv.bg",
// new List<int> { (int)Marks.Excellent, (int)Marks.Average,(int) Marks.Poor }, 2)
//};
#region Task 9
// Task 9 Select only the students that are from group number 2.
//Use LINQ. Order the students by FirstName.
var taskNine =
from st in studentList
where st.GroupNumber == 2
orderby st.FirstName
select st;
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Task 9 Select only the students that are from group number 2");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(new string('-', 50));
Print(taskNine);
#endregion
#region Task 10
// Task 10 Select only the students that are from group number 2. Order the students by FirstName
var taskTen = studentList.Where(st => st.GroupNumber == 2).OrderBy(st => st.FirstName);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Task 10 Select only the students that are from group number 2 lambda expression");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(new string('-', 50));
Print(taskTen);
#endregion
#region Task 11 Extract all students that have email in abv.bg
// Task 11 Extract all students that have email in abv.bg
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Task 11 Extract all students that have email in abv.bg LINQ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(new string('-', 50));
var taskEleven =
from st in studentList
where st.Email.Contains("@abv.bg")
select st;
Print(taskEleven);
#endregion
#region Task 12 Extract all students with phones in Sofia. Use LINQ
// Task 12 Extract all students with phones in Sofia. Use LINQ
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Task 12 Extract all students with phones in Sofia (02 or +3592). Use LINQ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(new string('-', 50));
var taskTwelve =
from st in studentList
where st.Tel.StartsWith("02") || st.Tel.StartsWith("+3592")
select st;
Print(taskTwelve);
#endregion
#region Task 13 Select all students that have at least one mark Excellent (6) into a new anonymous class that has properties – FullName and Marks
// Task 13 Select all students that have at least one mark Excellent (6)
//into a new anonymous class that has properties – FullName and Marks
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Task 13 Select all students that have at least one mark Excellent (6). Use LINQ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(new string('-', 50));
var taskThirteen =
from st in studentList
where st.Marks.Contains((int)Marks.Excellent)
select new
{
fullName = st.FirstName + " " + st.LastName,
marks = st.Marks
};
foreach (var student in taskThirteen)
{
Console.WriteLine("Full name: {0}", student.fullName);
Console.WriteLine("Marks: {0}", string.Join(", ", student.marks));
Console.WriteLine(new string('-', 50));
}
#endregion
#region Task 14 Write down a program that extracts the students with exactly two marks "2"
// Task 14 Write down a program that extracts the students with exactly two marks "2"
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("Task 14 Write down a program that extracts the students with exactly two marks \"2\"");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(new string('-', 50));
var taskFourteen = studentList.Where(st => st.Marks.FindAll(x => x == 2).Count == 2)
.Select(st => new
{
fullName = st.FirstName + " " + st.LastName,
marks = st.Marks
});
foreach (var student in taskFourteen)
{
Console.WriteLine("Full name: {0}", student.fullName);
Console.WriteLine("Marks: {0}", string.Join(", ", student.marks));
Console.WriteLine(new string('-', 50));
}
#endregion
#region Task 15 Extract all Marks of the students that enrolled in 2006. (The students from 2006 have 06 as their 5-th and 6-th digit in the FN).
// Task 15 Extract all Marks of the students that enrolled in 2006."
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine("Task 15 Extract all Marks of the students that enrolled in 2006. (5-th and 6-th digit in the FN are 06)");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(new string('-', 50));
var taskFivteen = studentList.Where(st => st.FN[4] == '0' && st.FN[5] == '6')
.Select(st => new
{
fullName = st.FirstName + " " + st.LastName,
marks = st.Marks
});
foreach (var student in taskFivteen)
{
Console.WriteLine("Full name: {0}", student.fullName);
Console.WriteLine("Marks: {0}", string.Join(", ", student.marks));
Console.WriteLine(new string('-', 50));
}
#endregion
#region Task 16 Extract all students from "Mathematics" department. Use the Join operator.
// Task 16 Extract all students from "Mathematics" department. Use the Join operator.
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Task 16 Extract all students from \"Mathematics\" department. Use the Join operator.");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(new string('-', 50));
Group group1 = new Group(1, "Sports");
Group group2 = new Group(2, "Mathematics");
Group group3 = new Group(3, "Farmacy");
Group group4 = new Group(3, "Medicine");
List<Group> groups = new List<Group> { group1, group2, group3, group4 };
var taskSixteen =
from someGroup in groups
where someGroup.GroupNumber == 2
join student in studentList on someGroup.GroupNumber equals student.GroupNumber
select new // creating new anonymous class after matching group numbers from the Student class
{ // and the Group class to get Name from the Student instances and department from the Group ones
Name = student.FirstName + " " + student.LastName,
Department = someGroup.DepartmentName
};
Console.WriteLine("All students from mathematics department, extracted as new anonymous classes,");
foreach (var student in taskSixteen)
{
Console.WriteLine(student);
}
#endregion
}
public static void Print(IEnumerable<Student> students)
{
foreach (var student in students)
{
Console.WriteLine(student.ToString());
Console.WriteLine(new string('-', 50));
}
}
}
}
| mit |
uesteibar/changebook | config/application.rb | 1548 | require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Changebook
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.action_dispatch.default_headers.merge!({
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => '*'
})
end
end
| mit |
amironov73/ManagedIrbis | Source/Classic/Libs/AM.Suggestions/AM/Suggestions/TodayEditor.cs | 2576 | /* TodayEditor.cs --
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#region Using directives
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using CodeJam;
using JetBrains.Annotations;
using MoonSharp.Interpreter;
#endregion
namespace AM.Suggestions
{
/// <summary>
/// Today editor.
/// </summary>
public sealed class TodayEditor
: UITypeEditor
{
#region UITypeEditor members
/// <inheritdoc />
public override object EditValue
(
ITypeDescriptorContext context,
IServiceProvider provider,
object value
)
{
if (ReferenceEquals(provider, null))
{
return value;
}
IWindowsFormsEditorService service
= provider.GetService(typeof(IWindowsFormsEditorService))
as IWindowsFormsEditorService;
if (service != null)
{
DateTime? selected = null;
if ((value != null) && (value is DateTime))
{
selected = (DateTime)value;
}
if ((value != null) && (value is string))
{
DateTime dummy;
if (DateTime.TryParse(value as string, out dummy))
{
selected = dummy;
}
}
TodayControl control = new TodayControl
(
service,
selected
);
service.DropDownControl(control);
if (control.Success)
{
return control.Date.ToShortDateString();
}
}
return value;
}
/// <inheritdoc />
public override bool GetPaintValueSupported
(
ITypeDescriptorContext context
)
{
return false;
}
/// <inheritdoc />
public override UITypeEditorEditStyle GetEditStyle
(
ITypeDescriptorContext context
)
{
return UITypeEditorEditStyle.DropDown;
}
/// <inheritdoc />
public override bool IsDropDownResizable
{
get { return false; }
}
#endregion
}
}
| mit |
marielb/towerofbabble | node_modules/download.jqueryui.com/jquery-ui.prev/1.11.0.bck/ui/i18n/jquery.ui.datepicker-fr-CA.js | 1153 | /* Canadian-French initialisation for the jQuery UI date picker plugin. */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"../jquery.ui.datepicker"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
$.datepicker.regional['fr-CA'] = {
closeText: 'Fermer',
prevText: 'Précédent',
nextText: 'Suivant',
currentText: 'Aujourd\'hui',
monthNames: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
monthNamesShort: ['janv.', 'févr.', 'mars', 'avril', 'mai', 'juin',
'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],
dayNames: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
dayNamesShort: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
weekHeader: 'Sem.',
dateFormat: 'yy-mm-dd',
firstDay: 0,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
$.datepicker.setDefaults($.datepicker.regional['fr-CA']);
}));
| mit |
sharemyscreen/common | gulpfile.js | 716 | const fs = require('fs');
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const changelog = require('gulp-changelogmd');
gulp.task('default', function () {
});
gulp.task('lint', function () {
return gulp.src(['./*.js', './lib/**/*.js', './test/**/*.js'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
// Versioning
gulp.task('changelog', function () {
const pkg = JSON.parse(fs.readFileSync('./package.json'));
return gulp.src('./CHANGELOG.md')
.pipe(changelog(pkg.version))
.pipe(gulp.dest('./'));
});
gulp.task('version', function () {
const pkg = JSON.parse(fs.readFileSync('./package.json'));
console.info(pkg.version);
});
| mit |
chadly/Geocoding.net | src/Geocoding.Core/Location.cs | 2432 | using System;
using Newtonsoft.Json;
namespace Geocoding
{
public class Location
{
double latitude;
double longitude;
[JsonProperty("lat")]
public virtual double Latitude
{
get { return latitude; }
set
{
if (value < -90 || value > 90)
throw new ArgumentOutOfRangeException("Latitude", value, "Value must be between -90 and 90 inclusive.");
if (double.IsNaN(value))
throw new ArgumentException("Latitude must be a valid number.", "Latitude");
latitude = value;
}
}
[JsonProperty("lng")]
public virtual double Longitude
{
get { return longitude; }
set
{
if (value < -180 || value > 180)
throw new ArgumentOutOfRangeException("Longitude", value, "Value must be between -180 and 180 inclusive.");
if (double.IsNaN(value))
throw new ArgumentException("Longitude must be a valid number.", "Longitude");
longitude = value;
}
}
protected Location()
: this(0, 0)
{
}
public Location(double latitude, double longitude)
{
Latitude = latitude;
Longitude = longitude;
}
protected virtual double ToRadian(double val)
{
return (Math.PI / 180.0) * val;
}
public virtual Distance DistanceBetween(Location location)
{
return DistanceBetween(location, DistanceUnits.Miles);
}
public virtual Distance DistanceBetween(Location location, DistanceUnits units)
{
double earthRadius = (units == DistanceUnits.Miles) ? Distance.EarthRadiusInMiles : Distance.EarthRadiusInKilometers;
double latRadian = ToRadian(location.Latitude - this.Latitude);
double longRadian = ToRadian(location.Longitude - this.Longitude);
double a = Math.Pow(Math.Sin(latRadian / 2.0), 2) +
Math.Cos(ToRadian(this.Latitude)) *
Math.Cos(ToRadian(location.Latitude)) *
Math.Pow(Math.Sin(longRadian / 2.0), 2);
double c = 2.0 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
double distance = earthRadius * c;
return new Distance(distance, units);
}
public override bool Equals(object obj)
{
return Equals(obj as Location);
}
public bool Equals(Location coor)
{
if (coor == null)
return false;
return (this.Latitude == coor.Latitude && this.Longitude == coor.Longitude);
}
public override int GetHashCode()
{
return Latitude.GetHashCode() ^ Latitude.GetHashCode();
}
public override string ToString()
{
return string.Format("{0}, {1}", latitude, longitude);
}
}
} | mit |
canmogol/design-patterns | src/main/java/com/fererlab/pattern/creational/prototype/Axe.java | 444 | package com.fererlab.pattern.creational.prototype;
public class Axe extends Item {
private double weight;
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Axe{" +
"weight=" + weight +
" item='" + super.toString() + '\'' +
'}';
}
}
| mit |
h2obandtec/Site-H2O | WebH2O/default.aspx.designer.cs | 1526 | //------------------------------------------------------------------------------
// <gerado automaticamente>
// Este código foi gerado por uma ferramenta.
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for recriado
// </gerado automaticamente>
//------------------------------------------------------------------------------
namespace WebH2O {
public partial class index {
/// <summary>
/// Controle signin.
/// </summary>
/// <remarks>
/// Campo gerado automaticamente.
/// Modificar a declaração do campo de movimento do arquivo de designer para o arquivo code-behind.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm signin;
/// <summary>
/// Controle txtEmail.
/// </summary>
/// <remarks>
/// Campo gerado automaticamente.
/// Modificar a declaração do campo de movimento do arquivo de designer para o arquivo code-behind.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtEmail;
/// <summary>
/// Controle txtSenha.
/// </summary>
/// <remarks>
/// Campo gerado automaticamente.
/// Modificar a declaração do campo de movimento do arquivo de designer para o arquivo code-behind.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSenha;
}
}
| mit |
jeevad/pm-university | database/migrations/2016_06_20_081039_create_password_resets_table.php | 672 | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePasswordResetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('email')->index();
$table->string('token')->index();
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('password_resets');
}
}
| mit |
rightlag/jsonfeed | main.go | 541 | package main
import (
"flag"
"io/ioutil"
"log"
)
var (
file string
)
func init() {
flag.StringVar(&file, "file", "", "")
}
func main() {
flag.Parse()
if file == "" {
log.Fatal("main: argument -file is required")
}
b, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var parser FeedParser
root, err := parser.Parse(b)
if err != nil {
log.Fatal(err)
}
visitor := NewValidationVisitor()
root.Accept(visitor)
if visitor.HasErrors() {
for _, err := range visitor.Errors() {
log.Println(err)
}
}
}
| mit |
wesleyegberto/study-ocbcd | Ejb2ProjectBankClientTest/src/study/ejb3/projectbank/test/Util.java | 857 | package study.ejb3.projectbank.test;
import java.util.Properties;
import javax.naming.Context;
public class Util {
public static Properties getJndiJbossProperties() {
// These properties are used to initialize the InitialContext object of java naming service from JBoss
// and we need use the jar from %JBOSS_HOME%/bin/client/jboss-client.jar
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
properties.put(Context.PROVIDER_URL,"remote://127.0.0.1:4447");
// this user and password was added with a tool: %JBOSS_HOME%/bin/add-user.sh
properties.put(Context.SECURITY_PRINCIPAL, "user");
properties.put(Context.SECURITY_CREDENTIALS, "1234abc@");
properties.put("jboss.naming.client.ejb.context", Boolean.TRUE);
return properties;
}
}
| mit |
codeforamerica/michigan-benefits | app/controllers/integrated/student_loan_interest_controller.rb | 392 | module Integrated
class StudentLoanInterestController < FormsController
include SingleExpense
def self.skip_rule_sets(application)
[
SkipRules.must_be_applying_for_healthcare(application),
]
end
def expense_type
:student_loan_interest
end
def expense_collection
current_application.expenses.student_loan_interest
end
end
end
| mit |
EVAST9919/osu-framework | osu.Framework.Tests/Visual/Layout/TestSceneGridContainer.cs | 34589 | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Framework.Utils;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Layout
{
public class TestSceneGridContainer : FrameworkTestScene
{
private Container gridParent;
private GridContainer grid;
[SetUp]
public void Setup() => Schedule(() =>
{
Child = gridParent = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f),
Children = new Drawable[]
{
grid = new GridContainer { RelativeSizeAxes = Axes.Both },
new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
BorderColour = Color4.White,
BorderThickness = 2,
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
AlwaysPresent = true
}
}
}
};
});
[Test]
public void TestBlankGrid()
{
}
[Test]
public void TestSingleCellDistributedXy()
{
FillBox box = null;
AddStep("set content", () => grid.Content = new[] { new Drawable[] { box = new FillBox() }, });
AddAssert("box is same size as grid", () => Precision.AlmostEquals(box.DrawSize, grid.DrawSize));
}
[Test]
public void TestSingleCellAbsoluteXy()
{
const float size = 100;
FillBox box = null;
AddStep("set content", () =>
{
grid.Content = new[] { new Drawable[] { box = new FillBox() }, };
grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, size) };
});
AddAssert("box has expected size", () => Precision.AlmostEquals(box.DrawSize, new Vector2(size)));
}
[Test]
public void TestSingleCellRelativeXy()
{
const float size = 0.5f;
FillBox box = null;
AddStep("set content", () =>
{
grid.Content = new[] { new Drawable[] { box = new FillBox() }, };
grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, size) };
});
AddAssert("box has expected size", () => Precision.AlmostEquals(box.DrawSize, grid.DrawSize * new Vector2(size)));
}
[Test]
public void TestSingleCellRelativeXAbsoluteY()
{
const float absolute_height = 100;
const float relative_width = 0.5f;
FillBox box = null;
AddStep("set content", () =>
{
grid.Content = new[] { new Drawable[] { box = new FillBox() }, };
grid.RowDimensions = new[] { new Dimension(GridSizeMode.Absolute, absolute_height) };
grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, relative_width) };
});
AddAssert("box has expected width", () => Precision.AlmostEquals(box.DrawWidth, grid.DrawWidth * relative_width));
AddAssert("box has expected height", () => Precision.AlmostEquals(box.DrawHeight, absolute_height));
}
[Test]
public void TestSingleCellDistributedXRelativeY()
{
const float height = 0.5f;
FillBox box = null;
AddStep("set content", () =>
{
grid.Content = new[] { new Drawable[] { box = new FillBox() }, };
grid.RowDimensions = new[] { new Dimension(GridSizeMode.Relative, height) };
});
AddAssert("box has expected width", () => Precision.AlmostEquals(box.DrawWidth, grid.DrawWidth));
AddAssert("box has expected height", () => Precision.AlmostEquals(box.DrawHeight, grid.DrawHeight * height));
}
[TestCase(false)]
[TestCase(true)]
public void Test3CellRowOrColumnDistributedXy(bool row)
{
FillBox[] boxes = new FillBox[3];
setSingleDimensionContent(() => new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() }
}, row: row);
for (int i = 0; i < 3; i++)
{
int local = i;
if (row)
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth / 3f, grid.DrawHeight)));
else
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, grid.DrawHeight / 3f)));
}
}
[TestCase(false)]
[TestCase(true)]
public void Test3CellRowOrColumnDistributedXyAbsoluteYx(bool row)
{
var sizes = new[] { 50f, 100f, 75f };
var boxes = new FillBox[3];
setSingleDimensionContent(() => new[]
{
new Drawable[] { boxes[0] = new FillBox() },
new Drawable[] { boxes[1] = new FillBox() },
new Drawable[] { boxes[2] = new FillBox() },
}, new[]
{
new Dimension(GridSizeMode.Absolute, sizes[0]),
new Dimension(GridSizeMode.Absolute, sizes[1]),
new Dimension(GridSizeMode.Absolute, sizes[2])
}, row);
for (int i = 0; i < 3; i++)
{
int local = i;
if (row)
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, sizes[local])));
else
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(sizes[local], grid.DrawHeight)));
}
}
[TestCase(false)]
[TestCase(true)]
public void Test3CellRowOrColumnDistributedXyRelativeYx(bool row)
{
var sizes = new[] { 0.2f, 0.4f, 0.2f };
var boxes = new FillBox[3];
setSingleDimensionContent(() => new[]
{
new Drawable[] { boxes[0] = new FillBox() },
new Drawable[] { boxes[1] = new FillBox() },
new Drawable[] { boxes[2] = new FillBox() },
}, new[]
{
new Dimension(GridSizeMode.Relative, sizes[0]),
new Dimension(GridSizeMode.Relative, sizes[1]),
new Dimension(GridSizeMode.Relative, sizes[2])
}, row);
for (int i = 0; i < 3; i++)
{
int local = i;
if (row)
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, sizes[local] * grid.DrawHeight)));
else
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(sizes[local] * grid.DrawWidth, grid.DrawHeight)));
}
}
[TestCase(false)]
[TestCase(true)]
public void Test3CellRowOrColumnDistributedXyMixedYx(bool row)
{
var sizes = new[] { 0.2f, 75f };
var boxes = new FillBox[3];
setSingleDimensionContent(() => new[]
{
new Drawable[] { boxes[0] = new FillBox() },
new Drawable[] { boxes[1] = new FillBox() },
new Drawable[] { boxes[2] = new FillBox() },
}, new[]
{
new Dimension(GridSizeMode.Relative, sizes[0]),
new Dimension(GridSizeMode.Absolute, sizes[1]),
new Dimension(),
}, row);
if (row)
{
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(grid.DrawWidth, sizes[0] * grid.DrawHeight)));
AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(grid.DrawWidth, sizes[1])));
AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth, grid.DrawHeight - boxes[0].DrawHeight - boxes[1].DrawHeight)));
}
else
{
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(sizes[0] * grid.DrawWidth, grid.DrawHeight)));
AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(sizes[1], grid.DrawHeight)));
AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight)));
}
}
[Test]
public void Test3X3GridDistributedXy()
{
var boxes = new FillBox[9];
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() },
new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() },
new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() }
};
});
for (int i = 0; i < 9; i++)
{
int local = i;
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(grid.DrawSize / 3f, boxes[local].DrawSize));
}
}
[Test]
public void Test3X3GridAbsoluteXy()
{
var boxes = new FillBox[9];
var dimensions = new[]
{
new Dimension(GridSizeMode.Absolute, 50),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Absolute, 75)
};
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() },
new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() },
new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() }
};
grid.RowDimensions = grid.ColumnDimensions = dimensions;
});
for (int i = 0; i < 9; i++)
{
int local = i;
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(new Vector2(dimensions[local % 3].Size, dimensions[local / 3].Size), boxes[local].DrawSize));
}
}
[Test]
public void Test3X3GridRelativeXy()
{
var boxes = new FillBox[9];
var dimensions = new[]
{
new Dimension(GridSizeMode.Relative, 0.2f),
new Dimension(GridSizeMode.Relative, 0.4f),
new Dimension(GridSizeMode.Relative, 0.2f)
};
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() },
new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() },
new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() }
};
grid.RowDimensions = grid.ColumnDimensions = dimensions;
});
for (int i = 0; i < 9; i++)
{
int local = i;
AddAssert($"box {local} has correct size",
() => Precision.AlmostEquals(new Vector2(dimensions[local % 3].Size * grid.DrawWidth, dimensions[local / 3].Size * grid.DrawHeight), boxes[local].DrawSize));
}
}
[Test]
public void Test3X3GridMixedXy()
{
var boxes = new FillBox[9];
var dimensions = new[]
{
new Dimension(GridSizeMode.Absolute, 50),
new Dimension(GridSizeMode.Relative, 0.2f)
};
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() },
new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() },
new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() }
};
grid.RowDimensions = grid.ColumnDimensions = dimensions;
});
// Row 1
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(dimensions[0].Size, dimensions[0].Size)));
AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, dimensions[0].Size)));
AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, dimensions[0].Size)));
// Row 2
AddAssert("box 3 has correct size", () => Precision.AlmostEquals(boxes[3].DrawSize, new Vector2(dimensions[0].Size, grid.DrawHeight * dimensions[1].Size)));
AddAssert("box 4 has correct size", () => Precision.AlmostEquals(boxes[4].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, grid.DrawHeight * dimensions[1].Size)));
AddAssert("box 5 has correct size",
() => Precision.AlmostEquals(boxes[5].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight * dimensions[1].Size)));
// Row 3
AddAssert("box 6 has correct size", () => Precision.AlmostEquals(boxes[6].DrawSize, new Vector2(dimensions[0].Size, grid.DrawHeight - boxes[3].DrawHeight - boxes[0].DrawHeight)));
AddAssert("box 7 has correct size",
() => Precision.AlmostEquals(boxes[7].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, grid.DrawHeight - boxes[4].DrawHeight - boxes[1].DrawHeight)));
AddAssert("box 8 has correct size",
() => Precision.AlmostEquals(boxes[8].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight - boxes[5].DrawHeight - boxes[2].DrawHeight)));
}
[Test]
public void TestGridWithNullRowsAndColumns()
{
var boxes = new FillBox[4];
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), null, boxes[1] = new FillBox(), null },
null,
new Drawable[] { boxes[2] = new FillBox(), null, boxes[3] = new FillBox(), null },
null
};
});
AddAssert("two extra rows and columns", () =>
{
for (int i = 0; i < 4; i++)
{
if (!Precision.AlmostEquals(boxes[i].DrawSize, grid.DrawSize / 4))
return false;
}
return true;
});
}
[Test]
public void TestNestedGrids()
{
var boxes = new FillBox[4];
AddStep("set content", () =>
{
grid.Content = new[]
{
new Drawable[]
{
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[] { boxes[0] = new FillBox(), new FillBox(), },
new Drawable[] { new FillBox(), boxes[1] = new FillBox(), },
}
},
new FillBox(),
},
new Drawable[]
{
new FillBox(),
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[] { boxes[2] = new FillBox(), new FillBox(), },
new Drawable[] { new FillBox(), boxes[3] = new FillBox(), },
}
}
}
};
});
for (int i = 0; i < 4; i++)
{
int local = i;
AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, grid.DrawSize / 4));
}
}
[Test]
public void TestGridWithAutoSizingCells()
{
FillBox fillBox = null;
var autoSizingChildren = new Drawable[2];
AddStep("set content", () =>
{
grid.Content = new[]
{
new[]
{
autoSizingChildren[0] = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(50, 10)
},
fillBox = new FillBox(),
},
new[]
{
null,
autoSizingChildren[1] = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(50, 10)
},
},
};
grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize) };
grid.RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
};
});
AddAssert("fill box has correct size", () => Precision.AlmostEquals(fillBox.DrawSize, new Vector2(grid.DrawWidth - 50, grid.DrawHeight - 10)));
AddStep("rotate boxes", () => autoSizingChildren.ForEach(c => c.RotateTo(90)));
AddAssert("fill box has resized correctly", () => Precision.AlmostEquals(fillBox.DrawSize, new Vector2(grid.DrawWidth - 10, grid.DrawHeight - 50)));
}
[TestCase(false)]
[TestCase(true)]
public void TestDimensionsWithMaximumSize(bool row)
{
var boxes = new FillBox[8];
var dimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Distributed, maxSize: 100),
new Dimension(),
new Dimension(GridSizeMode.Distributed, maxSize: 50),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Distributed, maxSize: 80),
new Dimension(GridSizeMode.Distributed, maxSize: 150)
};
setSingleDimensionContent(() => new[]
{
new Drawable[]
{
boxes[0] = new FillBox(),
boxes[1] = new FillBox(),
boxes[2] = new FillBox(),
boxes[3] = new FillBox(),
boxes[4] = new FillBox(),
boxes[5] = new FillBox(),
boxes[6] = new FillBox(),
boxes[7] = new FillBox()
},
}.Invert(), dimensions, row);
checkClampedSizes(row, boxes, dimensions);
}
[TestCase(false)]
[TestCase(true)]
public void TestDimensionsWithMinimumSize(bool row)
{
var boxes = new FillBox[8];
var dimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Distributed, minSize: 100),
new Dimension(),
new Dimension(GridSizeMode.Distributed, minSize: 50),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Distributed, minSize: 80),
new Dimension(GridSizeMode.Distributed, minSize: 150)
};
setSingleDimensionContent(() => new[]
{
new Drawable[]
{
boxes[0] = new FillBox(),
boxes[1] = new FillBox(),
boxes[2] = new FillBox(),
boxes[3] = new FillBox(),
boxes[4] = new FillBox(),
boxes[5] = new FillBox(),
boxes[6] = new FillBox(),
boxes[7] = new FillBox()
},
}.Invert(), dimensions, row);
checkClampedSizes(row, boxes, dimensions);
}
[TestCase(false)]
[TestCase(true)]
public void TestDimensionsWithMinimumAndMaximumSize(bool row)
{
var boxes = new FillBox[8];
var dimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Distributed, minSize: 100),
new Dimension(),
new Dimension(GridSizeMode.Distributed, maxSize: 50),
new Dimension(GridSizeMode.Absolute, 100),
new Dimension(GridSizeMode.Distributed, minSize: 80),
new Dimension(GridSizeMode.Distributed, maxSize: 150)
};
setSingleDimensionContent(() => new[]
{
new Drawable[]
{
boxes[0] = new FillBox(),
boxes[1] = new FillBox(),
boxes[2] = new FillBox(),
boxes[3] = new FillBox(),
boxes[4] = new FillBox(),
boxes[5] = new FillBox(),
boxes[6] = new FillBox(),
boxes[7] = new FillBox()
},
}.Invert(), dimensions, row);
checkClampedSizes(row, boxes, dimensions);
}
[Test]
public void TestCombinedMinimumAndMaximumSize()
{
AddStep("set content", () =>
{
gridParent.Masking = false;
gridParent.RelativeSizeAxes = Axes.Y;
gridParent.Width = 420;
grid.Content = new[]
{
new Drawable[]
{
new FillBox(),
new FillBox(),
new FillBox(),
},
};
grid.ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Distributed, minSize: 180),
new Dimension(GridSizeMode.Distributed, minSize: 50, maxSize: 70),
new Dimension(GridSizeMode.Distributed, minSize: 40, maxSize: 70),
};
});
AddAssert("content spans grid size", () => Precision.AlmostEquals(grid.DrawWidth, grid.Content[0].Sum(d => d.DrawWidth)));
}
[Test]
public void TestCombinedMinimumAndMaximumSize2()
{
AddStep("set content", () =>
{
gridParent.Masking = false;
gridParent.RelativeSizeAxes = Axes.Y;
gridParent.Width = 230;
grid.Content = new[]
{
new Drawable[]
{
new FillBox(),
new FillBox(),
},
};
grid.ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Distributed, minSize: 180),
new Dimension(GridSizeMode.Distributed, minSize: 40, maxSize: 70),
};
});
AddAssert("content spans grid size", () => Precision.AlmostEquals(grid.DrawWidth, grid.Content[0].Sum(d => d.DrawWidth)));
}
[TestCase(true)]
[TestCase(false)]
public void TestAutoSizedCellsWithTransparentContent(bool alwaysPresent)
{
AddStep("set content", () =>
{
grid.RowDimensions = new[]
{
new Dimension(),
new Dimension(),
new Dimension(GridSizeMode.AutoSize)
};
grid.ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension()
};
grid.Content = new[]
{
new Drawable[] { new FillBox(), transparentBox(alwaysPresent), new FillBox() },
new Drawable[] { new FillBox(), transparentBox(alwaysPresent), new FillBox() },
new Drawable[] { transparentBox(alwaysPresent), transparentBox(alwaysPresent), transparentBox(alwaysPresent) }
};
});
float desiredTransparentBoxSize = alwaysPresent ? 50 : 0;
AddAssert("non-transparent fill boxes have correct size", () =>
grid.Content
.SelectMany(row => row)
.Where(box => box.Alpha > 0)
.All(box => Precision.AlmostEquals(box.DrawWidth, (grid.DrawWidth - desiredTransparentBoxSize) / 2)
&& Precision.AlmostEquals(box.DrawHeight, (grid.DrawHeight - desiredTransparentBoxSize) / 2)));
}
[TestCase(true)]
[TestCase(false)]
public void TestAutoSizedRowOrColumnWithTransparentContent(bool row)
{
var boxes = new FillBox[5];
var dimensions = new[]
{
new Dimension(GridSizeMode.Absolute, 100f),
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.Relative, 0.2f),
new Dimension()
};
setSingleDimensionContent(() => new[]
{
new Drawable[]
{
boxes[0] = new FillBox(),
boxes[1] = new FillBox(),
boxes[2] = transparentBox(false),
boxes[3] = new FillBox(),
boxes[4] = new FillBox()
}
}.Invert(), dimensions, row);
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(getDimension(boxes[0], row), 100f));
AddAssert("box 1 has correct size", () =>
Precision.AlmostEquals(getDimension(boxes[1], row), (getDimension(grid, row) * 0.8f - 100f) / 2));
AddAssert("box 3 has correct size", () => Precision.AlmostEquals(getDimension(boxes[3], row), getDimension(grid, row) * 0.2f));
AddAssert("box 4 has correct size", () =>
Precision.AlmostEquals(getDimension(boxes[4], row), (getDimension(grid, row) * 0.8f - 100f) / 2));
}
private FillBox transparentBox(bool alwaysPresent) => new FillBox
{
Alpha = 0,
AlwaysPresent = alwaysPresent,
RelativeSizeAxes = Axes.None,
Size = new Vector2(50)
};
[TestCase(true)]
[TestCase(false)]
public void TestAutoSizedRowOrColumnWithDelayedLifetimeContent(bool row)
{
var boxes = new FillBox[3];
var dimensions = new[]
{
new Dimension(GridSizeMode.Absolute, 75f),
new Dimension(GridSizeMode.AutoSize),
new Dimension()
};
setSingleDimensionContent(() => new[]
{
new Drawable[]
{
boxes[0] = new FillBox(),
boxes[1] = new FillBox
{
RelativeSizeAxes = Axes.None,
LifetimeStart = double.MaxValue,
Size = new Vector2(50)
},
boxes[2] = new FillBox()
}
}.Invert(), dimensions, row);
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(getDimension(boxes[0], row), 75f));
AddAssert("box 2 has correct size", () => Precision.AlmostEquals(getDimension(boxes[2], row), getDimension(grid, row) - 75f));
AddStep("make box 1 alive", () => boxes[1].LifetimeStart = Time.Current);
AddUntilStep("wait for alive", () => boxes[1].IsAlive);
AddAssert("box 0 has correct size", () => Precision.AlmostEquals(getDimension(boxes[0], row), 75f));
AddAssert("box 2 has correct size", () => Precision.AlmostEquals(getDimension(boxes[2], row), getDimension(grid, row) - 125f));
}
private bool gridContentChangeEventWasFired;
[Test]
public void TestSetContentByIndex()
{
setSingleDimensionContent(() => new[]
{
new Drawable[]
{
new FillBox(),
new FillBox()
},
new Drawable[]
{
new FillBox(),
new FillBox()
}
});
AddStep("Subscribe to event", () => grid.Content.ArrayElementChanged += () => gridContentChangeEventWasFired = true);
AddStep("Replace bottom right box with a SpriteText", () =>
{
gridContentChangeEventWasFired = false;
grid.Content[1][1] = new SpriteText { Text = new LocalisedString("test") };
});
assertContentChangeEventWasFired();
AddAssert("[1][1] cell contains a SpriteText", () => grid.Content[1][1].GetType() == typeof(SpriteText));
AddStep("Replace top line with [SpriteText][null]", () =>
{
gridContentChangeEventWasFired = false;
grid.Content[0] = new Drawable[] { new SpriteText { Text = new LocalisedString("test") }, null };
});
assertContentChangeEventWasFired();
AddAssert("[0][0] cell contains a SpriteText", () => grid.Content[0][0].GetType() == typeof(SpriteText));
AddAssert("[0][1] cell contains null", () => grid.Content[0][1] == null);
void assertContentChangeEventWasFired() => AddAssert("Content change event was fired", () => gridContentChangeEventWasFired);
}
/// <summary>
/// Returns drawable dimension along desired axis.
/// </summary>
private float getDimension(Drawable drawable, bool row) => row ? drawable.DrawHeight : drawable.DrawWidth;
private void checkClampedSizes(bool row, FillBox[] boxes, Dimension[] dimensions)
{
AddAssert("sizes not over/underflowed", () =>
{
for (int i = 0; i < 8; i++)
{
if (dimensions[i].Mode != GridSizeMode.Distributed)
continue;
if (row && (boxes[i].DrawHeight > dimensions[i].MaxSize || boxes[i].DrawHeight < dimensions[i].MinSize))
return false;
if (!row && (boxes[i].DrawWidth > dimensions[i].MaxSize || boxes[i].DrawWidth < dimensions[i].MinSize))
return false;
}
return true;
});
AddAssert("column span total length", () =>
{
float expectedSize = row ? grid.DrawHeight : grid.DrawWidth;
float totalSize = row ? boxes.Sum(b => b.DrawHeight) : boxes.Sum(b => b.DrawWidth);
// Allowed to exceed the length of the columns due to absolute sizing
return totalSize >= expectedSize;
});
}
private void setSingleDimensionContent(Func<Drawable[][]> contentFunc, Dimension[] dimensions = null, bool row = false) => AddStep("set content", () =>
{
var content = contentFunc();
if (!row)
content = content.Invert();
grid.Content = content;
if (dimensions == null)
return;
if (row)
grid.RowDimensions = dimensions;
else
grid.ColumnDimensions = dimensions;
});
private class FillBox : Box
{
public FillBox()
{
RelativeSizeAxes = Axes.Both;
Colour = new Color4(RNG.NextSingle(1), RNG.NextSingle(1), RNG.NextSingle(1), 1);
}
}
}
}
| mit |
welphexa/hexabot | src/main/java/Triggers.java | 3679 | import pro.zackpollard.telegrambot.api.TelegramBot;
import pro.zackpollard.telegrambot.api.chat.ChatType;
import pro.zackpollard.telegrambot.api.chat.message.send.SendableTextMessage;
import pro.zackpollard.telegrambot.api.event.Listener;
import pro.zackpollard.telegrambot.api.event.chat.ParticipantJoinGroupChatEvent;
import pro.zackpollard.telegrambot.api.event.chat.ParticipantLeaveGroupChatEvent;
import pro.zackpollard.telegrambot.api.event.chat.message.CommandMessageReceivedEvent;
import pro.zackpollard.telegrambot.api.event.chat.message.VoiceMessageReceivedEvent;
public class Triggers implements Listener {
private TelegramBot telegramBot;
private static boolean triggers = true;
public Triggers(TelegramBot telegramBot) {
this.telegramBot = telegramBot;
}
@Override
public void onCommandMessageReceived(CommandMessageReceivedEvent event) {
ChatType chatType = event.getChat().getType();
String username = event.getMessage().getSender().getUsername();
String receivedMessage = event.getContent().getContent();
long id = event.getMessage().getSender().getId();
SendableTextMessage message;
if (receivedMessage.startsWith("/triggers") && (Main.admins.contains(username) || id == Main.id)) {
try {
String[] arr = receivedMessage.split(" ");
if (arr[1].equalsIgnoreCase("on")) {
triggers = true;
message = SendableTextMessage.builder().message("Triggers set to ON").build();
telegramBot.sendMessage(event.getChat(), message);
} else if (arr[1].equalsIgnoreCase("off")) {
triggers = false;
message = SendableTextMessage.builder().message("Triggers set to OFF").build();
telegramBot.sendMessage(event.getChat(), message);
}
} catch (Exception e) {
e.getMessage();
}
}
if (triggers && (receivedMessage.equals("/kickme") && !(chatType == ChatType.PRIVATE))) {
message = SendableTextMessage.builder().message("And dont come back!").build();
telegramBot.sendMessage(event.getChat(), message);
}
if (triggers && (receivedMessage.equals("/ban") && !(chatType == ChatType.PRIVATE))) {
message = SendableTextMessage.builder().message("Harsh").replyTo(event.getMessage()).build();
telegramBot.sendMessage(event.getChat(), message);
}
if (receivedMessage.startsWith("/admin") && id == Main.id) {
String[] arr = receivedMessage.split(" ");
Main.admins.add(arr[1]);
}
if (receivedMessage.startsWith("/unadmin") && id == Main.id) {
String[] arr = receivedMessage.split(" ");
Main.admins.remove(arr[1]);
}
}
@Override
public void onParticipantJoinGroupChat(ParticipantJoinGroupChatEvent event) {
String name = event.getMessage().getSender().getFullName();
if (triggers && !(event.getMessage().getSender().getId() == Main.id)) {
SendableTextMessage message = SendableTextMessage.builder().message("Hi " + name + ". Welcome?").build();
telegramBot.sendMessage(event.getChat(), message);
}
}
@Override
public void onParticipantLeaveGroupChat(ParticipantLeaveGroupChatEvent event) {
if (triggers) {
SendableTextMessage message = SendableTextMessage.builder().message("My favorite person left :(").build();
telegramBot.sendMessage(event.getChat(), message);
}
}
@Override
public void onVoiceMessageReceived(VoiceMessageReceivedEvent event) {
if (triggers) {
SendableTextMessage message = SendableTextMessage.builder().message("This is cancer").replyTo(event.getMessage()).build();
telegramBot.sendMessage(event.getChat(), message);
}
}
} | mit |
dclaysmith/generator | src/dclaysmith/Generator/Database/Table/Column.php | 402 | <?php
/*
* This file is part of Generator.
*
* (c) D Clay Smith <dclaysmith@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace dclaysmith\Generator\Database\Table;
/**
* Representation of a single column in a database
* @author D Clay Smith <dclaysmith@gmail.com>
*/
class Column
{
}
?> | mit |
bartsch-dev/jabref | src/main/java/org/jabref/logic/importer/fileformat/BibtexImporter.java | 5377 | package org.jabref.logic.importer.fileformat;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
import org.jabref.logic.exporter.SavePreferences;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.util.FileExtensions;
/**
* This importer exists only to enable `--importToOpen someEntry.bib`
*
* It is NOT intended to import a BIB file. This is done via the option action, which treats the metadata fields
* The metadata is not required to be read here, as this class is NOT called at --import
*/
public class BibtexImporter extends Importer {
// Signature written at the top of the .bib file in earlier versions.
private static final String SIGNATURE = "This file was created with JabRef";
private final ImportFormatPreferences importFormatPreferences;
public BibtexImporter(ImportFormatPreferences importFormatPreferences) {
this.importFormatPreferences = importFormatPreferences;
}
/**
* @return true as we have no effective way to decide whether a file is in bibtex format or not. See
* https://github.com/JabRef/jabref/pull/379#issuecomment-158685726 for more details.
*/
@Override
public boolean isRecognizedFormat(BufferedReader reader) {
Objects.requireNonNull(reader);
return true;
}
@Override
public ParserResult importDatabase(Path filePath, Charset defaultEncoding) throws IOException {
// We want to check if there is a JabRef signature in the file, because that would tell us
// which character encoding is used. However, to read the signature we must be using a compatible
// encoding in the first place. Since the signature doesn't contain any fancy characters, we can
// read it regardless of encoding, with either UTF-8 or UTF-16. That's the hypothesis, at any rate.
// 8 bit is most likely, so we try that first:
Optional<Charset> suppliedEncoding;
try (BufferedReader utf8Reader = getUTF8Reader(filePath)) {
suppliedEncoding = getSuppliedEncoding(utf8Reader);
}
// Now if that did not get us anywhere, we check with the 16 bit encoding:
if (!suppliedEncoding.isPresent()) {
try (BufferedReader utf16Reader = getUTF16Reader(filePath)) {
suppliedEncoding = getSuppliedEncoding(utf16Reader);
}
}
if(suppliedEncoding.isPresent()) {
return super.importDatabase(filePath, suppliedEncoding.get());
} else {
return super.importDatabase(filePath, defaultEncoding);
}
}
@Override
public ParserResult importDatabase(BufferedReader reader) throws IOException {
return new BibtexParser(importFormatPreferences).parse(reader);
}
@Override
public String getName() {
return "BibTeX";
}
@Override
public FileExtensions getExtensions() {
return FileExtensions.BIBTEX_DB;
}
@Override
public String getDescription() {
return "This importer exists only to enable `--importToOpen someEntry.bib`\n" +
"It is NOT intended to import a BIB file. This is done via the option action, which treats the metadata fields.\n" +
"The metadata is not required to be read here, as this class is NOT called at --import.";
}
/**
* Searches the file for "Encoding: myEncoding" and returns the found supplied encoding.
*/
private static Optional<Charset> getSuppliedEncoding(BufferedReader reader) {
try {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
// Line does not start with %, so there are no comment lines for us and we can stop parsing
if (!line.startsWith("%")) {
return Optional.empty();
}
// Only keep the part after %
line = line.substring(1).trim();
if (line.startsWith(BibtexImporter.SIGNATURE)) {
// Signature line, so keep reading and skip to next line
} else if (line.startsWith(SavePreferences.ENCODING_PREFIX)) {
// Line starts with "Encoding: ", so the rest of the line should contain the name of the encoding
// Except if there is already a @ symbol signaling the starting of a BibEntry
Integer atSymbolIndex = line.indexOf('@');
String encoding;
if (atSymbolIndex > 0) {
encoding = line.substring(SavePreferences.ENCODING_PREFIX.length(), atSymbolIndex);
} else {
encoding = line.substring(SavePreferences.ENCODING_PREFIX.length());
}
return Optional.of(Charset.forName(encoding));
} else {
// Line not recognized so stop parsing
return Optional.empty();
}
}
} catch (IOException ignored) {
// Ignored
}
return Optional.empty();
}
}
| mit |
vorquel/SimpleSkyGrid | src/main/java/vorquel/mod/simpleskygrid/config/prototype/generation/PGeneric.java | 3996 | package vorquel.mod.simpleskygrid.config.prototype.generation;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import vorquel.mod.simpleskygrid.config.SimpleSkyGridConfigReader;
import vorquel.mod.simpleskygrid.config.prototype.Prototype;
import vorquel.mod.simpleskygrid.helper.Pair;
import vorquel.mod.simpleskygrid.world.generated.GeneratedBlock;
import vorquel.mod.simpleskygrid.world.generated.IGeneratedObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class PGeneric extends Prototype<IGeneratedObject> {
private String name;
private ArrayList<String> names;
private boolean stasis;
public PGeneric(SimpleSkyGridConfigReader reader) {
super(reader);
}
@Override
protected void readLabel(SimpleSkyGridConfigReader reader, String label) {
switch(label) {
case "name": name = reader.nextString(); return;
case "names": readNames(reader); return;
case "stasis": stasis = reader.nextBoolean(); return;
default: reader.unknownOnce("label " + label, "generic block definition");
}
}
private void readNames(SimpleSkyGridConfigReader reader) {
names = new ArrayList<>();
reader.beginArray();
while(reader.hasNext())
names.add(reader.nextString());
reader.endArray();
}
@Override
public boolean isComplete() {
return name != null || (names != null && !names.isEmpty());
}
@Override
public IGeneratedObject getObject() {
if(name != null) {
for(ItemStack stack : OreDictionary.getOres(name)) {
if(stack == null)
continue;
Item item = stack.getItem();
Block block = Block.getBlockFromItem(item);
if(block == Blocks.AIR)
continue;
int meta = item.getMetadata(stack.getMetadata());
return new GeneratedBlock(block, meta, null, stasis);
}
if(names == null)
return null;
}
Map<Pair<Block, Integer>, ArrayList<String>> blockMap = new HashMap<>();
ArrayList<String> usedNames = new ArrayList<>();
for(String name : names) {
boolean isNameUsed = false;
for(ItemStack stack : OreDictionary.getOres(name)) {
if(stack == null)
continue;
Item item = stack.getItem();
Block block = Block.getBlockFromItem(item);
if(block == Blocks.AIR)
continue;
int meta = item.getMetadata(stack.getMetadata());
Pair<Block, Integer> pair = new Pair<>(block, meta);
if(!blockMap.containsKey(pair))
blockMap.put(pair, new ArrayList<String>());
blockMap.get(pair).add(name);
isNameUsed = true;
}
if(isNameUsed)
usedNames.add(name);
}
if(usedNames.isEmpty())
return null;
for(String name : usedNames) {
Iterator<Map.Entry<Pair<Block, Integer>, ArrayList<String>>> iterator = blockMap.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<Pair<Block, Integer>, ArrayList<String>> entry = iterator.next();
Pair<Block, Integer> pair = entry.getKey();
if(!entry.getValue().contains(name))
iterator.remove();
if(blockMap.isEmpty())
return new GeneratedBlock(pair.left, pair.right, null, stasis);
}
}
Pair<Block, Integer> pair = blockMap.keySet().iterator().next();
return new GeneratedBlock(pair.left, pair.right, null, stasis);
}
}
| mit |
vr-the-feedback/vr-the-feedback-unity | Assets/VRTheFeedback/Scripts/OggVorbisEncoder/Setup/Templates/BookBlocks/Stereo44/Coupled/Chapter9/Page5_0.cs | 872 | namespace OggVorbisEncoder.Setup.Templates.BookBlocks.Stereo44.Coupled.Chapter9
{
public class Page5_0 : IStaticCodeBook
{
public int Dimensions { get; } = 4;
public byte[] LengthList { get; } = {
1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
12,
};
public CodeBookMapType MapType { get; } = (CodeBookMapType)1;
public int QuantMin { get; } = -529137664;
public int QuantDelta { get; } = 1618345984;
public int Quant { get; } = 2;
public int QuantSequenceP { get; } = 0;
public int[] QuantList { get; } = {
1,
0,
2,
};
}
} | mit |
isysd/apistore | test/unit/controllers/CategoryController.test.js | 4386 | var request = require('supertest');
var should = require('should');
var REQUIRED_CATEGORY = "Bill Pay";
var mpath = '/category';
describe('CategoryController', function() {
describe('find()', function() {
it('Can find default list', function (done) {
request(sails.hooks.http.app)
.get(mpath)
.send()
.expect('_csrf', new RegExp('^.{16,}$')) // _csrf token exists and is > 16 chars
.expect('Content-Type', /json/)
.expect(200, done);
});
it('Find with where query', function (done) {
var query = {"name":{"contains": REQUIRED_CATEGORY}};
var jquery = JSON.stringify(query);
request(sails.hooks.http.app)
.get(mpath)
.query({where:jquery})
.expect('_csrf', new RegExp('^.{16,}$')) // _csrf token exists and is > 16 chars
.expect('Content-Type', /json/)
.expect(200)
.end(function(error, result) {
if (error) {
done(error);
}
result.req.path.should.be.equal(mpath + '?where=' + encodeURIComponent(jquery));
result.body.should.have.lengthOf(1);
result.body[0].should.have.property['name'];
result.body[0]['name'].should.containEql(REQUIRED_CATEGORY);
done();
});
});
it('Find with bad where query returns empty results', function (done) {
var query = {"name":{"contains": REQUIRED_CATEGORY + " bad"}};
var jquery = JSON.stringify(query);
request(sails.hooks.http.app)
.get(mpath)
.query({where:jquery})
.expect('_csrf', new RegExp('^.{16,}$')) // _csrf token exists and is > 16 chars
.expect('Content-Type', /json/)
.expect(200)
.end(function(error, result) {
if (error) {
done(error);
}
result.req.path.should.be.equal(mpath + '?where=' + encodeURIComponent(jquery));
result.body.should.have.lengthOf(0);
done();
});
});
it('Find with malformed where query returns default results', function (done) {
var query = {"name":{"contains": REQUIRED_CATEGORY + " bad"}};
var jquery = JSON.stringify(query).substring(2, 12); // this will no longer be valid json
request(sails.hooks.http.app)
.get(mpath)
.query({where:jquery})
.expect('_csrf', new RegExp('^.{16,}$')) // _csrf token exists and is > 16 chars
.expect('Content-Type', /json/)
.expect(200)
.end(function(error, result) {
if (error) {
done(error);
} else {
result.req.path.should.be.equal(mpath + '?where=' + encodeURIComponent(jquery));
result.body.should.not.have.lengthOf(0); // returns default results
done();
}
});
});
});
describe('create()', function() {
it('Cannot create a category', function (done) {
request(sails.hooks.http.app)
.post(mpath)
.send()
.expect(403, done);
});
});
describe('update()', function() {
it('Cannot update a category', function (done) {
var hackstring = "IhaxURstore";
request(sails.hooks.http.app)
.put(mpath)
.send({'name': hackstring})
.expect(403)
.end(function(err, res) {
request(sails.hooks.http.app)
.get(mpath)
.query({where:JSON.stringify({"name":hackstring})})
.expect('_csrf', new RegExp('^.{16,}$')) // _csrf token exists and is > 16 chars
.expect('Content-Type', /json/)
.expect(200)
.end(function(error, result) {
if (error) {
done(error);
} else {
result.body.should.have.lengthOf(0);
done();
}
});
});
});
});
describe('destroy()', function() {
it('Cannot delete a category', function (done) {
request(sails.hooks.http.app)
.delete(mpath)
.send({'name': REQUIRED_CATEGORY})
.expect(403)
.end(function(err, res) {
request(sails.hooks.http.app)
.get(mpath)
.query({'name': REQUIRED_CATEGORY})
.expect('_csrf', new RegExp('^.{16,}$')) // _csrf token exists and is > 16 chars
.expect('Content-Type', /json/)
.expect(200)
.end(function(error, result) {
if (error) {
done(error);
} else {
result.body.should.have.lengthOf(1);
done();
}
});
});
});
});
}); | mit |
VincentTide/vincenttide | app/__init__.py | 706 | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.moment import Moment
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config.from_object('config')
# Make sure we declare db first before importing views or models
db = SQLAlchemy(app)
# Flask-Login
login_manager = LoginManager(app)
login_manager.login_view = 'login'
# Extensions initialization
moment = Moment(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
from app.models import Role, User
# Import views at the end
from app import views, views_admin
| mit |
cameronhunter/glacier-cli | src/main/java/uk/co/cameronhunter/aws/glacier/actions/Upload.java | 2444 | package uk.co.cameronhunter.aws.glacier.actions;
import com.amazonaws.services.glacier.transfer.ArchiveTransferManager;
import com.amazonaws.services.glacier.transfer.UploadResult;
import org.apache.commons.lang.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import uk.co.cameronhunter.aws.glacier.domain.Archive;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;
import static org.apache.commons.io.FileUtils.byteCountToDisplaySize;
import static uk.co.cameronhunter.aws.glacier.utils.Check.notBlank;
import static uk.co.cameronhunter.aws.glacier.utils.Check.notNull;
public class Upload implements Callable<Archive> {
private static final Log LOG = LogFactory.getLog(Upload.class);
private final ArchiveTransferManager transferManager;
private final String vault;
private final File archive;
public Upload(ArchiveTransferManager transferManager, String vault, File archive) {
this.transferManager = notNull(transferManager);
this.vault = notBlank(vault);
this.archive = validate(archive);
}
@Override
public Archive call() {
try {
return upload(archive, vault, transferManager);
} catch (Exception e) {
LOG.error("Failed to upload archive \"" + archive + "\" to vault \"" + vault + "\"", e);
throw new RuntimeException(e);
}
}
private static File validate(File upload) {
Validate.notNull(upload);
Validate.isTrue(upload.exists(), "File \"" + upload.getAbsolutePath() + "\" doesn't exist");
Validate.isTrue(upload.isFile(), "Cannot directly upload a directory to Glacier. Create an archive from it first.");
return upload;
}
private static Archive upload(File upload, String vault, ArchiveTransferManager transferManager) throws IOException {
String filename = upload.getName();
LOG.info("Uploading \"" + filename + "\" (" + byteCountToDisplaySize(upload.length()) + ") to vault \"" + vault + "\"");
UploadResult result = transferManager.upload(vault, filename, upload);
LOG.info("Archive \"" + filename + "\" successfully uploaded to vault \"" + vault + "\"");
return new Archive(result.getArchiveId(), filename, new DateTime(DateTimeZone.UTC), upload.length());
}
}
| mit |
HosseinChibane/CFPMS | var/cache/dev/twig/1c/1cf8ae9dcb7677f5a03f123ccbee932a540b154df999e8e5d5e3b05d8bfc7b69.php | 3506 | <?php
/* @EasyAdmin/default/field_float.html.twig */
class __TwigTemplate_ed68c5c81f73a7689211885813593f78d04915255b1162e4c169b418470ac099 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())
{
$__internal_3215a31fb9bb1188c119731cbf0f14879dc150d8862303ea01c6f888ab142e6d = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
$__internal_3215a31fb9bb1188c119731cbf0f14879dc150d8862303ea01c6f888ab142e6d->enter($__internal_3215a31fb9bb1188c119731cbf0f14879dc150d8862303ea01c6f888ab142e6d_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@EasyAdmin/default/field_float.html.twig"));
$__internal_7f47db9fd8b34ad682a380ebec9ae53ba3b6b727cda24ea42415a1243eee4d2d = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_7f47db9fd8b34ad682a380ebec9ae53ba3b6b727cda24ea42415a1243eee4d2d->enter($__internal_7f47db9fd8b34ad682a380ebec9ae53ba3b6b727cda24ea42415a1243eee4d2d_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@EasyAdmin/default/field_float.html.twig"));
// line 1
if ($this->getAttribute(($context["field_options"] ?? $this->getContext($context, "field_options")), "format", array())) {
// line 2
echo " ";
echo twig_escape_filter($this->env, sprintf($this->getAttribute(($context["field_options"] ?? $this->getContext($context, "field_options")), "format", array()), ($context["value"] ?? $this->getContext($context, "value"))), "html", null, true);
echo "
";
} else {
// line 4
echo " ";
echo twig_escape_filter($this->env, twig_number_format_filter($this->env, ($context["value"] ?? $this->getContext($context, "value")), 2), "html", null, true);
echo "
";
}
$__internal_3215a31fb9bb1188c119731cbf0f14879dc150d8862303ea01c6f888ab142e6d->leave($__internal_3215a31fb9bb1188c119731cbf0f14879dc150d8862303ea01c6f888ab142e6d_prof);
$__internal_7f47db9fd8b34ad682a380ebec9ae53ba3b6b727cda24ea42415a1243eee4d2d->leave($__internal_7f47db9fd8b34ad682a380ebec9ae53ba3b6b727cda24ea42415a1243eee4d2d_prof);
}
public function getTemplateName()
{
return "@EasyAdmin/default/field_float.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 33 => 4, 27 => 2, 25 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% if field_options.format %}
{{ field_options.format|format(value) }}
{% else %}
{{ value|number_format(2) }}
{% endif %}
", "@EasyAdmin/default/field_float.html.twig", "C:\\wamp64\\www\\Projet\\CFPMS\\siteweb\\dudeego\\vendor\\javiereguiluz\\easyadmin-bundle\\Resources\\views\\default\\field_float.html.twig");
}
}
| mit |
marteserede/opensourcepos | application/views/giftcards/manage.php | 2609 | <?php $this->load->view("partial/header"); ?>
<script type="text/javascript">
$(document).ready(function()
{
init_table_sorting();
enable_select_all();
enable_checkboxes();
enable_row_selection();
enable_search({suggest_url: '<?php echo site_url("$controller_name/suggest")?>',
confirm_search_messsage: 'w<?php echo $this->lang->line("common_confirm_search")?>'});
enable_delete('<?php echo $this->lang->line($controller_name."_confirm_delete")?>','<?php echo $this->lang->line($controller_name."_none_selected")?>');
});
function init_table_sorting()
{
//Only init if there is more than one row
if($('.tablesorter tbody tr').length >1)
{
$("#sortable_table").tablesorter(
{
sortList: [[1,0]],
headers:
{
0: { sorter: false}
}
});
}
}
function post_giftcard_form_submit(response)
{
if(!response.success)
{
set_feedback(response.message,'error_message',true);
}
else
{
//This is an update, just update one row
if(jQuery.inArray(response.giftcard_id,get_visible_checkbox_ids()) != -1)
{
update_row(response.giftcard_id,'<?php echo site_url("$controller_name/get_row")?>');
set_feedback(response.message,'success_message',false);
}
else //refresh entire table
{
do_search(true,function()
{
//highlight new row
hightlight_row(response.giftcard_id);
set_feedback(response.message,'success_message',false);
});
}
}
}
</script>
<div id="title_bar">
<div id="title" class="float_left"><?php echo $this->lang->line('common_list_of').' '.$this->lang->line('module_'.$controller_name); ?></div>
<div id="new_button">
<?php echo anchor("$controller_name/view/-1/width:$form_width",
"<div class='big_button' style='float: left;'><span>".$this->lang->line($controller_name.'_new')."</span></div>",
array('class'=>'thickbox none','title'=>$this->lang->line($controller_name.'_new')));
?>
</div>
</div>
<div id="pagination"><?= $links ?></div>
<div id="table_action_header">
<ul>
<li class="float_left"><span><?php echo anchor("$controller_name/delete",$this->lang->line("common_delete"),array('id'=>'delete')); ?></span></li>
<li class="float_right">
<img src='<?php echo base_url()?>images/spinner_small.gif' alt='spinner' id='spinner' />
<?php echo form_open("$controller_name/search",array('id'=>'search_form')); ?>
<input type="text" name ='search' id='search'/>
<input type="hidden" name ='limit_from' id='limit_from'/>
</form>
</li>
</ul>
</div>
<div id="table_holder">
<?php echo $manage_table; ?>
</div>
<div id="feedback_bar"></div>
<?php $this->load->view("partial/footer"); ?> | mit |
whuailin/dogdie | vendor/anomaly/streams-platform/migrations/core/2015_03_15_171506_create_applications_domains_table.php | 1150 | <?php
use Anomaly\Streams\Platform\Database\Migration\Migration;
use Illuminate\Database\Schema\Blueprint;
/**
* Class CreateApplicationsDomainsTable
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <support@pyrocms.com>
* @author Ryan Thompson <ryan@pyrocms.com>
*/
class CreateApplicationsDomainsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::connection('core')->hasTable('applications_domains')) {
Schema::connection('core')->create(
'applications_domains',
function (Blueprint $table) {
$table->increments('id');
$table->integer('application_id');
$table->string('domain');
$table->string('locale');
$table->unique('domain', 'unique_domains');
}
);
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::connection('core')->dropIfExists('applications_domains');
}
}
| mit |
DarthJonathan/GrandABEHotel | application/views/admin/location/add_location_view.php | 2457 | <?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<script type="text/javascript">
tinymce.init({
selector:'#ta_locationDesc'
});
</script>
<div class="container">
<div class="col-lg-10 col-lg-offset-1">
<div class="col-lg-12 text-center">
<h3>Add Location</h3>
</div>
<?php echo form_open_multipart('admin/location/addlocation',array('class'=>'form-horizontal')); ?>
<div class="form-group">
<label for="ta_locationName" class="control-label col-sm-3">Location Name:</label>
<div class="col-sm-9">
<input type="text" class="form-control " id="ta_locationName" name="ta_locationName">
</div>
<?php echo form_error('ta_locationName','<div style="color:red;">','</div>');?>
</div>
<div class="form-group">
<label for="upload_location" class="control-label col-sm-3">Location Image:</label>
<div class="col-sm-4">
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-default">
Browse… <input type="file" style="display: none;" id="upload_location" accept=".png,.jpg,.jpeg,.gif" name="upload_location">
</span>
</label>
<input type="text" class="form-control" name="txtlocation" readonly>
</div>
</div>
<div class="col-sm-5" >
<div class="imgDiv">
<img src="<?php echo base_url() ?>assets/images/img_placeholder.png" id="img_location" >
</div>
</div>
<?php echo form_error('txtlocation','<div style="color:red;">','</div>');?>
<?php echo form_error('upload_location','<div style="color:red;">','</div>');?>
</div>
<div class="form-group">
<label for = "ta_locationDesc" class="control-label col-sm-3">Location Description:</label>
<div class="col-sm-9">
<textarea id="ta_locationDesc" name="ta_locationDesc"></textarea>
</div>
<?php echo form_error('ta_locationDesc','<div style="color:red;">','</div>');?>
</div>
<?php echo form_submit('submit' , 'Add' , 'class="btn btn-primary col-lg-offset-3"');?>
<?php echo form_close();?>
<br>
<br>
</div>
</div>
<script type="text/javascript">
document.getElementById('upload_location').onchange = function(e) {
// Get the first file in the FileList object
var imageFile = this.files[0];
// get a local URL representation of the image blob
var url = window.URL.createObjectURL(imageFile);
// Now use your newly created URL!
img_location.src = url;
}
</script>
| mit |
hoya0704/resortPrice | application/helpers/alert_helper.php | 1052 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
//메시지 출력 후 이동
function alert($msg='이동합니다.', $url = '')
{
$CI =& get_instance();
echo "<meta http-equiv = \"content-type\" content = \"text/html; charset = " .$CI->config->item('charset') . "\">";
echo "<script>
alert('".$msg."');
location.replace('" .$url ."');
</script> ";
exit;
}
//창 닫기
function alert_close($msg)
{
$CI =& get_instance();
echo "<meta http-equiv = \"content-type\" content = \"text/html; charset = " .$CI->config->item('charset') . "\">";
echo "<script> alert('" .$msg."'); window.close(); </script>";
exit;
}
//경고창만
function alert_only($msg, $exit = TRUE)
{
echo "<meta http-equiv = \"content-type\" content = \"text/html; charset = " .$CI->config->item('charset') . "\">";
echo "<script> alert('" .$msg."'); </script>";
if ($exit) exit;
}
function replace($url='/')
{
echo "<script> ";
if ($url) echo "window.location.replace('" .$url ."');";
echo "<script> ";
exit;
}
/* End of file */ | mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highcharts/config/PlotOptionsVectorPathfinderStartMarker.scala | 5769 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highcharts]]
*/
package com.highcharts.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-vector-pathfinder-startMarker</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsVectorPathfinderStartMarker extends com.highcharts.HighchartsGenericObject {
/**
* <p>Set the symbol of the pathfinder start markers.</p>
* @since 6.2.0
*/
val symbol: js.UndefOr[String] = js.undefined
/**
* <p>Enable markers for the connectors.</p>
* @since 6.2.0
*/
val enabled: js.UndefOr[Boolean] = js.undefined
/**
* <p>Horizontal alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val align: js.UndefOr[String] = js.undefined
/**
* <p>Vertical alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val verticalAlign: js.UndefOr[String] = js.undefined
/**
* <p>Whether or not to draw the markers inside the points.</p>
* @since 6.2.0
*/
val inside: js.UndefOr[Boolean] = js.undefined
/**
* <p>Set the line/border width of the pathfinder markers.</p>
* @since 6.2.0
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>Set the radius of the pathfinder markers. The default is
* automatically computed based on the algorithmMargin setting.</p>
* <p>Setting marker.width and marker.height will override this
* setting.</p>
* @since 6.2.0
*/
val radius: js.UndefOr[Double] = js.undefined
/**
* <p>Set the width of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val width: js.UndefOr[Double] = js.undefined
/**
* <p>Set the height of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val height: js.UndefOr[Double] = js.undefined
/**
* <p>Set the color of the pathfinder markers. By default this is the
* same as the connector color.</p>
* @since 6.2.0
*/
val color: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Set the line/border color of the pathfinder markers. By default
* this is the same as the marker color.</p>
* @since 6.2.0
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
}
object PlotOptionsVectorPathfinderStartMarker {
/**
* @param symbol <p>Set the symbol of the pathfinder start markers.</p>
* @param enabled <p>Enable markers for the connectors.</p>
* @param align <p>Horizontal alignment of the markers relative to the points.</p>
* @param verticalAlign <p>Vertical alignment of the markers relative to the points.</p>
* @param inside <p>Whether or not to draw the markers inside the points.</p>
* @param lineWidth <p>Set the line/border width of the pathfinder markers.</p>
* @param radius <p>Set the radius of the pathfinder markers. The default is. automatically computed based on the algorithmMargin setting.</p>. <p>Setting marker.width and marker.height will override this. setting.</p>
* @param width <p>Set the width of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param height <p>Set the height of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param color <p>Set the color of the pathfinder markers. By default this is the. same as the connector color.</p>
* @param lineColor <p>Set the line/border color of the pathfinder markers. By default. this is the same as the marker color.</p>
*/
def apply(symbol: js.UndefOr[String] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, align: js.UndefOr[String] = js.undefined, verticalAlign: js.UndefOr[String] = js.undefined, inside: js.UndefOr[Boolean] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, width: js.UndefOr[Double] = js.undefined, height: js.UndefOr[Double] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined): PlotOptionsVectorPathfinderStartMarker = {
val symbolOuter: js.UndefOr[String] = symbol
val enabledOuter: js.UndefOr[Boolean] = enabled
val alignOuter: js.UndefOr[String] = align
val verticalAlignOuter: js.UndefOr[String] = verticalAlign
val insideOuter: js.UndefOr[Boolean] = inside
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val radiusOuter: js.UndefOr[Double] = radius
val widthOuter: js.UndefOr[Double] = width
val heightOuter: js.UndefOr[Double] = height
val colorOuter: js.UndefOr[String | js.Object] = color
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsVectorPathfinderStartMarker {
override val symbol: js.UndefOr[String] = symbolOuter
override val enabled: js.UndefOr[Boolean] = enabledOuter
override val align: js.UndefOr[String] = alignOuter
override val verticalAlign: js.UndefOr[String] = verticalAlignOuter
override val inside: js.UndefOr[Boolean] = insideOuter
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val radius: js.UndefOr[Double] = radiusOuter
override val width: js.UndefOr[Double] = widthOuter
override val height: js.UndefOr[Double] = heightOuter
override val color: js.UndefOr[String | js.Object] = colorOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
})
}
}
| mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highcharts/config/PlotOptionsSeriesMarkerStatesHover.scala | 6280 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highcharts]]
*/
package com.highcharts.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-series-marker-states-hover</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsSeriesMarkerStatesHover extends com.highcharts.HighchartsGenericObject {
/**
* <p>Animation when hovering over the marker.</p>
*/
val animation: js.UndefOr[Boolean | js.Object] = js.undefined
/**
* <p>Enable or disable the point marker.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-hover-enabled/">Disabled hover state</a>
*/
val enabled: js.UndefOr[Boolean] = js.undefined
/**
* <p>The number of pixels to increase the radius of the hovered
* point.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-linewidthplus/">5 pixels greater radius on hover</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-linewidthplus/">5 pixels greater radius on hover</a>
* @since 4.0.3
*/
val radiusPlus: js.UndefOr[Double] = js.undefined
/**
* <p>The additional line width for a hovered point.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-linewidthplus/">2 pixels wider on hover</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-linewidthplus/">2 pixels wider on hover</a>
* @since 4.0.3
*/
val lineWidthPlus: js.UndefOr[Double] = js.undefined
/**
* <p>The fill color of the marker in hover state. When
* <code>undefined</code>, the series' or point's fillColor for normal
* state is used.</p>
*/
val fillColor: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>The color of the point marker's outline. When <code>undefined</code>,
* the series' or point's lineColor for normal state is used.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-hover-linecolor/">White fill color, black line color</a>
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>The width of the point marker's outline. When <code>undefined</code>,
* the series' or point's lineWidth for normal state is used.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-hover-linewidth/">3px line width</a>
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>The radius of the point marker. In hover state, it defaults
* to the normal state's radius + 2 as per the <a href="#plotOptions.series.marker.states.hover.radiusPlus">radiusPlus</a>
* option.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-hover-radius/">10px radius</a>
*/
val radius: js.UndefOr[Double] = js.undefined
}
object PlotOptionsSeriesMarkerStatesHover {
/**
* @param animation <p>Animation when hovering over the marker.</p>
* @param enabled <p>Enable or disable the point marker.</p>
* @param radiusPlus <p>The number of pixels to increase the radius of the hovered. point.</p>
* @param lineWidthPlus <p>The additional line width for a hovered point.</p>
* @param fillColor <p>The fill color of the marker in hover state. When. <code>undefined</code>, the series' or point's fillColor for normal. state is used.</p>
* @param lineColor <p>The color of the point marker's outline. When <code>undefined</code>,. the series' or point's lineColor for normal state is used.</p>
* @param lineWidth <p>The width of the point marker's outline. When <code>undefined</code>,. the series' or point's lineWidth for normal state is used.</p>
* @param radius <p>The radius of the point marker. In hover state, it defaults. to the normal state's radius + 2 as per the <a href="#plotOptions.series.marker.states.hover.radiusPlus">radiusPlus</a>. option.</p>
*/
def apply(animation: js.UndefOr[Boolean | js.Object] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, radiusPlus: js.UndefOr[Double] = js.undefined, lineWidthPlus: js.UndefOr[Double] = js.undefined, fillColor: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined): PlotOptionsSeriesMarkerStatesHover = {
val animationOuter: js.UndefOr[Boolean | js.Object] = animation
val enabledOuter: js.UndefOr[Boolean] = enabled
val radiusPlusOuter: js.UndefOr[Double] = radiusPlus
val lineWidthPlusOuter: js.UndefOr[Double] = lineWidthPlus
val fillColorOuter: js.UndefOr[String | js.Object] = fillColor
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val radiusOuter: js.UndefOr[Double] = radius
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsSeriesMarkerStatesHover {
override val animation: js.UndefOr[Boolean | js.Object] = animationOuter
override val enabled: js.UndefOr[Boolean] = enabledOuter
override val radiusPlus: js.UndefOr[Double] = radiusPlusOuter
override val lineWidthPlus: js.UndefOr[Double] = lineWidthPlusOuter
override val fillColor: js.UndefOr[String | js.Object] = fillColorOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val radius: js.UndefOr[Double] = radiusOuter
})
}
}
| mit |
expectation-php/expectation | spec/Configurable.spec.php | 1046 | <?php
/**
* This file is part of expectation package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use Assert\Assertion;
use expectation\spec\fixture\FixtureExpectation;
describe('Configurable', function() {
describe('configure', function() {
beforeEach(function() {
FixtureExpectation::configure();
});
it('should create configuration', function() {
Assertion::isInstanceOf(FixtureExpectation::configration(), 'expectation\Configuration');
});
});
describe('configureWithFile', function() {
beforeEach(function() {
$configPath = __DIR__ . '/fixture/config/composer.json';
FixtureExpectation::configureWithFile($configPath);
});
it('create configuration', function() {
Assertion::isInstanceOf(FixtureExpectation::configration(), 'expectation\Configuration');
});
});
});
| mit |
junctiontech/dbho | application/views/propertylog.php | 10790 | <!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="page-title">
<div class="title_left">
<h3>Property Log</h3>
</div>
</div>
<div class="clearfix"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#calender01').daterangepicker({
singleDatePicker: true,
calender_style: "picker_4"
}, function (start, end, label) {
console.log(start.toISOString(), end.toISOString(), label);
});
});
</script>
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Filter </h2>
<div class="clearfix"></div>
</div>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
<div class="x_content">
<form id="demo-form2" action="<?=base_url();?>AddProperty/PropertyLog/search" method="post" data-parsley-validate class="form-group form-label-left clearfix">
<div class="row">
<input type="hidden" readonly value="<?=isset($propertyID)?$propertyID:''?>" name="propertyID"/>
<div class="form-group col-xs-12 col-sm-3">
<label class="control-label" for="first-name">Property Name</label>
<input type="text" id="first-name" name="propertyName" value="<?=isset($propertyName)?$propertyName:''?>" class="form-control">
</div>
<div class="form-group col-xs-12 col-sm-3">
<label class="control-label" for="first-name">Property Key</label>
<input type="text" id="first-name" name="propertykey" value="<?=isset($propertykey)?$propertykey:''?>" class="form-control">
</div>
<div class="form-group col-xs-12 col-sm-3">
<label class="control-label" for="first-name">User Type</label>
<select class="select2_group form-control" name="usertype">
<option value="">Select User Type</option>
<option value="Agent" <?php if(!empty($usertype)){ if($usertype=="Agent"){ echo"selected";}}?>>Agent</option>
<option value="Builder" <?php if(!empty($usertype)){ if($usertype=="Builder"){ echo"selected";}}?>>Builder</option>
<option value="Individual" <?php if(!empty($usertype)){ if($usertype=="Individual"){ echo"selected";}}?>>Individual</option>
</select>
</div>
<div class="form-group col-xs-12 col-sm-3">
<label class="control-label" for="first-name">Property Name</label>
<input type="text" id="first-name" name="account" value="<?=isset($account)?$account:''?>" class="form-control">
</div>
<div class="form-group col-xs-12 col-sm-3">
<label class="control-label" for="first-name">Edit By</label>
<input type="text" id="first-name" name="activatedby" value="<?=isset($activatedby)?$activatedby:''?>" class="form-control">
</div>
<div class="form-group col-xs-12 col-sm-3">
<label for="middle-name" class="control-label">Plan</label>
<select id="first-name" name="plan" class="form-control">
<option value="">Select Plan</option>
<?php foreach($plandetails as $plandetails){?>
<option value="<?=isset($plandetails->planTypeTitle)?$plandetails->planTypeTitle:''?>" <?php if(!empty($plan)){ if($plan==$plandetails->planTypeTitle
){ echo"selected";} } ?>><?=isset($plandetails->planTypeTitle)?$plandetails->planTypeTitle:''?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-xs-12 col-sm-3">
<label for="middle-name" class="control-label">Status</label>
<select class="select2_group form-control" name="status">
<option value="">Select Status</option>
<option value="Active" <?php if(!empty($status1)){ if($status1=="Active"){ echo"selected";}}?>>Active</option>
<option value="Inactive" <?php if(!empty($status1)){ if($status1=="Inactive"){ echo"selected";}}?>>Inactive</option>
<option value="Draft" <?php if(!empty($status1)){ if($status1=="Draft"){ echo"selected";}}?>>Draft</option>
<option value="Requested" <?php if(!empty($status1)){ if($status1=="Requested"){ echo"selected";}}?>>Requested</option>
<option value="Deleted" <?php if(!empty($status1)){ if($status1=="Deleted"){ echo"selected";}}?>>Deleted</option>
<option value="Edit" <?php if(!empty($status1)){ if($status1=="Edit"){ echo"selected";}}?>>Edit</option>
<option value="Refresh" <?php if(!empty($status1)){ if($status1=="Refresh"){ echo"selected";}}?>>Refresh</option>
<option value="Admin Refresh" <?php if(!empty($status1)){ if($status1=="Admin Refresh"){ echo"selected";}}?>>Admin Refresh</option>
</select>
</div>
<div class="form-group col-xs-12 col-sm-4 martop20">
<button type="button" onclick="location.href = '<?=base_url();?>AddProperty/PropertyLog';" class="btn btn-primary">Reset</button>
<button type="submit" class="btn btn-success">Search</button>
<button type="submit" name='submit' class="btn btn-success" value="Export to CSV">Export to CSV</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Logs</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div style="overflow-x:auto; overflow-y:hidden;">
<table id="example" class="table table-striped jambo_table">
<thead>
<tr>
<th>Property</th>
<th>Edited By</th>
<th>Plan Type</th>
<th>Date & Time</th>
<th>Action Type</th>
</tr>
</thead>
<tbody>
<?php foreach($log_details as $log_detailss){
$userId=$log_detailss->userID;
if($log_detailss->userAccessType=='Admin'){
$select="adminUserEmail as useremail";
$from="rp_admin_users";$where="adminUserId=$userId";
$userdetails=$this->AddProperty_model->Getuserdetails($select,$from,$where);
}elseif($log_detailss->userAccessType=='Normal'){
$select="userEmail as useremail";
$from="rp_users";$where="userID=$userId";
$userdetails=$this->AddProperty_model->Getuserdetails($select,$from,$where);
}
?>
<tr>
<td><?=isset($log_detailss->propertyName)?$log_detailss->propertyName:''?></td>
<td><?=isset($userdetails[0]->useremail)?$userdetails[0]->useremail:''?></td>
<td><?=isset($log_detailss->planTitle)?$log_detailss->planTitle:''?></td>
<td><?=isset($log_detailss->createdOn)?$log_detailss->createdOn:''?></td>
<td> <?=isset($log_detailss->actionType)?$log_detailss->actionType:''?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('input.tableflat').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass: 'iradio_flat-green'
});
});
var asInitVals = new Array();
$(document).ready(function () {
var oTable = $('#example').dataTable({
"oLanguage": {
"sSearch": "Search all columns:"
},
"aoColumnDefs": [
{
'bSortable': false,
'aTargets': [0]
} //disables sorting for column one
],
'iDisplayLength': 12,
"sPaginationType": "full_numbers",
"dom": 'T<"clear">lfrtip',
"tableTools": {
"sSwfPath": "<?php echo base_url('assets2/js/Datatables/tools/swf/copy_csv_xls_pdf.swf'); ?>"
}
});
$("tfoot input").keyup(function () {
/* Filter on the column based on the index of this element's parent <th> */
oTable.fnFilter(this.value, $("tfoot th").index($(this).parent()));
});
$("tfoot input").each(function (i) {
asInitVals[i] = this.value;
});
$("tfoot input").focus(function () {
if (this.className == "search_init") {
this.className = "";
this.value = "";
}
});
$("tfoot input").blur(function (i) {
if (this.value == "") {
this.className = "search_init";
this.value = asInitVals[$("tfoot input").index(this)];
}
});
});
</script>
<!-- /page content -->
| mit |
nice-shot/FacebookFilter | manage.py | 258 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "facebook_filter.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| mit |
r-portas/tv-shows-notifier | src/FileDownloader/FileDownloader.java | 1686 | package FileDownloader;
import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
*
* @author roy
*/
public class FileDownloader {
/**
* Downloads a file from URL and puts it in the data folder
* @param seriesid
*/
public void downloadFile(String seriesid, String apikey, String path){
try {
URL downloadurl = new URL("http://www.thetvdb.com/api/" + apikey + "/series/" + seriesid + "/all/en.zip");
Files.copy(downloadurl.openStream(), new File(path + seriesid + ".zip").toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("DOWNLOADING " + seriesid);
// Extract the zip file and rename the 'en.xml' to the series id
ZipFile zfile = new ZipFile(path + seriesid + ".zip");
Enumeration entries = zfile.entries();
while (entries.hasMoreElements()){
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.getName().equals("en.xml")){
Files.copy(zfile.getInputStream(entry), Paths.get(path + seriesid + ".xml"), StandardCopyOption.REPLACE_EXISTING);
System.out.println("Extracting " + seriesid + ".xml");
}
}
// Delete the zip file
File file = new File(path + seriesid + ".zip");
file.delete();
System.out.println("Deleting zip file");
} catch (Exception e) {
System.out.println("Error in downloadFile: " + e.toString());
}
}
}
| mit |
carlgao/lenga | images/lenny64-peon/usr/share/python-support/python-subversion/libsvn/diff.py | 24293 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.36
#
# Don't modify this file, modify the SWIG interface instead.
# This file is compatible with both classic and new-style classes.
import _diff
import new
new_instancemethod = new.instancemethod
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'PySwigObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError,name
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
import core
def svn_diff_version(*args):
"""svn_diff_version() -> svn_version_t"""
return apply(_diff.svn_diff_version, args)
svn_diff_datasource_original = _diff.svn_diff_datasource_original
svn_diff_datasource_modified = _diff.svn_diff_datasource_modified
svn_diff_datasource_latest = _diff.svn_diff_datasource_latest
svn_diff_datasource_ancestor = _diff.svn_diff_datasource_ancestor
class svn_diff_fns_t:
"""Proxy of C svn_diff_fns_t struct"""
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, svn_diff_fns_t, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, svn_diff_fns_t, name)
__repr__ = _swig_repr
__swig_setmethods__["datasource_open"] = _diff.svn_diff_fns_t_datasource_open_set
__swig_getmethods__["datasource_open"] = _diff.svn_diff_fns_t_datasource_open_get
__swig_setmethods__["datasource_close"] = _diff.svn_diff_fns_t_datasource_close_set
__swig_getmethods__["datasource_close"] = _diff.svn_diff_fns_t_datasource_close_get
__swig_setmethods__["datasource_get_next_token"] = _diff.svn_diff_fns_t_datasource_get_next_token_set
__swig_getmethods__["datasource_get_next_token"] = _diff.svn_diff_fns_t_datasource_get_next_token_get
__swig_setmethods__["token_compare"] = _diff.svn_diff_fns_t_token_compare_set
__swig_getmethods__["token_compare"] = _diff.svn_diff_fns_t_token_compare_get
__swig_setmethods__["token_discard"] = _diff.svn_diff_fns_t_token_discard_set
__swig_getmethods__["token_discard"] = _diff.svn_diff_fns_t_token_discard_get
__swig_setmethods__["token_discard_all"] = _diff.svn_diff_fns_t_token_discard_all_set
__swig_getmethods__["token_discard_all"] = _diff.svn_diff_fns_t_token_discard_all_get
def set_parent_pool(self, parent_pool=None):
"""Create a new proxy object for svn_diff_fns_t"""
import libsvn.core, weakref
self.__dict__["_parent_pool"] = \
parent_pool or libsvn.core.application_pool;
if self.__dict__["_parent_pool"]:
self.__dict__["_is_valid"] = weakref.ref(
self.__dict__["_parent_pool"]._is_valid)
def assert_valid(self):
"""Assert that this object is using valid pool memory"""
if "_is_valid" in self.__dict__:
assert self.__dict__["_is_valid"](), "Variable has already been deleted"
def __getattr__(self, name):
"""Get an attribute from this object"""
self.assert_valid()
value = _swig_getattr(self, self.__class__, name)
members = self.__dict__.get("_members")
if members is not None:
old_value = members.get(name)
if (old_value is not None and value is not None and
value is not old_value):
try:
value.__dict__.update(old_value.__dict__)
except AttributeError:
pass
if hasattr(value, "assert_valid"):
value.assert_valid()
return value
def __setattr__(self, name, value):
"""Set an attribute on this object"""
self.assert_valid()
self.__dict__.setdefault("_members",{})[name] = value
return _swig_setattr(self, self.__class__, name, value)
def datasource_open(self, *args):
return svn_diff_fns_invoke_datasource_open(self, *args)
def datasource_close(self, *args):
return svn_diff_fns_invoke_datasource_close(self, *args)
def datasource_get_next_token(self, *args):
return svn_diff_fns_invoke_datasource_get_next_token(self, *args)
def token_compare(self, *args):
return svn_diff_fns_invoke_token_compare(self, *args)
def token_discard(self, *args):
return svn_diff_fns_invoke_token_discard(self, *args)
def token_discard_all(self, *args):
return svn_diff_fns_invoke_token_discard_all(self, *args)
def __init__(self, *args):
"""__init__(self) -> svn_diff_fns_t"""
this = apply(_diff.new_svn_diff_fns_t, args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _diff.delete_svn_diff_fns_t
__del__ = lambda self : None;
svn_diff_fns_t_swigregister = _diff.svn_diff_fns_t_swigregister
svn_diff_fns_t_swigregister(svn_diff_fns_t)
def svn_diff_diff(*args):
"""
svn_diff_diff(svn_diff_t diff, void diff_baton, svn_diff_fns_t diff_fns,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_diff, args)
def svn_diff_diff3(*args):
"""
svn_diff_diff3(svn_diff_t diff, void diff_baton, svn_diff_fns_t diff_fns,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_diff3, args)
def svn_diff_diff4(*args):
"""
svn_diff_diff4(svn_diff_t diff, void diff_baton, svn_diff_fns_t diff_fns,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_diff4, args)
def svn_diff_contains_conflicts(*args):
"""svn_diff_contains_conflicts(svn_diff_t diff) -> svn_boolean_t"""
return apply(_diff.svn_diff_contains_conflicts, args)
def svn_diff_contains_diffs(*args):
"""svn_diff_contains_diffs(svn_diff_t diff) -> svn_boolean_t"""
return apply(_diff.svn_diff_contains_diffs, args)
class svn_diff_output_fns_t:
"""Proxy of C svn_diff_output_fns_t struct"""
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, svn_diff_output_fns_t, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, svn_diff_output_fns_t, name)
__repr__ = _swig_repr
__swig_setmethods__["output_common"] = _diff.svn_diff_output_fns_t_output_common_set
__swig_getmethods__["output_common"] = _diff.svn_diff_output_fns_t_output_common_get
__swig_setmethods__["output_diff_modified"] = _diff.svn_diff_output_fns_t_output_diff_modified_set
__swig_getmethods__["output_diff_modified"] = _diff.svn_diff_output_fns_t_output_diff_modified_get
__swig_setmethods__["output_diff_latest"] = _diff.svn_diff_output_fns_t_output_diff_latest_set
__swig_getmethods__["output_diff_latest"] = _diff.svn_diff_output_fns_t_output_diff_latest_get
__swig_setmethods__["output_diff_common"] = _diff.svn_diff_output_fns_t_output_diff_common_set
__swig_getmethods__["output_diff_common"] = _diff.svn_diff_output_fns_t_output_diff_common_get
__swig_setmethods__["output_conflict"] = _diff.svn_diff_output_fns_t_output_conflict_set
__swig_getmethods__["output_conflict"] = _diff.svn_diff_output_fns_t_output_conflict_get
def set_parent_pool(self, parent_pool=None):
"""Create a new proxy object for svn_diff_output_fns_t"""
import libsvn.core, weakref
self.__dict__["_parent_pool"] = \
parent_pool or libsvn.core.application_pool;
if self.__dict__["_parent_pool"]:
self.__dict__["_is_valid"] = weakref.ref(
self.__dict__["_parent_pool"]._is_valid)
def assert_valid(self):
"""Assert that this object is using valid pool memory"""
if "_is_valid" in self.__dict__:
assert self.__dict__["_is_valid"](), "Variable has already been deleted"
def __getattr__(self, name):
"""Get an attribute from this object"""
self.assert_valid()
value = _swig_getattr(self, self.__class__, name)
members = self.__dict__.get("_members")
if members is not None:
old_value = members.get(name)
if (old_value is not None and value is not None and
value is not old_value):
try:
value.__dict__.update(old_value.__dict__)
except AttributeError:
pass
if hasattr(value, "assert_valid"):
value.assert_valid()
return value
def __setattr__(self, name, value):
"""Set an attribute on this object"""
self.assert_valid()
self.__dict__.setdefault("_members",{})[name] = value
return _swig_setattr(self, self.__class__, name, value)
def output_common(self, *args):
return svn_diff_output_fns_invoke_output_common(self, *args)
def output_diff_modified(self, *args):
return svn_diff_output_fns_invoke_output_diff_modified(self, *args)
def output_diff_latest(self, *args):
return svn_diff_output_fns_invoke_output_diff_latest(self, *args)
def output_diff_common(self, *args):
return svn_diff_output_fns_invoke_output_diff_common(self, *args)
def output_conflict(self, *args):
return svn_diff_output_fns_invoke_output_conflict(self, *args)
def __init__(self, *args):
"""__init__(self) -> svn_diff_output_fns_t"""
this = apply(_diff.new_svn_diff_output_fns_t, args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _diff.delete_svn_diff_output_fns_t
__del__ = lambda self : None;
svn_diff_output_fns_t_swigregister = _diff.svn_diff_output_fns_t_swigregister
svn_diff_output_fns_t_swigregister(svn_diff_output_fns_t)
def svn_diff_output(*args):
"""svn_diff_output(svn_diff_t diff, void output_baton, svn_diff_output_fns_t output_fns) -> svn_error_t"""
return apply(_diff.svn_diff_output, args)
svn_diff_file_ignore_space_none = _diff.svn_diff_file_ignore_space_none
svn_diff_file_ignore_space_change = _diff.svn_diff_file_ignore_space_change
svn_diff_file_ignore_space_all = _diff.svn_diff_file_ignore_space_all
class svn_diff_file_options_t:
"""Proxy of C svn_diff_file_options_t struct"""
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, svn_diff_file_options_t, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, svn_diff_file_options_t, name)
__repr__ = _swig_repr
__swig_setmethods__["ignore_space"] = _diff.svn_diff_file_options_t_ignore_space_set
__swig_getmethods__["ignore_space"] = _diff.svn_diff_file_options_t_ignore_space_get
__swig_setmethods__["ignore_eol_style"] = _diff.svn_diff_file_options_t_ignore_eol_style_set
__swig_getmethods__["ignore_eol_style"] = _diff.svn_diff_file_options_t_ignore_eol_style_get
__swig_setmethods__["show_c_function"] = _diff.svn_diff_file_options_t_show_c_function_set
__swig_getmethods__["show_c_function"] = _diff.svn_diff_file_options_t_show_c_function_get
def set_parent_pool(self, parent_pool=None):
"""Create a new proxy object for svn_diff_file_options_t"""
import libsvn.core, weakref
self.__dict__["_parent_pool"] = \
parent_pool or libsvn.core.application_pool;
if self.__dict__["_parent_pool"]:
self.__dict__["_is_valid"] = weakref.ref(
self.__dict__["_parent_pool"]._is_valid)
def assert_valid(self):
"""Assert that this object is using valid pool memory"""
if "_is_valid" in self.__dict__:
assert self.__dict__["_is_valid"](), "Variable has already been deleted"
def __getattr__(self, name):
"""Get an attribute from this object"""
self.assert_valid()
value = _swig_getattr(self, self.__class__, name)
members = self.__dict__.get("_members")
if members is not None:
old_value = members.get(name)
if (old_value is not None and value is not None and
value is not old_value):
try:
value.__dict__.update(old_value.__dict__)
except AttributeError:
pass
if hasattr(value, "assert_valid"):
value.assert_valid()
return value
def __setattr__(self, name, value):
"""Set an attribute on this object"""
self.assert_valid()
self.__dict__.setdefault("_members",{})[name] = value
return _swig_setattr(self, self.__class__, name, value)
def __init__(self, *args):
"""__init__(self) -> svn_diff_file_options_t"""
this = apply(_diff.new_svn_diff_file_options_t, args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _diff.delete_svn_diff_file_options_t
__del__ = lambda self : None;
svn_diff_file_options_t_swigregister = _diff.svn_diff_file_options_t_swigregister
svn_diff_file_options_t_swigregister(svn_diff_file_options_t)
def svn_diff_file_options_create(*args):
"""svn_diff_file_options_create(apr_pool_t pool) -> svn_diff_file_options_t"""
return apply(_diff.svn_diff_file_options_create, args)
def svn_diff_file_options_parse(*args):
"""
svn_diff_file_options_parse(svn_diff_file_options_t options, apr_array_header_t args,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_options_parse, args)
def svn_diff_file_diff_2(*args):
"""
svn_diff_file_diff_2(svn_diff_t diff, char original, char modified, svn_diff_file_options_t options,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_diff_2, args)
def svn_diff_file_diff(*args):
"""svn_diff_file_diff(svn_diff_t diff, char original, char modified, apr_pool_t pool) -> svn_error_t"""
return apply(_diff.svn_diff_file_diff, args)
def svn_diff_file_diff3_2(*args):
"""
svn_diff_file_diff3_2(svn_diff_t diff, char original, char modified, char latest,
svn_diff_file_options_t options, apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_diff3_2, args)
def svn_diff_file_diff3(*args):
"""
svn_diff_file_diff3(svn_diff_t diff, char original, char modified, char latest,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_diff3, args)
def svn_diff_file_diff4_2(*args):
"""
svn_diff_file_diff4_2(svn_diff_t diff, char original, char modified, char latest,
char ancestor, svn_diff_file_options_t options,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_diff4_2, args)
def svn_diff_file_diff4(*args):
"""
svn_diff_file_diff4(svn_diff_t diff, char original, char modified, char latest,
char ancestor, apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_diff4, args)
def svn_diff_file_output_unified3(*args):
"""
svn_diff_file_output_unified3(svn_stream_t output_stream, svn_diff_t diff, char original_path,
char modified_path, char original_header,
char modified_header, char header_encoding,
char relative_to_dir, svn_boolean_t show_c_function,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_output_unified3, args)
def svn_diff_file_output_unified2(*args):
"""
svn_diff_file_output_unified2(svn_stream_t output_stream, svn_diff_t diff, char original_path,
char modified_path, char original_header,
char modified_header, char header_encoding,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_output_unified2, args)
def svn_diff_file_output_unified(*args):
"""
svn_diff_file_output_unified(svn_stream_t output_stream, svn_diff_t diff, char original_path,
char modified_path, char original_header,
char modified_header, apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_output_unified, args)
def svn_diff_file_output_merge(*args):
"""
svn_diff_file_output_merge(svn_stream_t output_stream, svn_diff_t diff, char original_path,
char modified_path, char latest_path,
char conflict_original, char conflict_modified,
char conflict_latest, char conflict_separator,
svn_boolean_t display_original_in_conflict,
svn_boolean_t display_resolved_conflicts,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_file_output_merge, args)
def svn_diff_mem_string_diff(*args):
"""
svn_diff_mem_string_diff(svn_diff_t diff, svn_string_t original, svn_string_t modified,
svn_diff_file_options_t options,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_mem_string_diff, args)
def svn_diff_mem_string_diff3(*args):
"""
svn_diff_mem_string_diff3(svn_diff_t diff, svn_string_t original, svn_string_t modified,
svn_string_t latest, svn_diff_file_options_t options,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_mem_string_diff3, args)
def svn_diff_mem_string_diff4(*args):
"""
svn_diff_mem_string_diff4(svn_diff_t diff, svn_string_t original, svn_string_t modified,
svn_string_t latest, svn_string_t ancestor,
svn_diff_file_options_t options, apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_mem_string_diff4, args)
def svn_diff_mem_string_output_unified(*args):
"""
svn_diff_mem_string_output_unified(svn_stream_t output_stream, svn_diff_t diff, char original_header,
char modified_header, char header_encoding,
svn_string_t original, svn_string_t modified,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_mem_string_output_unified, args)
def svn_diff_mem_string_output_merge(*args):
"""
svn_diff_mem_string_output_merge(svn_stream_t output_stream, svn_diff_t diff, svn_string_t original,
svn_string_t modified, svn_string_t latest,
char conflict_original, char conflict_modified,
char conflict_latest, char conflict_separator,
svn_boolean_t display_original_in_conflict,
svn_boolean_t display_resolved_conflicts,
apr_pool_t pool) -> svn_error_t
"""
return apply(_diff.svn_diff_mem_string_output_merge, args)
class svn_diff_t:
"""Proxy of C svn_diff_t struct"""
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, svn_diff_t, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, svn_diff_t, name)
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def set_parent_pool(self, parent_pool=None):
"""Create a new proxy object for svn_diff_t"""
import libsvn.core, weakref
self.__dict__["_parent_pool"] = \
parent_pool or libsvn.core.application_pool;
if self.__dict__["_parent_pool"]:
self.__dict__["_is_valid"] = weakref.ref(
self.__dict__["_parent_pool"]._is_valid)
def assert_valid(self):
"""Assert that this object is using valid pool memory"""
if "_is_valid" in self.__dict__:
assert self.__dict__["_is_valid"](), "Variable has already been deleted"
def __getattr__(self, name):
"""Get an attribute from this object"""
self.assert_valid()
value = _swig_getattr(self, self.__class__, name)
members = self.__dict__.get("_members")
if members is not None:
old_value = members.get(name)
if (old_value is not None and value is not None and
value is not old_value):
try:
value.__dict__.update(old_value.__dict__)
except AttributeError:
pass
if hasattr(value, "assert_valid"):
value.assert_valid()
return value
def __setattr__(self, name, value):
"""Set an attribute on this object"""
self.assert_valid()
self.__dict__.setdefault("_members",{})[name] = value
return _swig_setattr(self, self.__class__, name, value)
svn_diff_t_swigregister = _diff.svn_diff_t_swigregister
svn_diff_t_swigregister(svn_diff_t)
def svn_diff_fns_invoke_datasource_open(*args):
"""svn_diff_fns_invoke_datasource_open(svn_diff_fns_t _obj, void diff_baton, svn_diff_datasource_e datasource) -> svn_error_t"""
return apply(_diff.svn_diff_fns_invoke_datasource_open, args)
def svn_diff_fns_invoke_datasource_close(*args):
"""svn_diff_fns_invoke_datasource_close(svn_diff_fns_t _obj, void diff_baton, svn_diff_datasource_e datasource) -> svn_error_t"""
return apply(_diff.svn_diff_fns_invoke_datasource_close, args)
def svn_diff_fns_invoke_datasource_get_next_token(*args):
"""
svn_diff_fns_invoke_datasource_get_next_token(svn_diff_fns_t _obj, apr_uint32_t hash, void token,
void diff_baton, svn_diff_datasource_e datasource) -> svn_error_t
"""
return apply(_diff.svn_diff_fns_invoke_datasource_get_next_token, args)
def svn_diff_fns_invoke_token_compare(*args):
"""
svn_diff_fns_invoke_token_compare(svn_diff_fns_t _obj, void diff_baton, void ltoken,
void rtoken, int compare) -> svn_error_t
"""
return apply(_diff.svn_diff_fns_invoke_token_compare, args)
def svn_diff_fns_invoke_token_discard(*args):
"""svn_diff_fns_invoke_token_discard(svn_diff_fns_t _obj, void diff_baton, void token)"""
return apply(_diff.svn_diff_fns_invoke_token_discard, args)
def svn_diff_fns_invoke_token_discard_all(*args):
"""svn_diff_fns_invoke_token_discard_all(svn_diff_fns_t _obj, void diff_baton)"""
return apply(_diff.svn_diff_fns_invoke_token_discard_all, args)
def svn_diff_output_fns_invoke_output_common(*args):
"""
svn_diff_output_fns_invoke_output_common(svn_diff_output_fns_t _obj, void output_baton, apr_off_t original_start,
apr_off_t original_length,
apr_off_t modified_start, apr_off_t modified_length,
apr_off_t latest_start, apr_off_t latest_length) -> svn_error_t
"""
return apply(_diff.svn_diff_output_fns_invoke_output_common, args)
def svn_diff_output_fns_invoke_output_diff_modified(*args):
"""
svn_diff_output_fns_invoke_output_diff_modified(svn_diff_output_fns_t _obj, void output_baton, apr_off_t original_start,
apr_off_t original_length,
apr_off_t modified_start, apr_off_t modified_length,
apr_off_t latest_start, apr_off_t latest_length) -> svn_error_t
"""
return apply(_diff.svn_diff_output_fns_invoke_output_diff_modified, args)
def svn_diff_output_fns_invoke_output_diff_latest(*args):
"""
svn_diff_output_fns_invoke_output_diff_latest(svn_diff_output_fns_t _obj, void output_baton, apr_off_t original_start,
apr_off_t original_length,
apr_off_t modified_start, apr_off_t modified_length,
apr_off_t latest_start, apr_off_t latest_length) -> svn_error_t
"""
return apply(_diff.svn_diff_output_fns_invoke_output_diff_latest, args)
def svn_diff_output_fns_invoke_output_diff_common(*args):
"""
svn_diff_output_fns_invoke_output_diff_common(svn_diff_output_fns_t _obj, void output_baton, apr_off_t original_start,
apr_off_t original_length,
apr_off_t modified_start, apr_off_t modified_length,
apr_off_t latest_start, apr_off_t latest_length) -> svn_error_t
"""
return apply(_diff.svn_diff_output_fns_invoke_output_diff_common, args)
def svn_diff_output_fns_invoke_output_conflict(*args):
"""
svn_diff_output_fns_invoke_output_conflict(svn_diff_output_fns_t _obj, void output_baton, apr_off_t original_start,
apr_off_t original_length,
apr_off_t modified_start, apr_off_t modified_length,
apr_off_t latest_start, apr_off_t latest_length,
svn_diff_t resolved_diff) -> svn_error_t
"""
return apply(_diff.svn_diff_output_fns_invoke_output_conflict, args)
| mit |
coteries/react-native-navigation | android/app/src/main/java/com/reactnativenavigation/views/SideMenu.java | 6199 | package com.reactnativenavigation.views;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.reactnativenavigation.NavigationApplication;
import com.reactnativenavigation.params.BaseScreenParams;
import com.reactnativenavigation.params.SideMenuParams;
import com.reactnativenavigation.screens.NavigationType;
import com.reactnativenavigation.screens.Screen;
import com.reactnativenavigation.utils.ViewUtils;
public class SideMenu extends DrawerLayout {
private SideMenuParams leftMenuParams;
private SideMenuParams rightMenuParams;
public enum Side {
Left(Gravity.LEFT), Right(Gravity.RIGHT);
int gravity;
Side(int gravity) {
this.gravity = gravity;
}
public static Side fromString(String side) {
if (side != null) return "left".equals(side.toLowerCase()) ? Left : Right;
return Left;
}
}
private ContentView leftSideMenuView;
private ContentView rightSideMenuView;
private RelativeLayout contentContainer;
private SimpleDrawerListener sideMenuListener;
public RelativeLayout getContentContainer() {
return contentContainer;
}
public void destroy() {
removeDrawerListener(sideMenuListener);
destroySideMenu(leftSideMenuView);
destroySideMenu(rightSideMenuView);
}
private void destroySideMenu(ContentView sideMenuView) {
if (sideMenuView == null) {
return;
}
removeDrawerListener(sideMenuListener);
sideMenuView.unmountReactView();
removeView(sideMenuView);
}
public void setVisible(boolean visible, boolean animated, Side side) {
if (!isShown() && visible) {
openDrawer(animated, side);
}
if (isShown() && !visible) {
closeDrawer(animated, side);
}
}
public void setEnabled(boolean enabled, Side side) {
if (enabled) {
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, side.gravity);
} else {
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, side.gravity);
}
}
public void openDrawer(Side side) {
openDrawer(side.gravity);
}
public void openDrawer(boolean animated, Side side) {
openDrawer(side.gravity, animated);
}
public void toggleVisible(boolean animated, Side side) {
if (isDrawerOpen(side.gravity)) {
closeDrawer(animated, side);
} else {
openDrawer(animated, side);
}
}
public void closeDrawer(boolean animated, Side side) {
closeDrawer(side.gravity, animated);
}
public SideMenu(Context context, SideMenuParams leftMenuParams, SideMenuParams rightMenuParams) {
super(context);
this.leftMenuParams = leftMenuParams;
this.rightMenuParams = rightMenuParams;
createContentContainer();
leftSideMenuView = createSideMenu(leftMenuParams);
rightSideMenuView = createSideMenu(rightMenuParams);
setStyle(leftMenuParams);
setStyle(rightMenuParams);
setScreenEventListener();
}
private void createContentContainer() {
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
contentContainer = new RelativeLayout(getContext());
contentContainer.setId(ViewUtils.generateViewId());
addView(contentContainer, lp);
}
private ContentView createSideMenu(@Nullable SideMenuParams params) {
if (params == null) {
return null;
}
ContentView sideMenuView = new ContentView(getContext(), params.screenId, params.navigationParams);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
lp.gravity = params.side.gravity;
setSideMenuWidth(sideMenuView);
addView(sideMenuView, lp);
return sideMenuView;
}
private void setSideMenuWidth(final ContentView sideMenuView) {
sideMenuView.setOnDisplayListener(new Screen.OnDisplayListener() {
@Override
public void onDisplay() {
ViewGroup.LayoutParams lp = sideMenuView.getLayoutParams();
lp.width = sideMenuView.getChildAt(0).getWidth();
sideMenuView.setLayoutParams(lp);
}
});
}
public void setScreenEventListener() {
sideMenuListener = new SimpleDrawerListener() {
@Override
public void onDrawerOpened(View drawerView) {
NavigationApplication.instance.getEventEmitter().sendWillAppearEvent(getVisibleDrawerScreenParams(), NavigationType.OpenSideMenu);
NavigationApplication.instance.getEventEmitter().sendDidAppearEvent(getVisibleDrawerScreenParams(), NavigationType.OpenSideMenu);
}
@Override
public void onDrawerClosed(View drawerView) {
NavigationApplication.instance.getEventEmitter().sendWillDisappearEvent(getVisibleDrawerScreenParams((ContentView) drawerView), NavigationType.CloseSideMenu);
NavigationApplication.instance.getEventEmitter().sendDidDisappearEvent(getVisibleDrawerScreenParams((ContentView) drawerView), NavigationType.CloseSideMenu);
}
private BaseScreenParams getVisibleDrawerScreenParams() {
return isDrawerOpen(Side.Left.gravity) ? leftMenuParams : rightMenuParams;
}
private BaseScreenParams getVisibleDrawerScreenParams(ContentView drawerView) {
return drawerView == leftSideMenuView ? leftMenuParams : rightMenuParams;
}
};
addDrawerListener(sideMenuListener);
}
private void setStyle(SideMenuParams params) {
if (params == null) {
return;
}
if (params.disableOpenGesture) {
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, params.side.gravity);
}
}
}
| mit |
jonathanpoelen/falcon | test/string/concat.cpp | 645 | #include <test/test.hpp>
#include <string>
#include <falcon/cstring.hpp>
#include <falcon/string/concat.hpp>
#include "concat.hpp"
void concat_test()
{
char s[] = "i";
falcon::cstring cs(s);
falcon::const_cstring ccs2(cs);
std::string ret = falcon::concat(
std::string(),
falcon::const_cstring("plo"),
"p",
std::string("lala"),
cs,
ccs2,
'a'
);
CHECK_EQUAL_VALUE(ret, "ploplalaiia");
ret = falcon::concat(ret, cs);
CHECK_EQUAL_VALUE(ret, "ploplalaiiai");
std::string ret2 = falcon::concat(std::move(ret), cs);
CHECK_EQUAL_VALUE(ret2, "ploplalaiiaii");
CHECK_EQUAL_VALUE(ret, "");
}
FALCON_TEST_TO_MAIN(concat_test)
| mit |
bfontaine/Teebr | teebr/admin.py | 851 | # -*- coding: UTF-8 -*-
# ref: https://github.com/mrjoes/flask-admin/blob/master/examples/peewee/app.py
from __future__ import absolute_import, unicode_literals
from flask.ext import admin
from flask.ext.admin.contrib.peewee import ModelView
from .models import Producer, Consumer, Status
# Note: no authentication is provided here
class ModelAdminView(ModelView):
# read only
can_create = False
can_edit = False
can_delete = False
page_size = 50
class ProducerAdmin(ModelAdminView):
pass
class ConsumerAdmin(ModelAdminView):
pass
class StatusAdmin(ModelAdminView):
pass
def setup_admin(app):
app_admin = admin.Admin(app, name=u"Teebr Admin")
app_admin.add_view(ProducerAdmin(Producer))
app_admin.add_view(ConsumerAdmin(Consumer))
app_admin.add_view(StatusAdmin(Status))
return app_admin
| mit |
EnSoftCorp/AuditMon | com.ensoftcorp.open.auditmon/src/com/ensoftcorp/open/auditmon/charts/ObservedTimeAllocationsChart.java | 5246 | package com.ensoftcorp.open.auditmon.charts;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import com.ensoftcorp.atlas.core.db.graph.GraphElement;
import com.ensoftcorp.open.auditmon.AuditConstants.Granularity;
import com.ensoftcorp.open.auditmon.AuditConstants.TimeUnit;
import com.ensoftcorp.open.auditmon.AuditUtils;
import com.ensoftcorp.open.auditmon.AuditUtils.AbstractObservation;
import com.ensoftcorp.open.auditmon.AuditUtils.ObservationType;
public class ObservedTimeAllocationsChart extends AuditChart {
private TimeUnit timeUnit;
private Granularity granularity;
public ObservedTimeAllocationsChart(String session, TimeUnit timeUnit, Granularity granularity) {
super(session, "");
this.timeUnit = timeUnit;
this.granularity = granularity;
this.showLegend = false;
this.showLabels = false;
if(timeUnit == TimeUnit.SECONDS){
title += " Seconds Observing ";
} else if(timeUnit == TimeUnit.MINUTES){
title += " Minutes Observing ";
} else if(timeUnit == TimeUnit.HOURS){
title += " Hours Observing ";
} else if(timeUnit == TimeUnit.DAYS){
title += " Days Observing ";
}
if(granularity == Granularity.PROGRAM_ARTIFACT){
title += "Program Artifact";
} else if(granularity == Granularity.PARENT_CLASS){
title += "Class";
} else if(granularity == Granularity.SOURCE_FILE){
title += "Source File";
} else if(granularity == Granularity.PACKAGE){
title += "Package";
} else if(granularity == Granularity.PROJECT){
title += "Project";
}
}
@Override
public JFreeChart getChart() {
TreeMap<Long, AbstractObservation> observations = AuditUtils.getSessionObservations(session);
HashMap<GraphElement,Long> timeAllocations = new HashMap<GraphElement,Long>();
// iterate over the observations in order and add up the time deltas
// according to the granularity level
AbstractObservation lastObservation = null;
for (Entry<Long, AbstractObservation> entry : observations.entrySet()) {
// start and end nodes don't count towards time spent, but they do reset the time deltas
if(entry.getValue().getType() == ObservationType.START || entry.getValue().getType() == ObservationType.STOP){
lastObservation = null;
continue;
}
if(lastObservation != null){
long timeDelta = entry.getValue().getTimestamp() - lastObservation.getTimestamp();
for(GraphElement programArtifact : lastObservation.getObservedNodes()){
GraphElement granule = AuditUtils.getNodeGranule(programArtifact, granularity);
if(granule != null){
if(timeAllocations.containsKey(granule)){
Long timeSpent = timeAllocations.remove(granule);
timeAllocations.put(granule, timeSpent + timeDelta);
} else {
timeAllocations.put(granule, timeDelta);
}
}
}
}
// update last time for next round
lastObservation = entry.getValue();
}
// convert timeAllocations to a displayable version of the data
HashMap<String,Long> timeAllocationsDisplay = new HashMap<String,Long>();
for(Entry<GraphElement,Long> timeAllocation : timeAllocations.entrySet()){
timeAllocationsDisplay.put(AuditUtils.getNodeGranuleDisplayName(timeAllocation.getKey(), granularity), timeAllocation.getValue());
}
return createPieChart(createPieDataset(timeAllocationsDisplay));
}
private DefaultPieDataset createPieDataset(final HashMap<String, Long> observedElements) {
DefaultPieDataset dataset = new DefaultPieDataset();
if(observedElements != null){
for(Entry<String,Long> entry : observedElements.entrySet()){
double formattedTime = 0.0;
if(timeUnit == TimeUnit.SECONDS){
formattedTime = entry.getValue() / 1000.0;
} else if(timeUnit == TimeUnit.MINUTES){
formattedTime = entry.getValue() / 1000.0 / 60.0;
} else if(timeUnit == TimeUnit.HOURS){
formattedTime = entry.getValue() / 1000.0 / 60.0 / 60.0;
} else if(timeUnit == TimeUnit.DAYS){
formattedTime = entry.getValue() / 1000.0 / 60.0 / 60.0 / 24.0;
}
dataset.setValue(entry.getKey() + " ", new Double(formattedTime));
}
}
return dataset;
}
private JFreeChart createPieChart(PieDataset dataset) {
JFreeChart chart = ChartFactory.createPieChart(
title, // chart title
dataset, // chart data
showLegend, // include legend
true, // tooltips
false // urls
);
PiePlot plot = (PiePlot) chart.getPlot();
plot.setSectionOutlinesVisible(false);
plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
plot.setNoDataMessage("No data available");
plot.setCircular(false);
plot.setLabelGap(0.02);
if(!showLabels){
plot.setLabelGenerator(null);
}
return chart;
}
}
| mit |
YY030913/tg | packages/tagt-importer/package.js | 1957 | Package.describe({
name: 'tagt:importer',
version: '0.0.1',
summary: 'TAGT importer library',
git: ''
});
Package.onUse(function(api) {
api.use([
'ecmascript',
'templating',
'coffeescript',
'check',
'tagt:lib'
]);
api.use('tagt:logger', 'server');
api.use('templating', 'client');
//Import Framework
api.addFiles('lib/_importer.coffee');
api.addFiles('lib/importTool.coffee');
api.addFiles('server/classes/ImporterBase.coffee', 'server');
api.addFiles('server/classes/ImporterProgress.coffee', 'server');
api.addFiles('server/classes/ImporterProgressStep.coffee', 'server');
api.addFiles('server/classes/ImporterSelection.coffee', 'server');
api.addFiles('server/classes/ImporterSelectionChannel.coffee', 'server');
api.addFiles('server/classes/ImporterSelectionUser.coffee', 'server');
//Database models
api.addFiles('server/models/Imports.coffee', 'server');
api.addFiles('server/models/RawImports.coffee', 'server');
//Server methods
api.addFiles('server/methods/getImportProgress.coffee', 'server');
api.addFiles('server/methods/getSelectionData.coffee', 'server');
api.addFiles('server/methods/prepareImport.coffee', 'server');
api.addFiles('server/methods/restartImport.coffee', 'server');
api.addFiles('server/methods/setupImporter.coffee', 'server');
api.addFiles('server/methods/startImport.coffee', 'server');
//Client
api.addFiles('client/admin/adminImport.html', 'client');
api.addFiles('client/admin/adminImport.coffee', 'client');
api.addFiles('client/admin/adminImportPrepare.html', 'client');
api.addFiles('client/admin/adminImportPrepare.coffee', 'client');
api.addFiles('client/admin/adminImportProgress.html', 'client');
api.addFiles('client/admin/adminImportProgress.coffee', 'client');
//Imports database records cleanup, mark all as not valid.
api.addFiles('server/startup/setImportsToInvalid.coffee', 'server');
api.export('Importer');
});
Npm.depends({
'adm-zip': '0.4.7'
});
| mit |
lasote/conan | conans/test/integration/symlinks_test.py | 5995 | import unittest
from conans.test.utils.tools import TestClient, TestServer
from conans.util.files import load, save
from conans.model.ref import PackageReference, ConanFileReference
import os
import platform
conanfile = """
from conans import ConanFile
from conans.util.files import save
import os
class HelloConan(ConanFile):
name = "Hello"
version = "0.1"
exports = "*"
def build(self):
save("file1.txt", "Hello1")
os.symlink("file1.txt", "file1.txt.1")
save("version1/file2.txt", "Hello2")
os.symlink("version1", "latest")
def package(self):
self.copy("*.txt*", links=True)
self.copy("*.so*", links=True)
"""
test_conanfile = """[requires]
Hello/0.1@lasote/stable
[imports]
., * -> .
"""
class SymLinksTest(unittest.TestCase):
def _check(self, client, ref, build=True):
folders = [client.paths.package(ref), client.current_folder]
if build:
folders.append(client.paths.build(ref))
for base in folders:
filepath = os.path.join(base, "file1.txt")
link = os.path.join(base, "file1.txt.1")
self.assertEqual(os.readlink(link), "file1.txt")
file1 = load(filepath)
self.assertEqual("Hello1", file1)
file1 = load(link)
self.assertEqual("Hello1", file1)
# Save any different string, random, or the base path
save(filepath, base)
self.assertEqual(load(link), base)
filepath = os.path.join(base, "version1")
link = os.path.join(base, "latest")
self.assertEqual(os.readlink(link), "version1")
filepath = os.path.join(base, "latest/file2.txt")
file1 = load(filepath)
self.assertEqual("Hello2", file1)
def basic_test(self):
if platform.system() == "Windows":
return
client = TestClient()
client.save({"conanfile.py": conanfile,
"conanfile.txt": test_conanfile})
client.run("export lasote/stable")
client.run("install --build -f=conanfile.txt")
ref = PackageReference.loads("Hello/0.1@lasote/stable:"
"5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
self._check(client, ref)
client.run("install --build -f=conanfile.txt")
self._check(client, ref)
def package_files_test(self):
if platform.system() == "Windows":
return
client = TestClient()
conanfile = """
from conans import ConanFile
class TestConan(ConanFile):
name = "Hello"
version = "0.1"
def package(self):
self.copy("*", symlinks=True)
"""
client.save({"recipe/conanfile.py": conanfile})
file1 = os.path.join(client.current_folder, "file1.txt")
file2 = os.path.join(client.current_folder, "version1/file2.txt")
file11 = os.path.join(client.current_folder, "file1.txt.1")
latest = os.path.join(client.current_folder, "latest")
save(file1, "Hello1")
os.symlink("file1.txt", file11)
save(file2, "Hello2")
os.symlink("version1", latest)
client.run("export-pkg ./recipe Hello/0.1@lasote/stable")
ref = PackageReference.loads("Hello/0.1@lasote/stable:"
"5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
self._check(client, ref, build=False)
def export_and_copy_test(self):
if platform.system() == "Windows":
return
lib_name = "libtest.so.2"
lib_contents = "TestLib"
link_name = "libtest.so"
client = TestClient()
client.save({"conanfile.py": conanfile,
"conanfile.txt": test_conanfile,
lib_name: lib_contents})
pre_export_link = os.path.join(client.current_folder, link_name)
os.symlink(lib_name, pre_export_link)
client.run("export lasote/stable")
client.run("install --build -f=conanfile.txt")
client.run("copy Hello/0.1@lasote/stable team/testing --all")
conan_ref = ConanFileReference.loads("Hello/0.1@lasote/stable")
team_ref = ConanFileReference.loads("Hello/0.1@team/testing")
package_ref = PackageReference(conan_ref,
"5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
team_package_ref = PackageReference(team_ref,
"5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
for folder in [client.paths.export(conan_ref), client.paths.source(conan_ref),
client.paths.build(package_ref), client.paths.package(package_ref),
client.paths.export(team_ref), client.paths.package(team_package_ref)]:
exported_lib = os.path.join(folder, lib_name)
exported_link = os.path.join(folder, link_name)
self.assertEqual(os.readlink(exported_link), lib_name)
self.assertEqual(load(exported_lib), load(exported_link))
self.assertTrue(os.path.islink(exported_link))
self._check(client, package_ref)
def upload_test(self):
if platform.system() == "Windows":
return
test_server = TestServer()
servers = {"default": test_server}
client = TestClient(servers=servers, users={"default": [("lasote", "mypass")]})
client.save({"conanfile.py": conanfile,
"conanfile.txt": test_conanfile})
client.run("export lasote/stable")
client.run("install --build -f=conanfile.txt")
ref = PackageReference.loads("Hello/0.1@lasote/stable:"
"5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
client.run("upload Hello/0.1@lasote/stable --all")
client.run('remove "*" -f')
client.save({"conanfile.txt": test_conanfile}, clean_first=True)
client.run("install")
self._check(client, ref, build=False)
| mit |
alltiny/alltiny-chorus | chorus/src/main/java/org/alltiny/chorus/model/SongBean.java | 879 | package org.alltiny.chorus.model;
import org.alltiny.chorus.dom.Song;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;
/**
* This class represents
*
* @author <a href="mailto:ralf.hergert.de@gmail.com">Ralf Hergert</a>
* @version 04.02.2009 21:34:42
*/
/*package-local*/class SongBean implements SongModel {
private final PropertyChangeSupport pcs;
private Song song;
public SongBean() {
pcs = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(String propName, PropertyChangeListener listener) {
pcs.addPropertyChangeListener(propName, listener);
}
public void setSong(Song newSong) {
Song old = song;
song = newSong;
pcs.firePropertyChange(SongModel.CURRENT_SONG, old, song);
}
public Song getSong() {
return song;
}
}
| mit |
Skiftet/php-speakout-api | src/Api/ResourceInterface.php | 1371 | <?php
namespace Skiftet\Speakout\Api;
use Skiftet\Speakout\Models\BaseModel;
/**
*
*/
interface ResourceInterface
{
/**
*
*/
public function subResourcePaths(): array;
/**
* @param BaseResource $resource
*/
public function registerSubResource(BaseResource $resource);
/**
* @param string $path
*/
public function subResource(string $path): BaseResource;
/**
* @param string $path
* @param int $id
*/
public function by(string $path, int $id): Query;
/**
*
*/
public function path(): string;
/**
* @param array $data
*/
public function hydrate($data): BaseModel;
/**
* @param array $data
* @param ?string $prefix
*/
public function create(array $data, ?string $prefix = null): BaseModel;
/**
* @param int $id
*/
public function find(int $id): BaseModel;
/**
*
*/
public function all(): array;
/**
* @param ?string $prefix
*/
public function query(?string $prefix = null): Query;
/**
* @param string $column
*/
public function orderBy(string $column): Query;
}
| mit |
he9qi/achievable | test/integration/navigation_test.rb | 84 | require 'test_helper'
class NavigationTest < ActiveSupport::IntegrationCase
end
| mit |
Faucetcoin/faucetcoin | src/qt/locale/bitcoin_bs.ts | 96851 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="bs" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Faucetcoin</source>
<translation>O Faucetcoinu</translation>
</message>
<message>
<location line="+39"/>
<source><b>Faucetcoin</b> version</source>
<translation><b>Faucetcoin</b> verzija</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 Faucetcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresar</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Faucetcoin 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 type="unfinished"/>
</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 Faucetcoin 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 Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</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 type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Faucetcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your faucetcoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Show information about Faucetcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</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 Faucetcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Faucetcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Faucetcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation type="unfinished"/>
</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 Faucetcoin</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 Faucetcoin 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 Faucetcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Faucetcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Faucetcoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</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 Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Faucetcoin 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 type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Faucetcoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Faucetcoin-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 type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Faucetcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Faucetcoin on system login</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Faucetcoin 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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Faucetcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Faucetcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Faucetcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Faucetcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start faucetcoin: 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 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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Faucetcoin-Qt help message to get a list with possible Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Faucetcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Faucetcoin 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 Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</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="+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 type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</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>
</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 type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</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 type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Faucetcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</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 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. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</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 type="unfinished"/>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</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 Faucetcoin 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 type="unfinished"/>
</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. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Faucetcoin 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 Faucetcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Faucetcoin 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 Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 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>
<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>Faucetcoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or faucetcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: faucetcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: faucetcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9949 or testnet: 39938)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</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: 9939 or testnet: 39939)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</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=faucetcoinrpc
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 "Faucetcoin 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. Faucetcoin 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 Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Faucetcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Faucetcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Faucetcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
</context>
</TS> | mit |
francoishill/generator-aurelia-auth-go | generators/app/templates/Interface/Authentication/AuthenticationService.go | 286 | package Authentication
import (
. "github.com/francoishill/golang-common-ddd/Interface/Security/Authentication"
"net/http"
. "<%= OWN_GO_IMPORT_PATH %>/Entities/User"
)
type AuthenticationService interface {
BaseAuthenticationService
GetUserFromRequest(r *http.Request) User
}
| mit |
SashaSansay/nanabe-wp | wp-content/themes/naba/inc/ajax.php | 254 | <?php
add_action('wp_ajax_shares', 'inc_shares');
add_action('wp_ajax_nopriv_shares', 'inc_shares');
function inc_shares(){
$id = absint($_POST['post_id']);
$sc = get_shares($id);
$sc++;
update_post_meta($id,'naba_shares-count',$sc);
}
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s01/CWE789_Uncontrolled_Mem_Alloc__malloc_char_connect_socket_83_bad.cpp | 4458 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_connect_socket_83_bad.cpp
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-83_bad.tmpl.cpp
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE789_Uncontrolled_Mem_Alloc__malloc_char_connect_socket_83.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
#define HELLO_STRING "hello"
namespace CWE789_Uncontrolled_Mem_Alloc__malloc_char_connect_socket_83
{
CWE789_Uncontrolled_Mem_Alloc__malloc_char_connect_socket_83_bad::CWE789_Uncontrolled_Mem_Alloc__malloc_char_connect_socket_83_bad(size_t dataCopy)
{
data = dataCopy;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET connectSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to unsigned int */
data = strtoul(inputBuffer, NULL, 0);
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
CWE789_Uncontrolled_Mem_Alloc__malloc_char_connect_socket_83_bad::~CWE789_Uncontrolled_Mem_Alloc__malloc_char_connect_socket_83_bad()
{
{
char * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING))
{
myString = (char *)malloc(data*sizeof(char));
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
}
#endif /* OMITBAD */
| mit |
aakselrod/lnd | routing/chainview/interface_test.go | 27479 | package chainview
import (
"bytes"
"fmt"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/integration/rpctest"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/walletdb"
_ "github.com/btcsuite/btcwallet/walletdb/bdb" // Required to register the boltdb walletdb implementation.
"github.com/lightninglabs/neutrino"
"github.com/lightningnetwork/lnd/channeldb"
)
var (
netParams = &chaincfg.RegressionNetParams
testPrivKey = []byte{
0x81, 0xb6, 0x37, 0xd8, 0xfc, 0xd2, 0xc6, 0xda,
0x63, 0x59, 0xe6, 0x96, 0x31, 0x13, 0xa1, 0x17,
0xd, 0xe7, 0x95, 0xe4, 0xb7, 0x25, 0xb8, 0x4d,
0x1e, 0xb, 0x4c, 0xfd, 0x9e, 0xc5, 0x8c, 0xe9,
}
privKey, pubKey = btcec.PrivKeyFromBytes(btcec.S256(), testPrivKey)
addrPk, _ = btcutil.NewAddressPubKey(pubKey.SerializeCompressed(),
netParams)
testAddr = addrPk.AddressPubKeyHash()
testScript, _ = txscript.PayToAddrScript(testAddr)
)
func waitForMempoolTx(r *rpctest.Harness, txid *chainhash.Hash) error {
var found bool
var tx *btcutil.Tx
var err error
timeout := time.After(10 * time.Second)
for !found {
// Do a short wait
select {
case <-timeout:
return fmt.Errorf("timeout after 10s")
default:
}
time.Sleep(100 * time.Millisecond)
// Check for the harness' knowledge of the txid
tx, err = r.Node.GetRawTransaction(txid)
if err != nil {
switch e := err.(type) {
case *btcjson.RPCError:
if e.Code == btcjson.ErrRPCNoTxInfo {
continue
}
default:
}
return err
}
if tx != nil && tx.MsgTx().TxHash() == *txid {
found = true
}
}
return nil
}
func getTestTXID(miner *rpctest.Harness) (*chainhash.Hash, error) {
script, err := txscript.PayToAddrScript(testAddr)
if err != nil {
return nil, err
}
outputs := []*wire.TxOut{
{
Value: 2e8,
PkScript: script,
},
}
return miner.SendOutputs(outputs, 2500)
}
func locateOutput(tx *wire.MsgTx, script []byte) (*wire.OutPoint, *wire.TxOut, error) {
for i, txOut := range tx.TxOut {
if bytes.Equal(txOut.PkScript, script) {
return &wire.OutPoint{
Hash: tx.TxHash(),
Index: uint32(i),
}, txOut, nil
}
}
return nil, nil, fmt.Errorf("unable to find output")
}
func craftSpendTransaction(outpoint wire.OutPoint, payScript []byte) (*wire.MsgTx, error) {
spendingTx := wire.NewMsgTx(1)
spendingTx.AddTxIn(&wire.TxIn{
PreviousOutPoint: outpoint,
})
spendingTx.AddTxOut(&wire.TxOut{
Value: 1e8,
PkScript: payScript,
})
sigScript, err := txscript.SignatureScript(spendingTx, 0, payScript,
txscript.SigHashAll, privKey, true)
if err != nil {
return nil, err
}
spendingTx.TxIn[0].SignatureScript = sigScript
return spendingTx, nil
}
func assertFilteredBlock(t *testing.T, fb *FilteredBlock, expectedHeight int32,
expectedHash *chainhash.Hash, txns []*chainhash.Hash) {
_, _, line, _ := runtime.Caller(1)
if fb.Height != uint32(expectedHeight) {
t.Fatalf("line %v: block height mismatch: expected %v, got %v",
line, expectedHeight, fb.Height)
}
if !bytes.Equal(fb.Hash[:], expectedHash[:]) {
t.Fatalf("line %v: block hash mismatch: expected %v, got %v",
line, expectedHash, fb.Hash)
}
if len(fb.Transactions) != len(txns) {
t.Fatalf("line %v: expected %v transaction in filtered block, instead "+
"have %v", line, len(txns), len(fb.Transactions))
}
expectedTxids := make(map[chainhash.Hash]struct{})
for _, txn := range txns {
expectedTxids[*txn] = struct{}{}
}
for _, tx := range fb.Transactions {
txid := tx.TxHash()
delete(expectedTxids, txid)
}
if len(expectedTxids) != 0 {
t.Fatalf("line %v: missing txids: %v", line, expectedTxids)
}
}
func testFilterBlockNotifications(node *rpctest.Harness,
chainView FilteredChainView, chainViewInit chainViewInitFunc,
t *testing.T) {
// To start the test, we'll create to fresh outputs paying to the
// private key that we generated above.
txid1, err := getTestTXID(node)
if err != nil {
t.Fatalf("unable to get test txid: %v", err)
}
err = waitForMempoolTx(node, txid1)
if err != nil {
t.Fatalf("unable to get test txid in mempool: %v", err)
}
txid2, err := getTestTXID(node)
if err != nil {
t.Fatalf("unable to get test txid: %v", err)
}
err = waitForMempoolTx(node, txid2)
if err != nil {
t.Fatalf("unable to get test txid in mempool: %v", err)
}
blockChan := chainView.FilteredBlocks()
// Next we'll mine a block confirming the output generated above.
newBlockHashes, err := node.Node.Generate(1)
if err != nil {
t.Fatalf("unable to generate block: %v", err)
}
_, currentHeight, err := node.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// We should get an update, however it shouldn't yet contain any
// filtered transaction as the filter hasn't been update.
select {
case filteredBlock := <-blockChan:
assertFilteredBlock(t, filteredBlock, currentHeight,
newBlockHashes[0], []*chainhash.Hash{})
case <-time.After(time.Second * 20):
t.Fatalf("filtered block notification didn't arrive")
}
// Now that the block has been mined, we'll fetch the two transactions
// so we can add them to the filter, and also craft transaction
// spending the outputs we created.
tx1, err := node.Node.GetRawTransaction(txid1)
if err != nil {
t.Fatalf("unable to fetch transaction: %v", err)
}
tx2, err := node.Node.GetRawTransaction(txid2)
if err != nil {
t.Fatalf("unable to fetch transaction: %v", err)
}
targetScript, err := txscript.PayToAddrScript(testAddr)
if err != nil {
t.Fatalf("unable to create target output: %v", err)
}
// Next, we'll locate the two outputs generated above that pay to use
// so we can properly add them to the filter.
outPoint1, _, err := locateOutput(tx1.MsgTx(), targetScript)
if err != nil {
t.Fatalf("unable to find output: %v", err)
}
outPoint2, _, err := locateOutput(tx2.MsgTx(), targetScript)
if err != nil {
t.Fatalf("unable to find output: %v", err)
}
_, currentHeight, err = node.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// Now we'll add both outpoints to the current filter.
filter := []channeldb.EdgePoint{
{FundingPkScript: targetScript, OutPoint: *outPoint1},
{FundingPkScript: targetScript, OutPoint: *outPoint2},
}
err = chainView.UpdateFilter(filter, uint32(currentHeight))
if err != nil {
t.Fatalf("unable to update filter: %v", err)
}
// With the filter updated, we'll now create two transaction spending
// the outputs we created.
spendingTx1, err := craftSpendTransaction(*outPoint1, targetScript)
if err != nil {
t.Fatalf("unable to create spending tx: %v", err)
}
spendingTx2, err := craftSpendTransaction(*outPoint2, targetScript)
if err != nil {
t.Fatalf("unable to create spending tx: %v", err)
}
// Now we'll broadcast the first spending transaction and also mine a
// block which should include it.
spendTxid1, err := node.Node.SendRawTransaction(spendingTx1, true)
if err != nil {
t.Fatalf("unable to broadcast transaction: %v", err)
}
err = waitForMempoolTx(node, spendTxid1)
if err != nil {
t.Fatalf("unable to get spending txid in mempool: %v", err)
}
newBlockHashes, err = node.Node.Generate(1)
if err != nil {
t.Fatalf("unable to generate block: %v", err)
}
// We should receive a notification over the channel. The notification
// should correspond to the current block height and have that single
// filtered transaction.
select {
case filteredBlock := <-blockChan:
assertFilteredBlock(t, filteredBlock, currentHeight+1,
newBlockHashes[0], []*chainhash.Hash{spendTxid1})
case <-time.After(time.Second * 20):
t.Fatalf("filtered block notification didn't arrive")
}
// Next, mine the second transaction which spends the second output.
// This should also generate a notification.
spendTxid2, err := node.Node.SendRawTransaction(spendingTx2, true)
if err != nil {
t.Fatalf("unable to broadcast transaction: %v", err)
}
err = waitForMempoolTx(node, spendTxid2)
if err != nil {
t.Fatalf("unable to get spending txid in mempool: %v", err)
}
newBlockHashes, err = node.Node.Generate(1)
if err != nil {
t.Fatalf("unable to generate block: %v", err)
}
select {
case filteredBlock := <-blockChan:
assertFilteredBlock(t, filteredBlock, currentHeight+2,
newBlockHashes[0], []*chainhash.Hash{spendTxid2})
case <-time.After(time.Second * 20):
t.Fatalf("filtered block notification didn't arrive")
}
}
func testUpdateFilterBackTrack(node *rpctest.Harness,
chainView FilteredChainView, chainViewInit chainViewInitFunc,
t *testing.T) {
// To start, we'll create a fresh output paying to the height generated
// above.
txid, err := getTestTXID(node)
if err != nil {
t.Fatalf("unable to get test txid")
}
err = waitForMempoolTx(node, txid)
if err != nil {
t.Fatalf("unable to get test txid in mempool: %v", err)
}
// Next we'll mine a block confirming the output generated above.
initBlockHashes, err := node.Node.Generate(1)
if err != nil {
t.Fatalf("unable to generate block: %v", err)
}
blockChan := chainView.FilteredBlocks()
_, currentHeight, err := node.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// Consume the notification sent which contains an empty filtered
// block.
select {
case filteredBlock := <-blockChan:
assertFilteredBlock(t, filteredBlock, currentHeight,
initBlockHashes[0], []*chainhash.Hash{})
case <-time.After(time.Second * 20):
t.Fatalf("filtered block notification didn't arrive")
}
// Next, create a transaction which spends the output created above,
// mining the spend into a block.
tx, err := node.Node.GetRawTransaction(txid)
if err != nil {
t.Fatalf("unable to fetch transaction: %v", err)
}
outPoint, _, err := locateOutput(tx.MsgTx(), testScript)
if err != nil {
t.Fatalf("unable to find output: %v", err)
}
spendingTx, err := craftSpendTransaction(*outPoint, testScript)
if err != nil {
t.Fatalf("unable to create spending tx: %v", err)
}
spendTxid, err := node.Node.SendRawTransaction(spendingTx, true)
if err != nil {
t.Fatalf("unable to broadcast transaction: %v", err)
}
err = waitForMempoolTx(node, spendTxid)
if err != nil {
t.Fatalf("unable to get spending txid in mempool: %v", err)
}
newBlockHashes, err := node.Node.Generate(1)
if err != nil {
t.Fatalf("unable to generate block: %v", err)
}
// We should have received another empty filtered block notification.
select {
case filteredBlock := <-blockChan:
assertFilteredBlock(t, filteredBlock, currentHeight+1,
newBlockHashes[0], []*chainhash.Hash{})
case <-time.After(time.Second * 20):
t.Fatalf("filtered block notification didn't arrive")
}
// After the block has been mined+notified we'll update the filter with
// a _prior_ height so a "rewind" occurs.
filter := []channeldb.EdgePoint{
{FundingPkScript: testScript, OutPoint: *outPoint},
}
err = chainView.UpdateFilter(filter, uint32(currentHeight))
if err != nil {
t.Fatalf("unable to update filter: %v", err)
}
// We should now receive a fresh filtered block notification that
// includes the transaction spend we included above.
select {
case filteredBlock := <-blockChan:
assertFilteredBlock(t, filteredBlock, currentHeight+1,
newBlockHashes[0], []*chainhash.Hash{spendTxid})
case <-time.After(time.Second * 20):
t.Fatalf("filtered block notification didn't arrive")
}
}
func testFilterSingleBlock(node *rpctest.Harness, chainView FilteredChainView,
chainViewInit chainViewInitFunc, t *testing.T) {
// In this test, we'll test the manual filtration of blocks, which can
// be used by clients to manually rescan their sub-set of the UTXO set.
// First, we'll create a block that includes two outputs that we're
// able to spend with the private key generated above.
txid1, err := getTestTXID(node)
if err != nil {
t.Fatalf("unable to get test txid")
}
err = waitForMempoolTx(node, txid1)
if err != nil {
t.Fatalf("unable to get test txid in mempool: %v", err)
}
txid2, err := getTestTXID(node)
if err != nil {
t.Fatalf("unable to get test txid")
}
err = waitForMempoolTx(node, txid2)
if err != nil {
t.Fatalf("unable to get test txid in mempool: %v", err)
}
blockChan := chainView.FilteredBlocks()
// Next we'll mine a block confirming the output generated above.
newBlockHashes, err := node.Node.Generate(1)
if err != nil {
t.Fatalf("unable to generate block: %v", err)
}
_, currentHeight, err := node.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// We should get an update, however it shouldn't yet contain any
// filtered transaction as the filter hasn't been updated.
select {
case filteredBlock := <-blockChan:
assertFilteredBlock(t, filteredBlock, currentHeight,
newBlockHashes[0], []*chainhash.Hash{})
case <-time.After(time.Second * 20):
t.Fatalf("filtered block notification didn't arrive")
}
tx1, err := node.Node.GetRawTransaction(txid1)
if err != nil {
t.Fatalf("unable to fetch transaction: %v", err)
}
tx2, err := node.Node.GetRawTransaction(txid2)
if err != nil {
t.Fatalf("unable to fetch transaction: %v", err)
}
// Next, we'll create a block that includes two transactions, each
// which spend one of the outputs created.
outPoint1, _, err := locateOutput(tx1.MsgTx(), testScript)
if err != nil {
t.Fatalf("unable to find output: %v", err)
}
outPoint2, _, err := locateOutput(tx2.MsgTx(), testScript)
if err != nil {
t.Fatalf("unable to find output: %v", err)
}
spendingTx1, err := craftSpendTransaction(*outPoint1, testScript)
if err != nil {
t.Fatalf("unable to create spending tx: %v", err)
}
spendingTx2, err := craftSpendTransaction(*outPoint2, testScript)
if err != nil {
t.Fatalf("unable to create spending tx: %v", err)
}
txns := []*btcutil.Tx{btcutil.NewTx(spendingTx1), btcutil.NewTx(spendingTx2)}
block, err := node.GenerateAndSubmitBlock(txns, 11, time.Time{})
if err != nil {
t.Fatalf("unable to generate block: %v", err)
}
select {
case filteredBlock := <-blockChan:
assertFilteredBlock(t, filteredBlock, currentHeight+1,
block.Hash(), []*chainhash.Hash{})
case <-time.After(time.Second * 20):
t.Fatalf("filtered block notification didn't arrive")
}
_, currentHeight, err = node.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// Now we'll manually trigger filtering the block generated above.
// First, we'll add the two outpoints to our filter.
filter := []channeldb.EdgePoint{
{FundingPkScript: testScript, OutPoint: *outPoint1},
{FundingPkScript: testScript, OutPoint: *outPoint2},
}
err = chainView.UpdateFilter(filter, uint32(currentHeight))
if err != nil {
t.Fatalf("unable to update filter: %v", err)
}
// We set the filter with the current height, so we shouldn't get any
// notifications.
select {
case <-blockChan:
t.Fatalf("got filter notification, but shouldn't have")
default:
}
// Now we'll manually rescan that past block. This should include two
// filtered transactions, the spending transactions we created above.
filteredBlock, err := chainView.FilterBlock(block.Hash())
if err != nil {
t.Fatalf("unable to filter block: %v", err)
}
txn1, txn2 := spendingTx1.TxHash(), spendingTx2.TxHash()
expectedTxns := []*chainhash.Hash{&txn1, &txn2}
assertFilteredBlock(t, filteredBlock, currentHeight, block.Hash(),
expectedTxns)
}
// testFilterBlockDisconnected triggers a reorg all the way back to genesis,
// and a small 5 block reorg, ensuring the chainView notifies about
// disconnected and connected blocks in the order we expect.
func testFilterBlockDisconnected(node *rpctest.Harness,
chainView FilteredChainView, chainViewInit chainViewInitFunc,
t *testing.T) {
// Create a node that has a shorter chain than the main chain, so we
// can trigger a reorg.
reorgNode, err := rpctest.New(netParams, nil, []string{"--txindex"})
if err != nil {
t.Fatalf("unable to create mining node: %v", err)
}
defer reorgNode.TearDown()
// This node's chain will be 105 blocks.
if err := reorgNode.SetUp(true, 5); err != nil {
t.Fatalf("unable to set up mining node: %v", err)
}
// Init a chain view that has this node as its block source.
cleanUpFunc, reorgView, err := chainViewInit(reorgNode.RPCConfig(),
reorgNode.P2PAddress())
if err != nil {
t.Fatalf("unable to create chain view: %v", err)
}
defer func() {
if cleanUpFunc != nil {
cleanUpFunc()
}
}()
if err = reorgView.Start(); err != nil {
t.Fatalf("unable to start btcd chain view: %v", err)
}
defer reorgView.Stop()
newBlocks := reorgView.FilteredBlocks()
disconnectedBlocks := reorgView.DisconnectedBlocks()
// If this the neutrino backend, then we'll give it some time to catch
// up, as it's a bit slower to consume new blocks compared to the RPC
// backends.
if _, ok := reorgView.(*CfFilteredChainView); ok {
time.Sleep(time.Second * 3)
}
_, oldHeight, err := reorgNode.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// Now connect the node with the short chain to the main node, and wait
// for their chains to synchronize. The short chain will be reorged all
// the way back to genesis.
if err := rpctest.ConnectNode(reorgNode, node); err != nil {
t.Fatalf("unable to connect harnesses: %v", err)
}
nodeSlice := []*rpctest.Harness{node, reorgNode}
if err := rpctest.JoinNodes(nodeSlice, rpctest.Blocks); err != nil {
t.Fatalf("unable to join node on blocks: %v", err)
}
_, newHeight, err := reorgNode.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// We should be getting oldHeight number of blocks marked as
// stale/disconnected. We expect to first get all stale blocks,
// then the new blocks. We also ensure a strict ordering.
for i := int32(0); i < oldHeight+newHeight; i++ {
select {
case block := <-newBlocks:
if i < oldHeight {
t.Fatalf("did not expect to get new block "+
"in iteration %d, old height: %v", i,
oldHeight)
}
expectedHeight := uint32(i - oldHeight + 1)
if block.Height != expectedHeight {
t.Fatalf("expected to receive connected "+
"block at height %d, instead got at %d",
expectedHeight, block.Height)
}
case block := <-disconnectedBlocks:
if i >= oldHeight {
t.Fatalf("did not expect to get stale block "+
"in iteration %d", i)
}
expectedHeight := uint32(oldHeight - i)
if block.Height != expectedHeight {
t.Fatalf("expected to receive disconnected "+
"block at height %d, instead got at %d",
expectedHeight, block.Height)
}
case <-time.After(10 * time.Second):
t.Fatalf("timeout waiting for block")
}
}
// Now we trigger a small reorg, by disconnecting the nodes, mining
// a few blocks on each, then connecting them again.
peers, err := reorgNode.Node.GetPeerInfo()
if err != nil {
t.Fatalf("unable to get peer info: %v", err)
}
numPeers := len(peers)
// Disconnect the nodes.
err = reorgNode.Node.AddNode(node.P2PAddress(), rpcclient.ANRemove)
if err != nil {
t.Fatalf("unable to disconnect mining nodes: %v", err)
}
// Wait for disconnection
for {
peers, err = reorgNode.Node.GetPeerInfo()
if err != nil {
t.Fatalf("unable to get peer info: %v", err)
}
if len(peers) < numPeers {
break
}
time.Sleep(100 * time.Millisecond)
}
// Mine 10 blocks on the main chain, 5 on the chain that will be
// reorged out,
node.Node.Generate(10)
reorgNode.Node.Generate(5)
// 5 new blocks should get notified.
for i := uint32(0); i < 5; i++ {
select {
case block := <-newBlocks:
expectedHeight := uint32(newHeight) + i + 1
if block.Height != expectedHeight {
t.Fatalf("expected to receive connected "+
"block at height %d, instead got at %d",
expectedHeight, block.Height)
}
case <-disconnectedBlocks:
t.Fatalf("did not expect to get stale block "+
"in iteration %d", i)
case <-time.After(10 * time.Second):
t.Fatalf("did not get connected block")
}
}
_, oldHeight, err = reorgNode.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// Now connect the two nodes, and wait for their chains to sync up.
if err := rpctest.ConnectNode(reorgNode, node); err != nil {
t.Fatalf("unable to connect harnesses: %v", err)
}
if err := rpctest.JoinNodes(nodeSlice, rpctest.Blocks); err != nil {
t.Fatalf("unable to join node on blocks: %v", err)
}
_, newHeight, err = reorgNode.Node.GetBestBlock()
if err != nil {
t.Fatalf("unable to get current height: %v", err)
}
// We should get 5 disconnected, 10 connected blocks.
for i := uint32(0); i < 15; i++ {
select {
case block := <-newBlocks:
if i < 5 {
t.Fatalf("did not expect to get new block "+
"in iteration %d", i)
}
// The expected height for the connected block will be
// oldHeight - 5 (the 5 disconnected blocks) + (i-5)
// (subtract 5 since the 5 first iterations consumed
// disconnected blocks) + 1
expectedHeight := uint32(oldHeight) - 9 + i
if block.Height != expectedHeight {
t.Fatalf("expected to receive connected "+
"block at height %d, instead got at %d",
expectedHeight, block.Height)
}
case block := <-disconnectedBlocks:
if i >= 5 {
t.Fatalf("did not expect to get stale block "+
"in iteration %d", i)
}
expectedHeight := uint32(oldHeight) - i
if block.Height != expectedHeight {
t.Fatalf("expected to receive disconnected "+
"block at height %d, instead got at %d",
expectedHeight, block.Height)
}
case <-time.After(10 * time.Second):
t.Fatalf("did not get disconnected block")
}
}
// Time for db access to finish between testcases.
time.Sleep(time.Millisecond * 500)
}
type chainViewInitFunc func(rpcInfo rpcclient.ConnConfig,
p2pAddr string) (func(), FilteredChainView, error)
type testCase struct {
name string
test func(*rpctest.Harness, FilteredChainView, chainViewInitFunc,
*testing.T)
}
var chainViewTests = []testCase{
{
name: "filtered block ntfns",
test: testFilterBlockNotifications,
},
{
name: "update filter back track",
test: testUpdateFilterBackTrack,
},
{
name: "filter single block",
test: testFilterSingleBlock,
},
{
name: "filter block disconnected",
test: testFilterBlockDisconnected,
},
}
var interfaceImpls = []struct {
name string
chainViewInit chainViewInitFunc
}{
{
name: "bitcoind_zmq",
chainViewInit: func(_ rpcclient.ConnConfig, p2pAddr string) (func(), FilteredChainView, error) {
// Start a bitcoind instance.
tempBitcoindDir, err := ioutil.TempDir("", "bitcoind")
if err != nil {
return nil, nil, err
}
zmqBlockHost := "ipc:///" + tempBitcoindDir + "/blocks.socket"
zmqTxHost := "ipc:///" + tempBitcoindDir + "/tx.socket"
cleanUp1 := func() {
os.RemoveAll(tempBitcoindDir)
}
rpcPort := rand.Int()%(65536-1024) + 1024
bitcoind := exec.Command(
"bitcoind",
"-datadir="+tempBitcoindDir,
"-regtest",
"-connect="+p2pAddr,
"-txindex",
"-rpcauth=weks:469e9bb14ab2360f8e226efed5ca6f"+
"d$507c670e800a95284294edb5773b05544b"+
"220110063096c221be9933c82d38e1",
fmt.Sprintf("-rpcport=%d", rpcPort),
"-disablewallet",
"-zmqpubrawblock="+zmqBlockHost,
"-zmqpubrawtx="+zmqTxHost,
)
err = bitcoind.Start()
if err != nil {
cleanUp1()
return nil, nil, err
}
cleanUp2 := func() {
bitcoind.Process.Kill()
bitcoind.Wait()
cleanUp1()
}
// Wait for the bitcoind instance to start up.
time.Sleep(time.Second)
host := fmt.Sprintf("127.0.0.1:%d", rpcPort)
chainConn, err := chain.NewBitcoindConn(
&chaincfg.RegressionNetParams, host, "weks",
"weks", zmqBlockHost, zmqTxHost,
100*time.Millisecond,
)
if err != nil {
return cleanUp2, nil, fmt.Errorf("unable to "+
"establish connection to bitcoind: %v",
err)
}
if err := chainConn.Start(); err != nil {
return cleanUp2, nil, fmt.Errorf("unable to "+
"establish connection to bitcoind: %v",
err)
}
cleanUp3 := func() {
chainConn.Stop()
cleanUp2()
}
chainView := NewBitcoindFilteredChainView(chainConn)
return cleanUp3, chainView, nil
},
},
{
name: "p2p_neutrino",
chainViewInit: func(_ rpcclient.ConnConfig, p2pAddr string) (func(), FilteredChainView, error) {
spvDir, err := ioutil.TempDir("", "neutrino")
if err != nil {
return nil, nil, err
}
dbName := filepath.Join(spvDir, "neutrino.db")
spvDatabase, err := walletdb.Create("bdb", dbName)
if err != nil {
return nil, nil, err
}
spvConfig := neutrino.Config{
DataDir: spvDir,
Database: spvDatabase,
ChainParams: *netParams,
ConnectPeers: []string{p2pAddr},
}
spvNode, err := neutrino.NewChainService(spvConfig)
if err != nil {
return nil, nil, err
}
spvNode.Start()
// Wait until the node has fully synced up to the local
// btcd node.
for !spvNode.IsCurrent() {
time.Sleep(time.Millisecond * 100)
}
cleanUp := func() {
spvDatabase.Close()
spvNode.Stop()
os.RemoveAll(spvDir)
}
chainView, err := NewCfFilteredChainView(spvNode)
if err != nil {
return nil, nil, err
}
return cleanUp, chainView, nil
},
},
{
name: "btcd_websockets",
chainViewInit: func(config rpcclient.ConnConfig, _ string) (func(), FilteredChainView, error) {
chainView, err := NewBtcdFilteredChainView(config)
if err != nil {
return nil, nil, err
}
return nil, chainView, err
},
},
}
func TestFilteredChainView(t *testing.T) {
// Initialize the harness around a btcd node which will serve as our
// dedicated miner to generate blocks, cause re-orgs, etc. We'll set up
// this node with a chain length of 125, so we have plenty of BTC to
// play around with.
miner, err := rpctest.New(netParams, nil, []string{"--txindex"})
if err != nil {
t.Fatalf("unable to create mining node: %v", err)
}
defer miner.TearDown()
if err := miner.SetUp(true, 25); err != nil {
t.Fatalf("unable to set up mining node: %v", err)
}
rpcConfig := miner.RPCConfig()
p2pAddr := miner.P2PAddress()
for _, chainViewImpl := range interfaceImpls {
t.Logf("Testing '%v' implementation of FilteredChainView",
chainViewImpl.name)
cleanUpFunc, chainView, err := chainViewImpl.chainViewInit(rpcConfig, p2pAddr)
if err != nil {
t.Fatalf("unable to make chain view: %v", err)
}
if err := chainView.Start(); err != nil {
t.Fatalf("unable to start chain view: %v", err)
}
for _, chainViewTest := range chainViewTests {
testName := fmt.Sprintf("%v: %v", chainViewImpl.name,
chainViewTest.name)
success := t.Run(testName, func(t *testing.T) {
chainViewTest.test(miner, chainView,
chainViewImpl.chainViewInit, t)
})
if !success {
break
}
}
if err := chainView.Stop(); err != nil {
t.Fatalf("unable to stop chain view: %v", err)
}
if cleanUpFunc != nil {
cleanUpFunc()
}
}
}
| mit |
scratch2mcpi/scratch2mcpi | bullseye/scratch2mcpi.py | 11968 | #!/usr/bin/env python2
import sys
import os
import gettext
import scratch
import mcpi.minecraft as minecraft
import mcturtle.minecraftturtle as turtle
import mcstuff.minecraftstuff as stuff
import mcpi.block as block
import time
VERSION = "2.1.0"
localedir = os.path.join(os.path.dirname(__file__), 'locale')
_ = gettext.translation(domain = 'scratch2mcpi', localedir = localedir, fallback = True).ugettext
def is_number(value):
if (isinstance(value, (int, float))):
return True
else:
return False
def connect():
try:
return scratch.Scratch()
except scratch.ScratchError:
print _("Error: Unable to connect to Scratch. Scratch may be not running or the remote sensor connections may be not enabled.")
return None
def _listen(s):
while True:
try:
yield s.receive()
except scratch.ScratchError:
print _("Error: Disconnected from Scratch.")
raise StopIteration
def listen(s, mc):
mcpiX = 0
mcpiY = 0
mcpiZ = 0
mcpiX0 = 0
mcpiY0 = 0
mcpiZ0 = 0
mcpiX1 = 0
mcpiY1 = 0
mcpiZ1 = 0
blockTypeId = 1
blockData = 0
# Minecraft Graphics Turtle
speed = 10
steps = 0
degrees = 0
mc = minecraft.Minecraft.create()
pos = mc.player.getPos()
steve = turtle.MinecraftTurtle(mc, pos)
# Minecraft Stuff
radius = 0
shapePoints = []
fill = True
mcDrawing = stuff.MinecraftDrawing(mc)
for msg in _listen(s):
if (msg):
print "Received: %s" % str(msg)
if msg[0] == 'broadcast':
if not mc:
mc = minecraft.Minecraft.create()
if msg[1] == 'hello_minecraft':
mc.postToChat("hello minecraft")
elif msg[1] == 'setPos':
if (is_number(mcpiX) and is_number(mcpiY) and is_number(mcpiZ)):
mc.player.setPos(mcpiX, mcpiY, mcpiZ)
print "setPos: %.1f %.1f %.1f" % (mcpiX, mcpiY, mcpiZ)
elif msg[1] == 'setBlock':
if (is_number(mcpiX) and is_number(mcpiY) and is_number(mcpiZ) and is_number(blockTypeId) and is_number(blockData)):
mc.setBlock(mcpiX, mcpiY, mcpiZ, blockTypeId, blockData)
print "setBlock: %d %d %d %d %d" % (mcpiX, mcpiY, mcpiZ, blockTypeId, blockData)
# Minecraft Graphics Turtle(Start)
elif msg[1] == 'turtle:setPos':
if is_number(mcpiX) and is_number(mcpiY) and is_number(mcpiZ):
steve.setposition(mcpiX, mcpiY, mcpiZ)
print "turtle:setPos: %.1f %.1f %.1f" % (mcpiX, mcpiY, mcpiZ)
elif msg[1] == 'turtle:forward':
if is_number(steps):
steve.forward(steps)
print "steve.forward: (%d)" % (steps)
elif msg[1] == 'turtle:backward':
if is_number(steps):
steve.backward(steps)
print "steve.backward: (%d)" % (steps)
elif msg[1] == 'turtle:right':
if is_number(degrees):
steve.right(degrees)
print "steve.right: (%d)" % (degrees)
elif msg[1] == 'turtle:left':
if is_number(degrees):
steve.left(degrees)
print "steve.left: (%d)" % (degrees)
elif msg[1] == 'turtle:up':
if is_number(degrees):
steve.up(degrees)
print "steve.up: (%d)" % (degrees)
elif msg[1] == 'turtle:down':
if is_number(degrees):
steve.down(degrees)
print "steve.down: (%d)" % (degrees)
elif msg[1] == 'turtle:penup':
steve.penup()
print "steve.penup"
elif msg[1] == 'turtle:pendown':
steve.pendown()
print "steve.pendown"
elif msg[1] == 'turtle:setheading':
if is_number(degrees):
steve.setheading(degrees)
print "steve.setheading: (%d)" % (degrees)
elif msg[1] == 'turtle:setverticalheading':
if is_number(degrees):
steve.setverticalheading(degrees)
print "steve.setverticalheading: (%d)" % (degrees)
# Minecraft Graphics Turtle(End)
# Minecraft Stuff(Start)
elif msg[1] == 'stuff:drawLine':
mcDrawing.drawLine(int(mcpiX1), int(mcpiY1), int(mcpiZ1), int(mcpiX), int(mcpiY), int(mcpiZ), blockTypeId, blockData)
print "mcDrawing.drawLine: (%d, %d, %d, %d, %d, %d, %d, %d)" % (mcpiX1, mcpiY1, mcpiZ1, mcpiX, mcpiY, mcpiZ, blockTypeId, blockData)
elif msg[1] == 'stuff:drawSphere':
mcDrawing.drawSphere(mcpiX, mcpiY, mcpiZ, radius, blockTypeId, blockData)
print "mcDrawing.drawSphere: (%d, %d, %d, %d, %d, %d)" % (mcpiX, mcpiY, mcpiZ, radius, blockTypeId, blockData)
elif msg[1] == 'stuff:drawCircle':
mcDrawing.drawCircle(mcpiX, mcpiY, mcpiZ, radius, blockTypeId, blockData)
print "mcDrawing.drawCircle: (%d, %d, %d, %d, %d, %d)" % (mcpiX, mcpiY, mcpiZ, radius, blockTypeId, blockData)
elif msg[1] == 'stuff:resetShapePoints':
shapePoints = []
mcDrawing = stuff.MinecraftDrawing(mc)
elif msg[1] == 'stuff:setShapePoints':
shapePoints.append(minecraft.Vec3(int(mcpiX), int(mcpiY), int(mcpiZ)))
print "append.shapePoints:"
print ' '.join(str(p) for p in shapePoints)
elif msg[1] == 'stuff:drawFace':
if (fill == 'True'):
fillFlag = True
elif (fill == 'False'):
fillFlag = False
mcDrawing.drawFace(shapePoints, fillFlag, blockTypeId)
print "mcDrawing.drawFace:"
print ' '.join(str(p) for p in shapePoints)
print(fill)
print(blockTypeId)
# Minecraft Stuff(End)
elif msg[1] == 'setBlocks':
if (is_number(mcpiX0) and is_number(mcpiY0) and is_number(mcpiZ0) and is_number(mcpiX1) and is_number(mcpiY1) and is_number(mcpiZ1) and is_number(blockTypeId) and is_number(blockData)):
mc.setBlocks(mcpiX0, mcpiY0, mcpiZ0, mcpiX1, mcpiY1, mcpiZ1, blockTypeId, blockData)
print "setBlocks(%d, %d, %d, %d, %d, %d, %d, %d" % (mcpiX0, mcpiY0, mcpiZ0, mcpiX1, mcpiY1, mcpiZ1, blockTypeId, blockData)
elif msg[1] == 'getPos':
playerPos = mc.player.getPos()
pos = playerPos
s.sensorupdate({
'playerX': playerPos.x,
'playerY': playerPos.y,
'playerZ': playerPos.z
})
elif msg[1] == 'getHeight':
posY = mc.getHeight(mcpiX, mcpiZ)
s.sensorupdate({'posY': posY})
mc.postToChat("posY: %d" % posY)
elif msg[1] == 'getBlock':
blockFound = mc.getBlockWithData(mcpiX, mcpiY, mcpiZ)
s.sensorupdate({
'blockTypeId': blockFound.id,
'blockData': blockFound.data
})
elif msg[1] == 'pollBlockHits':
blockEvents = mc.events.pollBlockHits()
print blockEvents
if blockEvents:
blockEvent = blockEvents[-1]
s.sensorupdate({
'blockEventX': blockEvent.pos.x,
'blockEventY': blockEvent.pos.y,
'blockEventZ': blockEvent.pos.z,
'blockEventFace': blockEvent.face,
'blockEventEntityId': blockEvent.entityId
})
else:
s.sensorupdate({
'blockEventX': '',
'blockEventY': '',
'blockEventZ': '',
'blockEventFace': '',
'blockEventEntityId': ''
})
elif msg[1] == 'reset':
mc.postToChat('reset the world')
mc.setBlocks(-100, 0, -100, 100, 63, 100, 0, 0)
mc.setBlocks(-100, -63, -100, 100, -2, 100, 1, 0)
mc.setBlocks(-100, -1, -100, 100, -1, 100, 2, 0)
mc.player.setPos(0, 0, 0)
elif msg[1] == 'echo' or msg[1].startswith('echo '):
words = msg[1].split()
mc.postToChat(" ".join(words[1:]))
elif msg[0] == 'sensor-update':
mcpiX = msg[1].get('mcpiX', mcpiX)
mcpiY = msg[1].get('mcpiY', mcpiY)
mcpiZ = msg[1].get('mcpiZ', mcpiZ)
mcpiX0 = msg[1].get('mcpiX0', mcpiX0)
mcpiY0 = msg[1].get('mcpiY0', mcpiY0)
mcpiZ0 = msg[1].get('mcpiZ0', mcpiZ0)
mcpiX1 = msg[1].get('mcpiX1', mcpiX1)
mcpiY1 = msg[1].get('mcpiY1', mcpiY1)
mcpiZ1 = msg[1].get('mcpiZ1', mcpiZ1)
blockTypeId = msg[1].get('blockTypeId', blockTypeId)
blockData = msg[1].get('blockData', blockData)
# Minecraft Graphics Turtle
speed = msg[1].get('speed', speed)
steps = msg[1].get('steps', steps)
degrees = msg[1].get('degrees', degrees)
steve.speed(speed)
steve.penblock(blockTypeId, blockData)
# Minecraft Stuff
radius = msg[1].get('radius', radius)
fill = msg[1].get('fill', fill)
def main():
print "================="
print "Sratch2MCPI %s" % VERSION
print "================="
print ""
while True:
s = connect()
mc = minecraft.Minecraft.create()
if (s):
mc.postToChat("Scratch2MCPI connected to Minecraft Pi.")
print _("Connected to Scratch")
s.broadcast("hello_minecraft")
s.broadcast("setPos")
s.broadcast("setBlock")
# s.broadcast("setBlocks")
s.broadcast("getPos")
s.broadcast("getHeight")
s.broadcast("getBlock")
s.broadcast("pollBlockHits")
s.broadcast("reset")
s.broadcast("turtle:forward")
s.broadcast("turtle:backward")
s.broadcast("turtle:right")
s.broadcast("turtle:left")
s.broadcast("turtle:up")
s.broadcast("turtle:down")
s.broadcast("turtle:setPos")
s.broadcast("turtle:penup")
s.broadcast("turtle:pendown")
s.broadcast("turtle:setheading")
s.broadcast("turtle:setverticalheading")
s.broadcast("stuff:drawSphere")
s.broadcast("stuff:drawCircle")
s.broadcast("stuff:drawLine")
s.broadcast("stuff:drawFace")
s.broadcast("stuff:resetShapePoints")
s.broadcast("stuff:setShapePoints")
s.sensorupdate({
'blockTypeId': 0,
'blockData': 0
})
listen(s, mc)
time.sleep(5)
main()
| mit |
anselmobd/fo2 | src/manutencao/migrations/0002_fo2_tipo_maquina_loaddata.py | 709 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-11-23 18:57
from __future__ import unicode_literals
from django.db import migrations, models
def load_tipo_maquina_from_fixture(apps, schema_editor):
from django.core.management import call_command
call_command("loaddata", "0002_fo2_tipo_maquina_loaddata")
def delete_tipo_maquina(apps, schema_editor):
TipoMaquina = apps.get_model("manutencao", "TipoMaquina")
TipoMaquina.objects.all().delete()
class Migration(migrations.Migration):
dependencies = [
('manutencao', '0001_initial'),
]
operations = [
migrations.RunPython(
load_tipo_maquina_from_fixture, delete_tipo_maquina),
]
| mit |
MoeOrganization/moe | src/main/scala/org/moe/runtime/builtins/ClassClass.scala | 1488 | package org.moe.runtime.builtins
import org.moe.runtime._
/**
* setup class Class
*/
object ClassClass {
def apply(r: MoeRuntime): Unit = {
val env = new MoeEnvironment(Some(r.getCorePackage.getEnv))
val classClass = r.getCoreClassFor("Class").getOrElse(
throw new MoeErrors.MoeStartupError("Could not find class Class")
)
import r.NativeObjects._
def self(e: MoeEnvironment): MoeClass = e.getCurrentInvocantAs[MoeClass].getOrElse(
throw new MoeErrors.InvocantNotFound("Could not find invocant")
)
// MRO: Class, Object
classClass.addMethod(
new MoeMethod(
"name",
new MoeSignature(),
env,
(e) => getStr(self(e).getName)
)
)
classClass.addMethod(
new MoeMethod(
"version",
new MoeSignature(),
env,
(e) => self(e).getVersion match {
case Some(v) => getStr(v)
case None => getUndef
}
)
)
classClass.addMethod(
new MoeMethod(
"authority",
new MoeSignature(),
env,
(e) => self(e).getAuthority match {
case Some(a) => getStr(a)
case None => getUndef
}
)
)
classClass.addMethod(
new MoeMethod(
"superclass",
new MoeSignature(),
env,
(e) => self(e).getSuperclass.getOrElse(getUndef)
)
)
/**
* List of Methods to support:
*
*
*/
}
}
| mit |
Condors/TunisiaMall | src/Condors/TnMallBundle/Entity/Panier.php | 1112 | <?php
namespace Condors\TnMallBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Panier
*
* @ORM\Table(name="panier", indexes={@ORM\Index(name="id_client", columns={"id_client"})})
* @ORM\Entity
*/
class Panier
{
/**
* @var integer
*
* @ORM\Column(name="id_panier", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idPanier;
/**
* @var integer
*
* @ORM\Column(name="id_client", type="integer", nullable=false)
*/
private $idClient;
/**
* @return int
*/
public function getIdPanier()
{
return $this->idPanier;
}
/**
* @param int $idPanier
*/
public function setIdPanier($idPanier)
{
$this->idPanier = $idPanier;
}
/**
* @return int
*/
public function getIdClient()
{
return $this->idClient;
}
/**
* @param int $idClient
*/
public function setIdClient($idClient)
{
$this->idClient = $idClient;
}
}
| mit |
rkadyb/slack-ruby-client | spec/slack/real_time/event_handlers/bot_spec.rb | 1280 | require 'spec_helper'
RSpec.describe Slack::RealTime::Client, vcr: { cassette_name: 'web/rtm_start' } do
include_context 'connected client'
context 'bot' do
it 'sets bot data on rtm.start' do
expect(client.bots.count).to eq 16
end
it 'bot_added' do
expect do
event = Slack::RealTime::Event.new(
'type' => 'bot_added',
'bot' => {
'id' => 'B024BE7LH',
'name' => 'hugbot',
'icons' => {
'image_48' => 'https:\/\/slack.com\/path\/to\/hugbot_48.png'
}
})
client.send(:dispatch, event)
end.to change(client.bots, :count).by(1)
bot = client.bots['B024BE7LH']
expect(bot['id']).to eq 'B024BE7LH'
expect(bot['name']).to eq 'hugbot'
expect(bot['icons']['image_48']).to eq 'https:\/\/slack.com\/path\/to\/hugbot_48.png'
end
it 'bot_changed' do
expect do
event = Slack::RealTime::Event.new(
'type' => 'bot_changed',
'bot' => {
'id' => 'B0751JU2H',
'name' => 'hugbot'
})
client.send(:dispatch, event)
end.to_not change(client.bots, :count)
bot = client.bots['B0751JU2H']
expect(bot['name']).to eq 'hugbot'
end
end
end
| mit |
colitman/ShoppingList-webapp | src/main/java/ua/romenskyi/webapp/shopping/domain/UniqueNamedEntityInterface.java | 303 | /**
* This software is licensed under the terms of the MIT license.
* Copyright (C) 2016 Dmytro Romenskyi
*/
package ua.romenskyi.webapp.shopping.domain;
/**
* @author dmytro.romenskyi - Jun 28, 2016
*
*/
public interface UniqueNamedEntityInterface extends NamedEntityInterface {
}
| mit |
torbjornvatn/powerline-shell | segments/kube.py | 408 | from subprocess import Popen, PIPE
from shlex import split
def add_kube_segment(powerline):
try:
cmd = "kubectl config view -o=jsonpath={.current-context} | sed -e 's/gke_uc-prox-//g;s/_europe-west1-b_/-/g' | tr -d '\n' "
output = Popen("%s " % cmd, stdout=PIPE, shell=True).communicate()[0]
except OSError:
return
powerline.append(output, Color.JOBS_FG, Color.JOBS_BG)
| mit |
lionfire/Core | src/LionFire.Info/Info/HierarchicalTags/HierarchicalTagNode.cs | 2783 | using LionFire.FlexObjects;
using LionFire.Referencing;
using System.Collections.Concurrent;
namespace LionFire.Info
{
//public interface INamedNode
//{
// INamedNode? Parent { get; set; }
//}
public class HierarchicalNamedNodeBase<TConcrete>
where TConcrete : HierarchicalNamedNodeBase<TConcrete>
{
public TConcrete? Parent { get; protected set; } = default;
public ConcurrentDictionary<string, TConcrete>? Children { get; protected set; } = default;
public int Depth
{
get
{
if (depth == int.MinValue)
{
depth = Parent == null ? 0 : Parent.Depth + 1;
}
return depth;
}
}
private int depth = int.MinValue;
}
public class HierarchicalNamedNode<TConcrete, TValue> : HierarchicalNamedNodeBase<TConcrete>
where TConcrete : HierarchicalNamedNode<TConcrete, TValue>
{
public string? Key
{
get
{
if (key == null)
{
if (Parent == null)
{
key = Name;
}
else
{
key = LionPath.Combine(Parent.Key, Name);
}
}
return key;
}
}
private string? key = null;
public string? Name { get; set; }
public HierarchicalNamedNode()
{
Name = null;
Value = default;
}
public HierarchicalNamedNode(TConcrete? parent, string name)
{
Parent = parent;
Name = name;
if (typeof(TValue) == typeof(string))
{
Value = (TValue)(object)name;
}
Value = default;
}
public TValue? Value { get; set; }
public void Add(TConcrete node)
{
node.Parent = (TConcrete)this;
if (Children == null) { Children = new(); }
if (!Children.TryAdd(node.Name ?? throw new ArgumentNullException(nameof(node.Name)), node))
{
throw new AlreadySetException();
}
}
public void Remove(TConcrete node)
{
throw new NotImplementedException();
}
public override string ToString()
{
return Name ?? "(null)";
}
}
public class TagNode : HierarchicalNamedNode<TagNode, string>, IFlex
{
public TagNode() { }
public TagNode(TagNode? parent, string name) : base(parent, name) { }
object? IFlex.FlexData { get; set; } = null;
}
} | mit |
valorin/pinpusher | tests/Pin/Layout/WeatherTest.php | 681 | <?php
namespace tests\Pin\Layout;
use Valorin\PinPusher\Pin\Icon;
use Valorin\PinPusher\Pin\Layout\Weather;
class WeatherTest extends \PHPUnit_Framework_TestCase
{
public function test_defaults()
{
$generated = (new Weather('weather title', Icon::SUNRISE, Icon::SUNSET, 'location name'))
->generate();
$this->assertEquals('weatherPin', $generated['type']);
$this->assertEquals('weather title', $generated['title']);
$this->assertEquals(Icon::SUNRISE, $generated['tinyIcon']);
$this->assertEquals(Icon::SUNSET, $generated['largeIcon']);
$this->assertEquals('location name', $generated['locationName']);
}
}
| mit |
ur92/ng-bitwise-enum | bitwiseEnum.module.js | 110 | (function () {
'use strict';
angular.module('optiApp.services.bitwise-enum', [
]);
})(); | mit |
CodeLiftSleep/Electron-GoalLineStand-Football | app/main.js | 526 | const electron = require('electron');
//const {app, BrowserWindow} = electron;
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var mainWindow = null;
app.on('window-all-closed', function() {
if (process.platform != 'darwin')
app.quit();
});
app.on('ready', function() {
mainWindow = new BrowserWindow({width: 800, height: 600});
mainWindow.maximize();
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.on('closed', function() {
mainWindow = null;
});
}); | mit |
DJCordhose/javascript-einfuehrung | coding-sessions/wjax2015/src/util.js | 266 | export function displayInPage(text) {
if (typeof text !== 'string') {
text = JSON.stringify(text);
}
if (typeof document !== 'undefined') {
return document.body.innerHTML += `${text}<br>`;
} else {
console.log(text);
}
}
| mit |
freeman-lab/station | station/__init__.py | 84 | from .station import (start, stop, engine, mode, credentials)
__version__ = '2.0.0' | mit |
orgasmicnightmare/cakephp-seo | src/Model/Behavior/SeoBehavior.php | 12246 | <?php
namespace Seo\Model\Behavior;
use ArrayObject;
use Cake\Event\Event;
use Cake\I18n\I18n;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Routing\Router;
use Cake\Utility\Inflector;
/**
* Seo behavior
*/
class SeoBehavior extends Behavior
{
use \Seo\Model\Behavior\SeoTrait;
/**
* Default configuration.
*
* @var array
* @todo Add the choice to merge or overwrite configuration.
*/
protected $_defaultConfig = [
'urls' => [
[
'url' => [
'prefix' => false,
'action' => 'view',
'_' => [
'slug' => 'slug'
]
],
'locale' => null,
'title' => 'Seo default title',
'canonical' => true,
'meta_tags' => [
// 'og:type' => [
// 'content' => 'website',
// 'is_property' => true
// ],
// 'og:description' => [
// 'content' => '{{content}}',
// 'is_property' => true
// ],
// 'og:locale' => [
// 'callback' => 'getLocale',
// 'is_property' => true
// ],
// 'twitter:description' => [
// 'content' => '{{content}}',
// 'is_property' => true
// ],
]
]
]
];
/**
* Entities Seo.SeoUris stored in the beforeDelete Event
* Needed because sometimes we have a url callback defined to find
* some routes.
* So we have to do some logic before the entity (for which the behavior
* is attached) is deleted
*
* @var array
*/
protected $_seoUriEntities = [];
/**
* Instance of Seo.SeoUrisTable
*
* @var Seo\Model\Table\SeoUrisTable
*/
protected $_SeoUris = null;
/**
* Initialize method
*
* @param array $config Configuration options
* @return void
*/
public function initialize(array $config)
{
$this->_SeoUris = TableRegistry::get('Seo.SeoUris');
// Add Relations.
$this->_table->hasMany('SeoUris', [
'foreignKey' => 'foreign_key',
'conditions' => [
'SeoUris.model' => $this->_table->alias(),
//'SeoUris.locale' => I18n::locale()
],
'dependent' => true
]);
}
/**
* After Save Callback
*
* @param Cake/Event/Event $event The afterSave event that was fired.
* @param Cake/ORM/Entity $entity The entity
* @param ArrayObject $options Options
* @return void
*/
public function afterSave(Event $event, Entity $entity, ArrayObject $options)
{
if ($entity->isNew()) {
$this->saveDefaultUri($entity);
} else {
// Change route.
if ($entity->dirty()) {
$SeoUris = TableRegistry::get('Seo.SeoUris');
$SeoCanonicals = TableRegistry::get('Seo.SeoCanonicals');
$urlsConfig = $this->config('urls');
foreach ($urlsConfig as $key => $url) {
$uri = $this->_getUri($entity, $url);
$seoUri = $SeoUris->find()->contain(['SeoCanonicals'])->where([
'model' => $this->_table->alias(),
'foreign_key' => $entity->id,
'locale' => isset($url['locale']) ? $url['locale'] : null
])->first();
if ($seoUri) {
$seoUri = $SeoUris->patchEntity($seoUri, ['uri' => $uri], ['associated' => ['SeoCanonicals']]);
$SeoUris->save($seoUri);
$seoUriCanonical = Router::fullBaseUrl() . $uri;
$seoUri->seo_canonical->set('canonical', $seoUriCanonical);
$SeoCanonicals->save($seoUri->seo_canonical);
}
}
}
}
\Cake\Cache\Cache::clear(false, 'seo');
}
/**
* Before Delete Callback
*
* @param Cake/Event/Event $event The beforeDelete event that was fired.
* @param Cake/ORM/Entity $entity The entity
* @param ArrayObject $options Options
* @return void
*/
public function beforeDelete(Event $event, Entity $entity, ArrayObject $options)
{
// $this->beforeDeleteUri($entity);
return;
}
/**
* After Delete Callback
*
* @param Cake/Event/Event $event The afterDelete event that was fired.
* @param Cake/ORM/Entity $entity The entity
* @param ArrayObject $options Options
* @return void
*/
public function afterDelete(Event $event, Entity $entity, ArrayObject $options)
{
// $seoUri = "Seo\\Model\\Entity\\SeoUri";
// foreach ($this->_seoUriEntities as $seoUriEntity) {
// if ($seoUriEntity instanceof $seoUri) {
// $this->_SeoUris->delete($seoUriEntity);
// }
// }
\Cake\Cache\Cache::clear(false, 'seo');
//return;
}
/**
* Delete Uri
*
* Delete Seo Entries for an Entity
* @param Cake\ORM\Entity $entity The entity
* @return void
*/
public function beforeDeleteUri(Entity $entity)
{
foreach ($this->config('urls') as $key => $url) {
$uri = $this->_getUri($entity, $url);
$this->_seoUriEntities[] = $this->_SeoUris->getByUri($uri);
}
}
/**
* Save Default Uri
*
* Save defaults uri, title, meta tags defined
* for the model based on the configuration array.
*
* @param Cake\ORM\Entity $entity The Entity
* @param mixed $urlsConfig array of urls configuration to generate tags. If false,
* it will use the behavior configuration $this->config('urls') RECOMMENDED.
* @return mixed Entity SeoUri or False if the uri already exists.
*/
public function saveDefaultUri(Entity $entity, $urlsConfig = false, $checkApproved = true)
{
if (!$urlsConfig) {
$urlsConfig = $this->config('urls');
}
$uris = [];
foreach ($urlsConfig as $key => $url) {
$uri = $this->_getUri($entity, $url);
$SeoUris = TableRegistry::get('Seo.SeoUris');
if ($checkApproved === true && $SeoUris->findByUri($uri)->find('approved')->first()) {
return false;
}
$uriEntity = [
'uri' => $uri,
'model' => $this->_table->alias(),
'foreign_key' => $entity->id,
'locale' => isset($url['locale']) ? $url['locale'] : null,
'is_approved' => true,
'seo_title' => [
'title' => $this->setSeoTitle($entity, $uri, $url)
],
'seo_canonical' => $this->setCanonical($entity, $uri, $url),
'seo_meta_tags' => $this->setMetaTags($entity, $uri, $url)
];
$seoUriEntity = $SeoUris->newEntity($uriEntity);
$SeoUris->save($seoUriEntity);
$uris[] = $seoUriEntity;
}
return $uris;
}
/**
* @param Cake\ORM\Entity $entity The entity
* @param string $uri The Uri
* @param array $config Options configuration
* @return mixed array|false
*/
public function setMetaTags(Entity $entity, $uri, array $config = [])
{
if (array_key_exists('meta_tags', $config) && is_array($config['meta_tags'])) {
$metaTags = [];
foreach ($config['meta_tags'] as $key => $value) {
if (isset($value['callback'])) {
$defaults = [
'function' => '',
'options' => []
];
if (!is_array($value['callback'])) {
throw new \Exception("callback key must be an array");
}
$callback = array_merge($defaults, $value['callback']);
unset($value['callback']);
if (is_array($callback['function'])) {
$value['content'] = call_user_func($callback['function'], $value, $entity, $callback['options']);
} else {
$value['content'] = call_user_func([$this, $callback['function']], $value, $entity, $callback['options']);
}
}
$metaTags[] = [
'name' => $key,
'content' => $this->_formatTemplate($value['content'], $entity),
'is_http_equiv' => (array_key_exists('is_http_equiv', $value)) ? $value['is_http_equiv'] : false,
'is_property' => (array_key_exists('is_property', $value)) ? $value['is_property'] : false
];
}
return $metaTags;
}
return false;
}
/**
* @param Cake\ORM\Entity $entity The entity
* @param string $uri The Uri
* @param array $config Configuration array for the uri
* @return mixed array|false
*/
public function setCanonical(Entity $entity, $uri, array $config = [])
{
if (array_key_exists('canonical', $config) && $config['canonical'] === true) {
return [
'canonical' => Router::fullBaseUrl() . $uri,
'active' => true
];
}
return false;
}
/**
* @param Cake\ORM\Entity $entity The entity
* @param string $uri The Uri
* @param array $config Configuration array for the uri
* @return mixed string|false ex.: My super title
*/
public function setSeoTitle(Entity $entity, $uri, array $config)
{
if (array_key_exists('title', $config)) {
return $this->_formatTemplate($config['title'], $entity);
}
return false;
}
/**
* @param Cake\ORM\Entity $entity The entity
* @param array $urlParams The optionals parameters to generate a route
* @return string ex.: /articles/view/foo
* @todo Allow named routes
*/
protected function _getUri(Entity $entity, Array $urlParams)
{
$uri = null;
if (is_array($urlParams['url'])) {
if (array_key_exists('_callback', $urlParams['url'])) {
$urlParams['url'] = call_user_func($urlParams['url']['_callback'], $entity, $urlParams);
} elseif (array_key_exists('_', $urlParams['url'])) {
foreach ($urlParams['url']['_'] as $extraParam => $value) {
$urlParams['url'][$extraParam] = $entity->{$value};
}
unset($urlParams['url']['_']);
}
$uri = Router::url($urlParams['url']);
} else {
// named route
}
return $uri;
}
/**
* Format Template
*
* Return a formated template to use as content for a tag
* ex :
* Hello {{name}} -> Hello John
* {{name}} is the property entity
*
* @param string $pattern a pattern to match
* @param Cake\ORM\Entity $entity The entity
* @return string
* @todo Allow {{model.field}} syntax
*/
protected function _formatTemplate($pattern, $entity)
{
$template = preg_replace_callback('/{{([\w\.]+)}}/', function ($matches) use ($entity) {
if (preg_match('/^([_\w]+)\.(\w+)$/', $matches[1], $x)) {
$table = TableRegistry::get(Inflector::tableize($x[1]));
$matchEntity = $table->get($entity->{$x[1] . '_id'});
return $matchEntity->{$x[2]};
}
if ($entity->has($matches[1])) {
return $entity->{$matches[1]};
}
}, $pattern);
return trim($template);
}
}
| mit |
github/codeql | javascript/ql/test/library-tests/Expr/legacyletexpr.js | 41 | console.log(let (x = 23, y = 19) x + y);
| mit |
Dynatrace/superdump | src/SuperDumpService/Services/Analyzers/AnalyzerJob.cs | 1729 | using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using SuperDumpService.Models;
namespace SuperDumpService.Services.Analyzers {
public enum AnalyzerState {
/// <summary>
/// No Further Analyzers should be executed.
/// </summary>
Cancelled,
/// <summary>
/// A primary dump was sucessfully analyzed. Further Pipeline Steps are executed.
/// </summary>
Succeeded,
/// <summary>
/// No primary dump was analyzed sucessfully. Further Pipeline Steps are executed.
/// </summary>
Failed,
/// <summary>
/// Indicates the first Analysis step.
/// </summary>
Initialized
}
/// <summary>
/// This class defines a step in the analysis pipeline that enriches the result created by InitialAnalyzers.
/// </summary>
public abstract class AnalyzerJob {
public abstract Task<AnalyzerState> AnalyzeDump(DumpMetainfo dumpInfo, string analysisWorkingDir, AnalyzerState previousState);
}
/// <summary>
/// An InitialAnalyzer is a step in the analysis pipeline that can create new DumpMetainfo objects.
/// Each DumpMetainfo object is then analyzed seperately.
///
/// This class should be used for main analysis steps, e.g. the analyzer creates a result that can be shown to the user on its own.
/// </summary>
public abstract class InitalAnalyzerJob : AnalyzerJob {
public abstract Task<IEnumerable<DumpMetainfo>> CreateDumpInfos(string bundleId, DirectoryInfo directory);
}
/// <summary>
/// This analyzer steps depend on the sucessful analysis of previous steps. These steps are only executed if the main analyis was sucessful.
/// </summary>
public abstract class PostAnalysisJob {
public abstract Task AnalyzeDump(DumpMetainfo dumpInfo);
}
}
| mit |
MontyThibault/Force-Sensor-Integration | MayaIntegration/SixAxis.py | 2895 | from ctypes import *
import maya.cmds as cmds
import Calibration as C
import unittest
class SixAxis(object):
def __init__(self, device, channels, name, load = True):
""" Maps a single six-axis sensor to a Maya transform
Device: An instance of PAIO.AIODevice()
Channels: The channel indicies for the sensor in the following order:
[forceX, forceY, forceZ, torqueX, torqueY, torqueZ] """
self.device = device
self.channels = channels
self.measurements = (c_float * 6)()
if len(channels) != 6:
assert("Error: must give six channels in SixAxis.")
if name:
self.name = 'SixAxis_%s' % name
else:
self.name = 'SixAxis_%s' % hash(self)
self.transform = cmds.createNode('transform', name = self.name)
self.calibration = C.SixAxisCalibrationMatrix(name, load)
print('Created new SixAxis %s' % self.name)
def __del__(self):
cmds.delete(self.transform)
@property
def forces(self):
""" Channels 1 - 3 """
return self.calibration.process(self.measurements)[:3]
@property
def torques(self):
""" Channels 4 - 6 """
return self.calibration.process(self.measurements)[3:]
def updateMeasurements(self):
""" Update sensor measurements. Wrap this in an executeDeferred(). """
ptr = cast(self.measurements, c_voidp).value
for (i, channel) in enumerate(self.channels):
slot = cast(ptr + (4 * i), POINTER(c_float))
self.device.AioSingleAiEx(c_short(channel), slot)
# This will feed the data into the calibration object so that the user
# can set calibrations without accessing the data first.
self.forces
self.torques
def updateTransform(self):
""" Update Maya transform object. Wrap this in an executeDeferred(). """
cmds.xform(self.transform, t = self.forces, ro = self.torques)
# def setChannelsZero(self, channels):
# """ Sets given channels to zero. These are channel indicies, not the
# channel numbers themselves. For instance, setting all forces to zero
# would be `setChannelsZero([0, 1, 2])` """
# for channel in channels:
# self.calibrations[channel].setZero()
# def setChannelsOne(self, channels):
# """ Sets given channels to one. These are channel indicies, not the
# channel numbers themselves. For instance, setting all forces to one
# would be `setChannelsOne([0, 1, 2])` """
# for channel in channels:
# self.calibrations[channel].setOne()
class Tests(object):
class FauxDevice(object):
def Init():
pass
def AioSetAiRangeAll(range):
pass
def AioSingleAiEx(deviceID, c_channel, slot):
from random import random
slot.contents = c_float(random() + c_channel.value)
def setUp(self):
self.device = self.FauxDevice()
self.channels = [6, 7, 8, 9, 10, 11]
def test_create_and_process_six_axis(self):
rock = SixAxis(self.device, self.channels, "test", False)
rock.updateMeasurements()
assert rock.forces == rock.measurements[:3] | mit |
peachyang/py_website | sql.php | 555 | <?php
/*
* cms_block
* cms_block_language
* cms_category
* cms_category_language
* cms_category_page
* cms_page
* cms_page_language
* core_config
* eav_attribute
* eav_attribute_label
* eav_attribute_group
* eav_attribute_group_label
* eav_attribute_option
* eav_attribute_option_label
* eav_attribute_set
* eav_attribute_set_label
* eav_entity_type
* email_template
* email_template_language
* message_template
* message_template_language
* resource
* resource_category
* resource_category_language
*/
| mit |
motherjones/datawrapper | lib/utils/chart_content.php | 9582 | <?php
function get_chart_content($chart, $user, $published = false, $debug = false) {
$theme_css = array();
$theme_js = array();
$protocol = !empty($_SERVER['HTTPS']) ? "https" : "http";
$next_theme_id = $chart->getTheme();
$locale = DatawrapperSession::getLanguage();
while (!empty($next_theme_id)) {
$theme = DatawrapperTheme::get($next_theme_id);
$theme_js[] = $theme['__static_path'] . $next_theme_id . '.js';
if ($theme['hasStyles']) {
$theme_css[] = $theme['__static_path'] . $next_theme_id . '.css';
}
$next_theme_id = $theme['extends'];
}
$abs = $protocol . '://' . $GLOBALS['dw_config']['domain'];
$chart_abs = $protocol . '://' . $GLOBALS['dw_config']['chart_domain'];
$debug = $GLOBALS['dw_config']['debug'] == true || $debug;
if ($published && !$debug && !empty($GLOBALS['dw_config']['asset_domain'])) {
$base_js = array(
'//' . $GLOBALS['dw_config']['asset_domain'] . '/globalize.min.js',
'//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js',
'//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js'
);
if (substr($locale, 0, 2) != 'en') {
$base_js[] = '//' . $GLOBALS['dw_config']['asset_domain'] . '/cultures/globalize.culture.' . str_replace('_', '-', $locale) . '.js';
}
} else {
// use local assets
$base_js = array(
$abs . '/static/vendor/globalize/globalize.min.js',
$abs . '/static/vendor/underscore/underscore-1.5.2.min.js',
$abs . '/static/vendor/jquery/jquery-1.10.2'.($debug ? '' : '.min').'.js'
);
if (substr($locale, 0, 2) != 'en') {
$base_js[] = $abs . '/static/vendor/globalize/cultures/globalize.culture.' . str_replace('_', '-', $locale) . '.js';
}
}
$vis_js = array();
$vis_css = array();
$next_vis_id = $chart->getType();
$vis_libs = array();
$vis_libs_cdn = array();
$vis_libs_local = array();
$vis_locale = array(); // visualizations may define localized strings, e.g. "other"
while (!empty($next_vis_id)) {
$vis = DatawrapperVisualization::get($next_vis_id);
$vjs = array();
if (!empty($vis['libraries'])) {
foreach ($vis['libraries'] as $url) {
if (!is_array($url)) {
$url = array("local" => $url, "cdn" => false);
}
if ($url['cdn']) $vis_libs_cdn[] = $url['cdn'];
// at first we check if the library lives in ./lib of the vis module
if (file_exists(ROOT_PATH . 'www/' . $vis['__static_path'] . $url['local'])) {
$u = $vis['__static_path'] . $url['local'];
} else if (file_exists(ROOT_PATH . 'www/static/vendor/' . $url['local'])) {
$u = '/static/vendor/' . $url['local'];
} else {
die("could not find required library ".$url["local"]);
}
$vis_libs[] = $u;
if (!$url['cdn']) $vis_libs_local[] = $u;
}
}
if (!empty($vis['locale']) && is_array($vis['locale'])) {
foreach ($vis['locale'] as $term => $translations) {
if (!isset($vis_locale[$term])) $vis_locale[$term] = $translations;
}
}
$vjs[] = $vis['__static_path'] . $vis['id'] . '.js';
$vis_js = array_merge($vis_js, array_reverse($vjs));
if ($vis['hasCSS']) {
$vis_css[] = $vis['__static_path'] . $vis['id'] . '.css';
}
$next_vis_id = !empty($vis['extends']) ? $vis['extends'] : null;
}
$stylesheets = array_merge(
array('/static/css/chart.base.css'),
$vis_css,
array_reverse($theme_css)
);
$the_vis = DatawrapperVisualization::get($chart->getType());
$the_vis['locale'] = $vis_locale;
$the_theme = DatawrapperTheme::get($chart->getTheme());
$the_vis_js = get_vis_js($the_vis, array_merge(array_reverse($vis_js), $vis_libs_local));
$the_theme_js = get_theme_js($the_theme, array_reverse($theme_js));
$the_chart_js = get_chart_js();
if ($published) {
$scripts = array_merge(
$base_js,
$vis_libs_cdn,
array(
$chart_abs . '/lib/' . $the_vis_js[0],
$chart_abs . '/lib/' . $the_theme_js[0],
$chart_abs . '/lib/' . $the_chart_js[0]
)
);
$stylesheets = array($chart->getID().'.all.css');
// NOTE: replace `/static/` by `assets/` in the `__static_path` value,
// since vis assets are handle by DatawrapperVisualization
$replace_in = $the_vis['__static_path']; $replace_by = 'assets/'; $replace = '/static/';
$the_vis['__static_path'] = substr_replace(
$replace_in, // subject
$replace_by, // replace by
strrpos($replace_in, $replace), // position
strlen($replace)); // length
$the_theme['__static_path'] = '';
} else {
$scripts = array_unique(
array_merge(
$base_js,
array('/static/js/dw-2.0'.($debug ? '' : '.min').'.js'),
array_reverse($theme_js),
array_reverse($vis_js),
$vis_libs,
array('/static/js/dw/chart.base.js')
)
);
}
$cfg = $GLOBALS['dw_config'];
$published_urls = DatawrapperHooks::execute(DatawrapperHooks::GET_PUBLISHED_URL, $chart);
if (empty($published_urls)) {
$chart_url = $protocol . '://' . $cfg['chart_domain'] . '/' . $chart->getID() . '/';
} else {
$chart_url = $published_urls[0]; // ignore urls except from the first one
}
$page = array(
'chartData' => $chart->loadData(),
'chart' => $chart,
'lang' => strtolower(substr($locale, 0, 2)),
'metricPrefix' => get_metric_prefix($locale),
'l10n__domain' => $the_theme['__static_path'],
'origin' => !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
'DW_DOMAIN' => $protocol . '://' . $cfg['domain'] . '/',
'DW_CHART_DATA' => $protocol . '://' . $cfg['domain'] . '/chart/' . $chart->getID() . '/data.csv',
'ASSET_PATH' => $published ? '' : $the_theme['__static_path'],
'chartUrl' => $chart_url,
'embedCode' => '<iframe src="' .$chart_url. '" frameborder="0" allowtransparency="true" allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen width="'.$chart->getMetadata('publish.embed-width') . '" height="'. $chart->getMetadata('publish.embed-height') .'"></iframe>',
'chartUrlFs' => strpos($chart_url, '.html') > 0 ? str_replace('index.html', 'fs.html', $chart_url) : $chart_url . '?fs=1',
// used in chart.twig
'stylesheets' => $stylesheets,
'scripts' => $scripts,
'visualization' => $the_vis,
'theme' => $the_theme,
'chartLocale' => str_replace('_', '-', $locale),
// the following is used by chart_publish.php
'vis_js' => $the_vis_js,
'theme_js' => $the_theme_js,
'chart_js' => $the_chart_js
);
return $page;
}
/*
* returns an array
* [0] filename of the vis js class, eg, vis/column-chart-7266c4ee39b3d19f007f01be8853ac87.min.js
* [1] minified source code
*/
function get_vis_js($vis, $visJS) {
// merge vis js into a single file
$all = '';
$org = DatawrapperSession::getUser()->getCurrentOrganization();
if (!empty($org)) $org = '/'.$org->getID(); else $org = '';
$keys = DatawrapperHooks::execute(DatawrapperHooks::GET_PUBLISH_STORAGE_KEY);
if (is_array($keys)) $org .= '/' . join($keys, '/');
foreach ($visJS as $js) {
if (substr($js, 0, 7) != "http://" && substr($js, 0, 8) != "https://" && substr($js, 0, 2) != '//') {
$all .= "\n\n\n" . file_get_contents(ROOT_PATH . 'www' . $js);
}
}
$all = \JShrink\Minifier::minify($all);
$all = file_get_contents(ROOT_PATH . 'www/static/js/dw-2.0.min.js') . "\n\n" . $all;
// generate md5 hash of this file to get filename
$vis_js_md5 = md5($all.$org);
$vis_path = 'vis/' . $vis['id'] . '-' . $vis_js_md5 . '.min.js';
return array($vis_path, $all);
}
/*
* returns an array
* [0] filename of the theme js class, eg, theme/default-7266c4ee39b3d19f007f01be8853ac87.min.js
* [1] minified source code
*/
function get_theme_js($theme, $themeJS) {
$all = '';
$org = DatawrapperSession::getUser()->getCurrentOrganization();
if (!empty($org)) $org = '/'.$org->getID(); else $org = '';
$keys = DatawrapperHooks::execute(DatawrapperHooks::GET_PUBLISH_STORAGE_KEY);
if (is_array($keys)) $org .= '/' . join($keys, '/');
foreach ($themeJS as $js) {
if (substr($js, 0, 7) != "http://" && substr($js, 0, 8) != "https://" && substr($js, 0, 2) != '//') {
$all .= "\n\n\n" . file_get_contents(ROOT_PATH . 'www' . $js);
}
}
$all = \JShrink\Minifier::minify($all);
$theme_js_md5 = md5($all.$org);
$theme_path = 'theme/' . $theme['id'] . '-' . $theme_js_md5 . '.min.js';
return array($theme_path, $all);
}
function get_chart_js() {
$js = file_get_contents(ROOT_PATH . 'www/static/js/dw/chart.base.js');
$min = \JShrink\Minifier::minify($js);
$md5 = md5($min);
return array('chart-'.$md5.'.min.js', $min);
}
| mit |
warehouseman/pkgd-todos | packages/todos-pkg/client/todos-pkg.js | 1949 | Meteor.subscribe("tasks");
Template.todos.helpers({
tasks: function () {
if (Session.get("hideCompleted")) {
// If hide completed is checked, filter tasks
return Tasks.find({checked: {$ne: true}}, {sort: {createdAt: -1}});
} else {
// Otherwise, return all of the tasks
return Tasks.find({}, {sort: {createdAt: -1}});
}
}
, hideCompleted: function () {
return Session.get("hideCompleted");
}
, incompleteCount: function () {
return Tasks.find({checked: {$ne: true}}).count();
}
});
Template.todos.events({
"submit .new-task": function (event) {
// This function is called when the new task form is submitted
var text = event.target.text.value;
Meteor.call("addTask", text);
/*
Tasks.insert({
text: text
, createdAt: new Date() // current time
, owner: Meteor.userId() // _id of logged in user
, username: Meteor.user().username // username of logged in user
});
*/
// Clear form
event.target.text.value = "";
// Prevent default form submit
return false;
}
, "change .hide-completed input": function (event) {
Session.set("hideCompleted", event.target.checked);
}
});
Template.task.helpers({
isOwner: function () {
return this.owner === Meteor.userId();
}
});
Template.task.events({
"click .toggle-checked": function () {
// Set the checked property to the opposite of its current value
Meteor.call("setChecked", this._id, ! this.checked);
// Tasks.update(this._id, {$set: {checked: ! this.checked}});
}
, "click .delete": function () {
Meteor.call("deleteTask", this._id);
// Tasks.remove(this._id);
}
, "click .toggle-private": function () {
Meteor.call("setPrivate", this._id, ! this.private);
}
});
Accounts.ui.config({
passwordSignupFields: "USERNAME_ONLY"
});
| mit |
ppot14/chinchilla | src/main/java/com/chinchilla/persistence/dao/ElectricidadDAO.java | 1054 | package com.chinchilla.persistence.dao;
import com.chinchilla.persistence.MyBatisDAO;
import com.chinchilla.persistence.objects.Electricidad;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import org.springframework.stereotype.Repository;
/**
* Simple example DAO which uses the MyBatisDAO Helper Framework
*/
@Repository("electricidadDAO")
public class ElectricidadDAO extends MyBatisDAO<Electricidad, Integer> {
private static Logger log = (Logger) LoggerFactory.getLogger(ElectricidadDAO.class);
//Don't forget to define the default custom constructor when implementing a new
//child DAO class, and set the class type accordingly
public ElectricidadDAO() throws IOException {
this(Electricidad.class);
}
public ElectricidadDAO(Class<Electricidad> type) throws IOException {
super(type);
}
// public ElectricidadDAO(Class<Electricidad> type, SqlSessionFactory containerSessionFactory) {
// super(type, containerSessionFactory);
// }
}
| mit |
thomasfrei/Nova | Library/Nova/Http/Request.php | 4843 | <?php
/**
* Nova - PHP 5 Framework
*
* @package Http
* @author Thomas Frei <thomast.frei@gmail.com>
* @copyright 2013 Thomas Frei
* @license https://github.com/thomasfrei/Nova/blob/master/License.txt
* @link https://github.com/thomasfrei/Nova
*/
Namespace Nova\Http;
use Nova\Http\AbstractRequest as AbstractRequest;
/**
* Request
*
* @package Http
* @author Thomas Frei <thomast.frei@gmail.com>
* @copyright 2013 Thomas Frei
* @license https://github.com/thomasfrei/Nova/blob/master/License.txt
* @link https://github.com/thomasfrei/Nova
* @todo Implement isPUT()
* @todo Implement isDELETE()
* @todo Implement isHEAD()
* @todo Implement isOPTIONS()
* @todo Implement setQuery()
* @todo Implement getCookie()
*/
Class Request extends AbstractRequest
{
/**
* The Request Uri
* @var string
*/
protected $_requestUri = null;
/**
* The Base Uri
* @var string
*/
protected $_baseUri;
/**
* Contructor
*
* Automatically calls the setRequestUri and setBaseUri methods
*
* @param string $requestUri
* @return void
*/
public function __construct($requestUri = null)
{
$this->setRequestUri($requestUri)->setBaseUri();
}
/**
* Sets the Request Uri
*
* @param mixed
* @return AbstractRequest
*/
public function setRequestUri($requestUri = null)
{
if ($requestUri !== null) {
$this->_requestUri = $requestUri;
} else {
if (isset($_SERVER["REQUEST_URI"])) {
$this->_requestUri = $_SERVER["REQUEST_URI"];
}
}
return $this;
}
/**
* Returns the Request Uri.
*
* @return string The Request Uri
*/
public function getRequestUri()
{
return $this->_requestUri;
}
/**
* Returns the base Uri
*
* @return string _baseUri
*/
public function getBaseUri()
{
return $this->_baseUri;
}
/**
* Sets the Base Uri
*
* @param string $baseUri
* @return AbstractRequest
*/
public function setBaseUri($baseUri = null)
{
if ($baseUri === null) {
if (($this->getServer("SCRIPT_NAME")) !== null) {
$this->_baseUri = $this->getServer("SCRIPT_NAME");
} elseif (($this->getServer("PHP_SELF")) !== null) {
$this->_baseUri = $this->getServer("PHP_SELF");
}
} else {
$this->_baseUri = $baseUri;
}
return $this;
}
/**
* Returns a Value Fron the $_SERVER global
*
* Returns Entire $_SERVER Array if Key has a value of null
*
* @param mixed $key Key or null
* @param mixed $default Default Value to Return if Key is not found
* @return mixed
*/
public function getServer($key = null, $default = null)
{
if (null === $key) {
return $_SERVER;
}
return (isset($_SERVER[$key])) ? $_SERVER[$key] : $default;
}
/**
* Retrieve a Value of the $_POST Superglobal.
*
* Returns Entire $_POST Array if Key has a Value of null.
*
* @param mixed $key
* @param mixed $default Default Value to Return if Key is not found
* @return mixed
*/
public function getPost($key = null, $default = null)
{
if ($key === null) {
return $_POST;
}
return (isset($_POST[$key])) ? $_POST[$key] : $default;
}
/**
* Retrieve a Value of the $_GET Superglobal.
*
* Return entire $_GET array if kex has a value of null
*
* @param mixed $key
* @param mixed $default Default value to return if key is not found
* @return mixed
*/
public function getQuery($key = null, $default = null)
{
if ($key === null) {
return $_GET;
}
return (isset($_GET[$key])) ? $_GET[$key] : $default;
}
/**
* Returns The Request Method
*
* @return string Request Method
*/
public function getMethod()
{
return $this->getServer('REQUEST_METHOD');
}
/**
* Is this a POST Request ?
*
* @return boolean
*/
public function isPost()
{
return ($this->getMethod() === 'POST');
}
/**
* Is this a GET Request ?
*
* @return boolean
*/
public function isGet()
{
return ($this->getMethod() === 'GET');
}
/**
* Is the request a javascript XmlHttpRequest ?
*
* @return boolean
*/
public function isXmlHttpRequest()
{
return ($this->getServer('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest');
}
} | mit |
praktijkindex/ransack | spec/ransack/predicate_spec.rb | 4826 | require 'spec_helper'
module Ransack
describe Predicate do
before do
@s = Search.new(Person)
end
shared_examples 'wildcard escaping' do |method, regexp|
it 'automatically converts integers to strings' do
subject.parent_id_cont = 1
expect { subject.result }.to_not raise_error
end
it "escapes '%', '.' and '\\\\' in value" do
subject.send(:"#{method}=", '%._\\')
subject.result.to_sql.should match(regexp)
end
end
describe 'eq' do
it 'generates an equality condition for boolean true' do
@s.awesome_eq = true
field = "#{quote_table_name("people")}.#{
quote_column_name("awesome")}"
@s.result.to_sql.should match /#{field} = #{
ActiveRecord::Base.connection.quoted_true}/
end
it 'generates an equality condition for boolean false' do
@s.awesome_eq = false
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
@s.result.to_sql.should match /#{field} = #{
ActiveRecord::Base.connection.quoted_false}/
end
it 'does not generate a condition for nil' do
@s.awesome_eq = nil
@s.result.to_sql.should_not match /WHERE/
end
end
describe 'cont' do
it_has_behavior 'wildcard escaping', :name_cont,
(if ActiveRecord::Base.connection.adapter_name == "PostgreSQL"
/"people"."name" ILIKE '%\\%\\._\\\\%'/
elsif ActiveRecord::Base.connection.adapter_name == "Mysql2"
/`people`.`name` LIKE '%\\\\%\\\\._\\\\\\\\%'/
else
/"people"."name" LIKE '%%._\\%'/
end) do
subject { @s }
end
it 'generates a LIKE query with value surrounded by %' do
@s.name_cont = 'ric'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} I?LIKE '%ric%'/
end
end
describe 'not_cont' do
it_has_behavior 'wildcard escaping', :name_not_cont,
(if ActiveRecord::Base.connection.adapter_name == "PostgreSQL"
/"people"."name" NOT ILIKE '%\\%\\._\\\\%'/
elsif ActiveRecord::Base.connection.adapter_name == "Mysql2"
/`people`.`name` NOT LIKE '%\\\\%\\\\._\\\\\\\\%'/
else
/"people"."name" NOT LIKE '%%._\\%'/
end) do
subject { @s }
end
it 'generates a NOT LIKE query with value surrounded by %' do
@s.name_not_cont = 'ric'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} NOT I?LIKE '%ric%'/
end
end
describe 'null' do
it 'generates a value IS NULL query' do
@s.name_null = true
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} IS NULL/
end
it 'generates a value IS NOT NULL query when assigned false' do
@s.name_null = false
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} IS NOT NULL/
end
end
describe 'not_null' do
it 'generates a value IS NOT NULL query' do
@s.name_not_null = true
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} IS NOT NULL/
end
it 'generates a value IS NULL query when assigned false' do
@s.name_not_null = false
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} IS NULL/
end
end
describe 'present' do
it %q[generates a value IS NOT NULL AND value != '' query] do
@s.name_present = true
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} IS NOT NULL AND #{field} != ''/
end
it %q[generates a value IS NULL OR value = '' query when assigned false] do
@s.name_present = false
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} IS NULL OR #{field} = ''/
end
end
describe 'blank' do
it %q[generates a value IS NULL OR value = '' query] do
@s.name_blank = true
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} IS NULL OR #{field} = ''/
end
it %q[generates a value IS NOT NULL AND value != '' query when assigned false] do
@s.name_blank = false
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
@s.result.to_sql.should match /#{field} IS NOT NULL AND #{field} != ''/
end
end
end
end
| mit |
fr43nk/vscode-clearcase | src/ccIgnoreHandler.ts | 3239 | import { workspace, WorkspaceFolder, Uri, EventEmitter } from "vscode";
import { existsSync, readFileSync, statSync } from "fs";
import { join, dirname, sep } from "path";
import ignore from "ignore";
import { Model, ModelHandler } from "./model";
export class IgnoreHandler {
private fileIgnores: FileIgnore[];
private m_onFilterRefreshed: EventEmitter<void>;
constructor(private m_fsWatch: ModelHandler) {
this.m_onFilterRefreshed = new EventEmitter<void>();
this.init();
}
get OnFilterRefreshed(): EventEmitter<void> {
return this.m_onFilterRefreshed;
}
public init() {
this.fileIgnores = [];
workspace.workspaceFolders.forEach((folder: WorkspaceFolder) => {
let l_m = this.m_fsWatch.addWatcher(join(folder.uri.fsPath, '.ccignore'));
l_m.onWorkspaceChanged(this.refreshFilter, this);
l_m.onWorkspaceCreated(this.refreshFilter, this);
l_m.onWorkspaceDeleted(this.removeFilter, this);
let dir = this.appendSeparator(folder.uri.fsPath);
this.fileIgnores.push(new FileIgnore(Uri.file(dir)));
});
}
public getFolderIgnore(path: Uri | string): FileIgnore | null {
for (let i = 0; i < this.fileIgnores.length; i++) {
let p:string = "";
if (typeof path == "string") {
let t = this.appendSeparator(path);
}
else {
let t = this.appendSeparator(path.fsPath);
if (t.indexOf(this.fileIgnores[i].PathStr) == 0 && this.fileIgnores[i].HasIgnore === true)
return this.fileIgnores[i];
}
}
return null;
}
public refreshFilter(fileObj:Uri) {
let dir = this.appendSeparator(fileObj.fsPath);
for (let i = 0; i < this.fileIgnores.length; i++) {
if(this.fileIgnores[i].PathStr == dir) {
this.fileIgnores[i] = new FileIgnore(Uri.file(dir));
this.m_onFilterRefreshed.fire();
return;
}
}
this.fileIgnores.push(new FileIgnore(Uri.file(dir)));
this.m_onFilterRefreshed.fire();
}
public removeFilter(fileObj:Uri) {
let dir = this.appendSeparator(fileObj.fsPath);
for (let i = 0; i < this.fileIgnores.length; i++) {
if(this.fileIgnores[i].PathStr == dir) {
this.fileIgnores.splice(i, 1);
this.m_onFilterRefreshed.fire();
return;
}
}
}
public appendSeparator(path:string): string {
const ps = statSync(path);
if( ps.isFile() === true )
path = dirname(path);
if( path.substr(-1, 1) !== sep )
return path + sep;
return path;
}
}
export class FileIgnore {
private path: Uri;
private hasIgnore: boolean = false;
private ignore: any = null;
constructor(path: Uri) {
this.init(path);
}
public init(path: Uri) {
this.ignore = ignore();
this.path = path;
let p = join(path.fsPath, ".ccignore");
if (existsSync(p) == true) {
this.hasIgnore = true;
this.ignore.add(readFileSync(p).toString());
}
}
public get Path(): Uri {
return this.path;
}
public get PathStr(): string {
let p = this.Path.fsPath;
p = p.substr(-1, 1) !== sep ? p+sep : p;
return p;
}
public get Ignore(): any {
return this.ignore;
}
public get HasIgnore(): boolean {
return this.hasIgnore;
}
} | mit |
wappulehti-apy/diilikone-api | autoapp.py | 55 | from diilikone import Application
app = Application()
| mit |
ronency/ajaxDebounce | jquery.ajaxDebounce.js | 1568 | (function ($) {
var count = 0;
var lastFetchId = 0,
timeoutActive,
defaults = {
delay: 250,
};
$.ajaxDebounce = function( options ) {
var settings = $.extend(defaults, options );
var doAjax = function(ajaxOptions){
var currentFetchId = new Date().getTime();
timeoutActive = null; // Resets the "non-active" delay count
var smartAjaxOptions = $.extend({}, ajaxOptions);
smartAjaxOptions.success = function(data) {
if ( isMostRecentCall(currentFetchId) ) {
ajaxOptions.success(data);
}
};
smartAjaxOptions.error = function(xhr, status, error) {
if ( !!ajaxOptions.error && isMostRecentCall(currentFetchId) ) {
ajaxOptions.error(xhr, status, error);
}
}
var isMostRecentCall = function(currentId) {
// To resolve a race-condition, where a later ajax call comes back before an earlier one.
if (currentId < lastFetchId) {
return false;
}
lastFetchId = currentId;
return true;
}
$.ajax(smartAjaxOptions);
};
if(timeoutActive){
clearTimeout(timeoutActive);
}
timeoutActive = setTimeout(function(){ doAjax(options.ajax); }, settings.delay);
};
}(jQuery));
var $input = $('input');
var getAjaxObject = function(){
return {
url: '/echo/html/',
data: {value: $input.val()},
success: function(data){},
error: function(xhr, status, error){}
};
}
$input.keyup(function(){$.ajaxDebounce({delay: 100, ajax: getAjaxObject()});});
| mit |
tcdl/msb-java | core/src/main/java/io/github/tcdl/msb/threading/ConsumerExecutorFactoryImpl.java | 1190 | package io.github.tcdl.msb.threading;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ConsumerExecutorFactoryImpl implements ConsumerExecutorFactory {
protected static final int QUEUE_SIZE_UNLIMITED = -1;
private final BasicThreadFactory threadFactory = new BasicThreadFactory.Builder()
.namingPattern("msb-consumer-thread-%d")
.build();
@Override
public ExecutorService createConsumerThreadPool(int numberOfThreads, int queueCapacity) {
BlockingQueue<Runnable> queue;
if (queueCapacity == QUEUE_SIZE_UNLIMITED) {
queue = new LinkedBlockingQueue<>();
} else {
queue = new ArrayBlockingQueue<>(queueCapacity);
}
return new ThreadPoolExecutor(numberOfThreads, numberOfThreads,
0L, TimeUnit.MILLISECONDS,
queue,
threadFactory);
}
}
| mit |