code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumsShouldHaveZeroValueAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpEnumsShouldHaveZeroValueFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumsShouldHaveZeroValueAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicEnumsShouldHaveZeroValueFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class EnumsShouldHaveZeroValueFixerTests
{
[Fact]
public async Task CSharp_EnumsShouldZeroValueFlagsRenameAsync()
{
var code = @"
public class Outer
{
[System.Flags]
public enum E
{
A = 0,
B = 3
}
}
[System.Flags]
public enum E2
{
A2 = 0,
B2 = 1
}
[System.Flags]
public enum E3
{
A3 = (ushort)0,
B3 = (ushort)1
}
[System.Flags]
public enum E4
{
A4 = 0,
B4 = (int)2 // Sample comment
}
[System.Flags]
public enum NoZeroValuedField
{
A5 = 1,
B5 = 2
}";
var expectedFixedCode = @"
public class Outer
{
[System.Flags]
public enum E
{
None = 0,
B = 3
}
}
[System.Flags]
public enum E2
{
None = 0,
B2 = 1
}
[System.Flags]
public enum E3
{
None = (ushort)0,
B3 = (ushort)1
}
[System.Flags]
public enum E4
{
None = 0,
B4 = (int)2 // Sample comment
}
[System.Flags]
public enum NoZeroValuedField
{
A5 = 1,
B5 = 2
}";
await VerifyCS.VerifyCodeFixAsync(
code,
new[]
{
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(7, 9, 7, 10).WithArguments("E", "A"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(15, 5, 15, 7).WithArguments("E2", "A2"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(22, 5, 22, 7).WithArguments("E3", "A3"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(29, 5, 29, 7).WithArguments("E4", "A4"),
},
expectedFixedCode);
}
[Fact]
public async Task CSharp_EnumsShouldZeroValueFlagsMultipleZeroAsync()
{
var code = @"// Some comment
public class Outer
{
[System.Flags]
public enum E
{
None = 0,
A = 0
}
}
// Some comment
[System.Flags]
public enum E2
{
None = 0,
A = None
}";
var expectedFixedCode = @"// Some comment
public class Outer
{
[System.Flags]
public enum E
{
None = 0
}
}
// Some comment
[System.Flags]
public enum E2
{
None = 0
}";
await VerifyCS.VerifyCodeFixAsync(
code,
new[]
{
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(5, 17, 5, 18).WithArguments("E"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(13, 13, 13, 15).WithArguments("E2"),
},
expectedFixedCode);
}
[Fact]
public async Task CSharp_EnumsShouldZeroValueNotFlagsNoZeroValueAsync()
{
var code = @"
public class Outer
{
public enum E
{
A = 1
}
public enum E2
{
None = 1,
A = 2
}
}
public enum E3
{
None = 0,
A = 1
}
public enum E4
{
None = 0,
A = 0
}
";
var expectedFixedCode = @"
public class Outer
{
public enum E
{
None,
A = 1
}
public enum E2
{
None,
A = 2
}
}
public enum E3
{
None = 0,
A = 1
}
public enum E4
{
None = 0,
A = 0
}
";
await VerifyCS.VerifyCodeFixAsync(
code,
new[]
{
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(4, 17, 4, 18).WithArguments("E"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(9, 17, 9, 19).WithArguments("E2"),
},
expectedFixedCode);
}
[Fact]
public async Task VisualBasic_EnumsShouldZeroValueFlagsRenameAsync()
{
var code = @"
Public Class Outer
<System.Flags>
Public Enum E
A = 0
B = 1
End Enum
End Class
<System.Flags>
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags>
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
Public Class Outer
<System.Flags>
Public Enum E
None = 0
B = 1
End Enum
End Class
<System.Flags>
Public Enum E2
None = 0
B2 = 1
End Enum
<System.Flags>
Public Enum E3
None = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
await VerifyVB.VerifyCodeFixAsync(
code,
new[]
{
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(5, 9, 5, 10).WithArguments("E", "A"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(12, 5, 12, 7).WithArguments("E2", "A2"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(18, 5, 18, 7).WithArguments("E3", "A3"),
},
expectedFixedCode);
}
[WorkItem(836193, "DevDiv")]
[Fact]
public async Task VisualBasic_EnumsShouldZeroValueFlagsRename_AttributeListHasTriviaAsync()
{
var code = @"
Public Class Outer
<System.Flags> _
Public Enum E
A = 0
B = 1
End Enum
End Class
<System.Flags> _
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags> _
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags> _
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
Public Class Outer
<System.Flags> _
Public Enum E
None = 0
B = 1
End Enum
End Class
<System.Flags> _
Public Enum E2
None = 0
B2 = 1
End Enum
<System.Flags> _
Public Enum E3
None = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags> _
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
await VerifyVB.VerifyCodeFixAsync(
code,
new[]
{
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(5, 9, 5, 10).WithArguments("E", "A"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(12, 5, 12, 7).WithArguments("E2", "A2"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(18, 5, 18, 7).WithArguments("E3", "A3"),
},
expectedFixedCode);
}
[Fact]
public async Task VisualBasic_EnumsShouldZeroValueFlagsMultipleZeroAsync()
{
var code = @"
Public Class Outer
<System.Flags>
Public Enum E
None = 0
A = 0
End Enum
End Class
<System.Flags>
Public Enum E2
None = 0
A = None
End Enum
<System.Flags>
Public Enum E3
A3 = 0
B3 = CUInt(0) ' Not a constant
End Enum";
var expectedFixedCode = @"
Public Class Outer
<System.Flags>
Public Enum E
None = 0
End Enum
End Class
<System.Flags>
Public Enum E2
None = 0
End Enum
<System.Flags>
Public Enum E3
None
End Enum";
await VerifyVB.VerifyCodeFixAsync(
code,
new[]
{
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(4, 17, 4, 18).WithArguments("E"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(11, 13, 11, 15).WithArguments("E2"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(17, 13, 17, 15).WithArguments("E3"),
},
expectedFixedCode);
}
[Fact]
public async Task VisualBasic_EnumsShouldZeroValueNotFlagsNoZeroValueAsync()
{
var code = @"
Public Class C
Public Enum E
A = 1
End Enum
Public Enum E2
None = 1
A = 2
End Enum
End Class
Public Enum E3
None = 0
A = 1
End Enum
Public Enum E4
None = 0
A = 0
End Enum
";
var expectedFixedCode = @"
Public Class C
Public Enum E
None
A = 1
End Enum
Public Enum E2
None
A = 2
End Enum
End Class
Public Enum E3
None = 0
A = 1
End Enum
Public Enum E4
None = 0
A = 0
End Enum
";
await VerifyVB.VerifyCodeFixAsync(
code,
new[]
{
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(3, 17, 3, 18).WithArguments("E"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(7, 17, 7, 19).WithArguments("E2"),
},
expectedFixedCode);
}
}
}
| dotnet/roslyn-analyzers | src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumsShouldHaveZeroValueTests.Fixer.cs | C# | mit | 9,759 |
/**
* Conversion:
* All dynamic tweaked dom id or class names are prefixed with 't-'.
*/
/**
* Config
*/
var PRIVATE_TOKEN = 'xYDh7cpVX8BS2unon1hp';
/**
* Globals.
*/
var autocompleteOpts,
projectOpts,
currentProjectID,
currentProjectPath;
$(function () {
initGlobals();
handleAll();
mapUrlHandler(location.pathname, [
{ pattern: /^\/[^\/]+\/[^\/]+$/, handle: handleProjectDashboard },
{ pattern: /^.+\/tree\/.+/, handle: handleTreeView },
{ pattern: /^.+\/blob\/[^\/]+\/.+\.md$/, handle: handleMdBlobView }
]);
});
$(document).ajaxSuccess(function (event, xhr, settings) {
mapUrlHandler(settings.url, [
{ pattern: /.+\?limit=20/, handle: handleDashboardActivities },
{ pattern: /.+\/refs\/.+\/logs_tree\/.+/, handle: handleLogsTree },
{ pattern: /.+notes\.js\?target_type=issue.+/, handle: handleIssueComments }
]);
});
/**
* Parse useful data from dom elements and assign them to globals for later use.
*/
function initGlobals () {
autocompleteOpts = JSON.parse($('.search-autocomplete-json').attr('data-autocomplete-opts'));
projectOpts = _.where(autocompleteOpts, function (opt) {
if (opt.label.indexOf('project:') !== -1) {
return true;
}
});
currentUser = $('.profile-pic').attr('href').slice(3);
currentProjectID = $(document.body).attr('data-project-id');
currentProjectPath = '/';
if ($('h1.project_name span').length) {
currentProjectPath += $('h1.project_name span').text()
.replace(/\s/, '').replace(/\s/, '').replace(' ', '-').toLowerCase();
} else {
currentProjectPath += currentUser + '/' + $('h1.project_name').text().replace(' ', '-').toLowerCase();
}
currentBranch = $('.project-refs-select').val();
console.log(currentUser, currentProjectID, currentProjectPath, currentBranch);
}
/**
* Document loaded url handlers.
*/
/**
* Handle tweak tasks for all pages.
*/
function handleAll() {
$('.home a').attr('href', $('.home a').attr('href') + '#');
addProjectSelect();
}
/**
* Handle tweak tasks for project dashboard page.
*/
function handleProjectDashboard() {
// Nothing to do.
}
/**
* Handle tweak tasks for files tree view.
*/
function handleTreeView() {
genMdFileTOCAndAdjustHyperlink();
}
/**
* Handle tweak tasks for markdown file blob view.
*/
function handleMdBlobView() {
var slideLink = $('<a class="btn btn-tiny" target="_blank">slide</a>')
.attr('href', '/reveal/md.html?p=' + location.pathname.replace('blob', 'raw'));
$('.file-title .options .btn-group a:nth-child(2)').after(slideLink);
genMdFileTOCAndAdjustHyperlink();
}
/**
* Add project select on the top bar.
*/
function addProjectSelect() {
var projectSelectForm = $('<form class="navbar-form pull-left">' +
'<select id="t-project-list"></select>' +
'</form>');
$('.navbar .container .nav li:nth-child(2)').after(projectSelectForm);
var options = projectOpts.map(function (project) {
return $('<option />').val(project.url.toLowerCase()).text(project.label.slice(9));
});
if (!$('h1.project_name span').length) {
options.unshift('<option>Go to Project</option>');
}
$('#t-project-list').append(options)
.val(currentProjectPath)
.change(function () {
location.href = $(this).val();
});
}
/**
* Generate TOC for markdown file.
*/
function genMdFileTOCAndAdjustHyperlink() {
// Assume there is only one .file-holder.
var fileHolder = $('.file-holder');
if (fileHolder.length !== 1) {
return;
}
var fileTitle = fileHolder.find('.file-title'),
fileContent = fileHolder.find('.file-content');
fileTitle.wrapInner('<div class="t-file-title-header" />')
.scrollToFixed();
var fileTitleFooter = $('<div class="t-file-title-footer"><div class="t-file-title-toc navbar-inner" /></div>')
.appendTo(fileTitle)
.hide();
var fileTitleToc = fileTitleFooter.find('.t-file-title-toc')
.tocify({
context: fileContent,
selectors: 'h1,h2,h3,h4,h5,h6',
showAndHide: false,
hashGenerator: 'pretty',
scrollTo: 38
});
// Some special characters will cause tocify hash error, replace them with empty string.
fileHolder.find('[data-unique]').each(function () {
$(this).attr('data-unique', $(this).attr('data-unique').replace(/\./g, ''));
});
$('<span class="t-file-title-toc-toggler options">' +
'<div class="btn-group tree-btn-group">' +
'<a class="btn btn-tiny" title="Table of Content, \'m\' for shortcut.">TOC</a>' +
'</div>' +
'</span>')
.click(function () {
fileTitleFooter.toggle();
})
.appendTo(fileTitle.find('.t-file-title-header'));
$(document).keyup(function(e) {
switch (e.which) {
case 27:
fileTitleFooter.hide();
break;
case 77:
fileTitleFooter.toggle();
break;
}
});
// Jumpt to ahchor if has one.
if (location.hash) {
var anchor = location.hash.slice(1);
fileTitleToc.find('li[data-unique="' + anchor + '"] a').click();
}
// Adjust hyperlink.
fileContent.find('a').each(function () {
var href = $(this).attr('href');
// Sine 6-2-stable, gitlab will handle relative links when rendering markdown,
// but it didn't work, all relative links fallback to wikis path,
// I didn't have much time to figure out why, so I did this quick fix.
var gitlabPrefixedWikisPath = currentProjectPath + '/wikis/';
var gitlabPrefixedWikisPathIndex = href.indexOf(gitlabPrefixedWikisPath);
if (gitlabPrefixedWikisPathIndex != -1) {
href = href.slice(gitlabPrefixedWikisPath.length);
}
// If not start with '/' and doesn't have '//', consider it as a relative path.
if (/^[^\/]/.test(href) && !/.*\/\/.*/.test(href)) {
var middlePath;
// If end with .ext, this is a file path, otherwise is a directory path.
if (/.*\.[^\/]+$/.test(href)) {
middlePath = '/blob/';
} else {
middlePath = '/tree/';
}
$(this).attr('href', currentProjectPath + middlePath + currentBranch + '/' + href);
}
});
}
/**
* Ajax success url handlers.
*/
/**
* Handle tweak tasks for dashboard activities.
*/
function handleDashboardActivities() {
// Nothing to do.
}
/**
* Handle tweak tasks for issue comments.
*/
function handleIssueComments() {
$('.note-image-attach').each(function () {
var img = $(this);
var wrapper = $('<a class="t-fancybox-note-image-attach" rel="gallery-note-image-attach" />')
.attr('href', img.attr('src'))
.attr('title', img.attr('alt'));
img.wrap(wrapper);
wrapper.commonFancybox();
});
$('.t-fancybox-note-image-attach').commonFancybox();
}
/**
* Handle tweak tasks for git logs tree.
*/
function handleLogsTree() {
// Nothing to do.
}
/**
* Helpers.
*/
function mapUrlHandler(url, handlers) {
handlers.forEach(function (handler) {
if (handler.pattern.test(url)) {
handler.handle();
}
});
}
function mySetInterval(fn, interval) {
setTimeout(function () {
fn(function () {
mySetInterval(fn, interval);
});
}, interval);
}
function myGitLabAPIGet(url, data, cb) {
$.get('/api/v3/' + url + '?private_token=' + PRIVATE_TOKEN, data, function (data) {
cb(data);
});
}
/**
* Extensions
*/
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
(function ($) {
$.fn.extend({
commonFancybox: function () {
$(this).fancybox({
closeBtn: false,
helpers: {
title: { type : 'inside' },
buttons: {}
}
});
}
});
})(jQuery);
| inetfuture/gitlab-tweak | public/tweak.js | JavaScript | mit | 7,663 |
import axios from 'axios'
import pipelineApi from './api'
import { addMessage } from '../../../client/utils/flash-messages'
import { transformValueForAPI } from '../../../client/utils/date'
function transformValuesForApi(values, oldValues = {}) {
const data = {
name: values.name,
status: values.category,
}
function addValue(key, value) {
const existingValue = oldValues[key]
const hasExistingValue = Array.isArray(existingValue)
? !!existingValue.length
: !!existingValue
if (hasExistingValue || (Array.isArray(value) ? value.length : value)) {
data[key] = value || null
}
}
addValue('likelihood_to_win', parseInt(values.likelihood, 10))
addValue('sector', values.sector?.value)
addValue(
'contacts',
values.contacts ? values.contacts.map(({ value }) => value) : []
)
addValue('potential_value', values.export_value)
addValue('expected_win_date', transformValueForAPI(values.expected_win_date))
return data
}
export async function getPipelineByCompany({ companyId }) {
const { data } = await pipelineApi.list({ company_id: companyId })
return {
companyId,
count: data.count,
results: data.results,
}
}
export async function addCompanyToPipeline({ values, companyId }) {
const { data } = await pipelineApi.create({
company: companyId,
...transformValuesForApi(values),
})
addMessage('success', `You added ${values.name} to your pipeline`)
return data
}
export async function getPipelineItem({ pipelineItemId }) {
const { data } = await pipelineApi.get(pipelineItemId)
return data
}
export async function getCompanyContacts({ companyId, features }) {
const contactEndpointVersion = features['address-area-contact-required-field']
? 'v4'
: 'v3'
const { data } = await axios.get(
`/api-proxy/${contactEndpointVersion}/contact`,
{
params: { company_id: companyId, limit: 500 },
}
)
return data.results
}
export async function editPipelineItem({
values,
pipelineItemId,
currentPipelineItem,
}) {
const { data } = await pipelineApi.update(
pipelineItemId,
transformValuesForApi(values, currentPipelineItem)
)
addMessage('success', `You saved changes to ${values.name}`)
return data
}
export async function archivePipelineItem({
values,
pipelineItemId,
projectName,
}) {
const { data } = await pipelineApi.archive(pipelineItemId, {
reason: values.reason,
})
addMessage('success', `You archived ${projectName}`)
return data
}
export async function unarchivePipelineItem({ projectName, pipelineItemId }) {
const { data } = await pipelineApi.unarchive(pipelineItemId)
addMessage('success', `You unarchived ${projectName}`)
return data
}
export async function deletePipelineItem({ projectName, pipelineItemId }) {
const { status } = await pipelineApi.delete(pipelineItemId)
addMessage('success', `You deleted ${projectName} from your pipeline`)
return status
}
| uktrade/data-hub-fe-beta2 | src/apps/my-pipeline/client/tasks.js | JavaScript | mit | 2,963 |
var global = require('../../global');
module.exports = function (data, offset) {
var items = data.items.map(invoiceNote => {
var invoiceItem = invoiceNote.items.map(dataItem => {
var _items = dataItem.items.map(item => {
dueDate = new Date(dataItem.deliveryOrderSupplierDoDate);
dueDate.setDate(dueDate.getDate() + item.paymentDueDays);
return {
deliveryOrderNo: dataItem.deliveryOrderNo,
date: dataItem.deliveryOrderDate,
purchaseRequestRefNo: item.purchaseRequestRefNo,
product: item.product.name,
productDesc: item.product.description,
quantity: item.deliveredQuantity,
uom: item.purchaseOrderUom.unit,
unit: item.unit,
price: item.pricePerDealUnit,
priceTotal: item.pricePerDealUnit * item.deliveredQuantity,
correction: item.correction,
dueDate: dueDate,
paymentMethod: item.paymentMethod,
currRate: item.kursRate,
}
});
_items = [].concat.apply([], _items);
return _items;
})
invoiceItem = [].concat.apply([], invoiceItem);
return invoiceItem;
});
items = [].concat.apply([], items);
var dueDate, paymentMethod;
var dueDates = items.map(item => {
return item.dueDate
})
dueDate = Math.max.apply(null, dueDates);
paymentMethod = items[0].paymentMethod;
var useIncomeTax = data.items
.map((item) => item.useIncomeTax)
.reduce((prev, curr, index) => {
return prev && curr
}, true);
var useVat = data.items
.map((item) => item.useVat)
.reduce((prev, curr, index) => {
return prev && curr
}, true);
var vatRate = 0;
if (useVat) {
vatRate = data.items[0].vat.rate;
}
var sumByUnit = [];
items.reduce(function (res, value) {
if (!res[value.unit]) {
res[value.unit] = {
priceTotal: 0,
unit: value.unit
};
sumByUnit.push(res[value.unit])
}
res[value.unit].priceTotal += value.priceTotal
return res;
}, {});
var locale = global.config.locale;
var moment = require('moment');
moment.locale(locale.name);
var header = [
{
stack: [
'PT. DAN LIRIS',
'Head Office : ',
'Kelurahan Banaran, Kecamatan Grogol',
'Sukoharjo 57193 - INDONESIA',
'PO.BOX 166 Solo 57100',
'Telp. (0271) 740888, 714400',
'Fax. (0271) 735222, 740777'
],
alignment: "left",
style: ['size06', 'bold']
},
{
alignment: "center",
text: 'NOTA INTERN',
style: ['size08', 'bold']
},
'\n'
];
var subHeader = [
{
columns: [
{
width: '50%',
stack: [
{
columns: [{
width: '25%',
text: 'No. Nota Intern',
style: ['size06']
}, {
width: '2%',
text: ':',
style: ['size06']
}, {
width: '*',
text: data.no,
style: ['size06']
}]
},
{
columns: [{
width: '25%',
text: 'Kode Supplier',
style: ['size06']
}, {
width: '2%',
text: ':',
style: ['size06']
}, {
width: '*',
text: data.supplier.code,
style: ['size06']
}]
},
{
columns: [{
width: '25%',
text: 'Nama Supplier',
style: ['size06']
}, {
width: '2%',
text: ':',
style: ['size06']
}, {
width: '*',
text: data.supplier.name,
style: ['size06']
}]
}
]
}, {
width: '50%',
stack: [
{
columns: [{
width: '28%',
text: 'Tgl. Nota Intern',
style: ['size06']
}, {
width: '2%',
text: ':',
style: ['size06']
}, {
width: '*',
text: `${moment(data.date).add(offset, 'h').format("DD MMM YYYY")}`,
style: ['size06']
}]
},
{
columns: [{
width: '28%',
text: 'Tgl. Jatuh Tempo',
style: ['size06']
}, {
width: '2%',
text: ':',
style: ['size06']
}, {
width: '*',
text: `${moment(dueDate).add(offset, 'h').format("DD MMM YYYY")}`,
style: ['size06']
}]
},{
columns: [{
width: '28%',
text: 'Term Pembayaran',
style: ['size06']
}, {
width: '2%',
text: ':',
style: ['size06']
}, {
width: '*',
text: paymentMethod,
style: ['size06']
}]
},
]
}
]
},
{
text: '\n',
style: ['size06']
}
];
var thead = [
{
text: 'No. Surat Jalan',
style: ['size06', 'bold', 'center']
}, {
text: 'Tgl. Surat Jalan',
style: ['size06', 'bold', 'center']
}, {
text: 'Nomor referensi PR',
style: ['size06', 'bold', 'center']
}, {
text: 'Keterangan Barang',
style: ['size06', 'bold', 'center']
}, {
text: 'Jumlah',
style: ['size06', 'bold', 'center']
}, {
text: 'Satuan',
style: ['size06', 'bold', 'center']
}, {
text: 'Harga Satuan',
style: ['size06', 'bold', 'center']
}, {
text: 'Harga Total',
style: ['size06', 'bold', 'center']
}
];
var tbody = items.map(function (item, index) {
return [{
text: item.deliveryOrderNo,
style: ['size06', 'left']
}, {
text: `${moment(item.date).add(offset, 'h').format("DD MMM YYYY")}`,
style: ['size06', 'left']
}, {
text: item.purchaseRequestRefNo,
style: ['size06', 'left']
}, {
text: `${item.product};${item.productDesc}`,
style: ['size06', 'left']
}, {
text: item.quantity,
style: ['size06', 'right']
}, {
text: item.uom,
style: ['size06', 'left']
}, {
text: parseFloat(item.price).toLocaleString(locale, locale.currency),
style: ['size06', 'right']
}, {
text: parseFloat(item.priceTotal).toLocaleString(locale, locale.currency),
style: ['size06', 'right']
}];
});
tbody = tbody.length > 0 ? tbody : [
[{
text: "tidak ada barang",
style: ['size06', 'center'],
colSpan: 8
}, "", "", "", "", "", "", ""]
];
var table = [{
table: {
widths: ['12%', '12%', '10%', '25%', '7%', '7%', '12%', '15%'],
headerRows: 1,
body: [].concat([thead], tbody)
}
}];
var unitK1 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2A");
var unitK2 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2B");
var unitK3 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2C");
var unitK4 = sumByUnit.find((item) => item.unit.toUpperCase() == "C1A");
var unit2D = sumByUnit.find((item) => item.unit.toUpperCase() == "C1B");
var sum = sumByUnit.map(item => item.priceTotal)
.reduce(function (prev, curr, index, arr) {
return prev + curr;
}, 0);
var sumKoreksi = items.map(item => item.correction)
.reduce(function (prev, curr, index, arr) {
return prev + curr;
}, 0);
var sumByCurrency = items.map(item => item.priceTotal * item.currRate)
.reduce(function (prev, curr, index, arr) {
return prev + curr;
}, 0);
var incomeTaxTotal = useIncomeTax ? sumByCurrency * 0.1 : 0;
var vatTotal = useVat ? sumByCurrency * vatRate / 100 : 0;
var sumTotal = sumByCurrency - vatTotal + incomeTaxTotal + sumKoreksi;
var subFooter = [
{
text: '\n',
style: ['size06']
},
{
columns: [
{
stack: [
{
columns: [
{
width: '25%',
text: 'Total K1 (2A)'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: unitK1 ? parseFloat(unitK1.priceTotal).toLocaleString(locale, locale.currency) : ""
}
]
},
{
columns: [
{
width: '25%',
text: 'Total K2 (2B)'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: unitK2 ? parseFloat(unitK2.priceTotal).toLocaleString(locale, locale.currency) : ""
}
]
},
{
columns: [
{
width: '25%',
text: 'Total K3 (2C)'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: unitK3 ? parseFloat(unitK3.priceTotal).toLocaleString(locale, locale.currency) : ""
}
]
},
{
columns: [
{
width: '25%',
text: 'Total K4 (1)'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: unitK4 ? parseFloat(unitK4.priceTotal).toLocaleString(locale, locale.currency) : ""
}
]
},
{
columns: [
{
width: '25%',
text: 'Total 2D'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: unit2D ? parseFloat(unit2D.priceTotal).toLocaleString(locale, locale.currency) : ""
}
]
},
]
},
{
stack: [
{
columns: [
{
width: '45%',
text: 'Total Harga Pokok (DPP)'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: parseFloat(sum).toLocaleString(locale, locale.currency)
}
]
},
{
columns: [
{
width: '45%',
text: 'Mata Uang'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: data.currency.code
}
]
},
{
columns: [
{
width: '45%',
text: 'Total Harga Pokok (Rp)'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: parseFloat(sum * data.currency.rate).toLocaleString(locale, locale.currency)
}
]
},
{
columns: [
{
width: '45%',
text: 'Total Nota Koreksi'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: parseFloat(sumKoreksi).toLocaleString(locale, locale.currency)
}
]
},
{
columns: [
{
width: '45%',
text: 'Total Nota PPN'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: parseFloat(incomeTaxTotal).toLocaleString(locale, locale.currency)
}
]
},
{
columns: [
{
width: '45%',
text: 'Total Nota PPH'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: parseFloat(vatTotal).toLocaleString(locale, locale.currency)
}
]
},
{
columns: [
{
width: '45%',
text: 'Total yang harus dibayar'
},
{
width: '2%',
text: ':'
},
{
width: '*',
text: parseFloat(sumTotal).toLocaleString(locale, locale.currency)
}
]
},
]
}
],
style: ['size07']
}];
var footer = ['\n\n', {
alignment: "center",
table: {
widths: ['33%', '33%', '33%'],
body: [
[
{
text: 'Administrasi',
style: ['size06', 'bold', 'center']
}, {
text: 'Staff Pembelian',
style: ['size06', 'bold', 'center']
}, {
text: 'Verifikasi',
style: ['size06', 'bold', 'center']
}
],
[
{
stack: ['\n\n\n\n',
{
text: '(Nama & Tanggal)',
style: ['size06', 'center']
}
]
}, {
stack: ['\n\n\n\n',
{
text: '(Nama & Tanggal)',
style: ['size06', 'center']
}
]
}, {
stack: ['\n\n\n\n',
{
text: '(Nama & Tanggal)',
style: ['size06', 'center']
}
]
}
]
]
}
}];
var dd = {
pageSize: 'A5',
pageOrientation: 'portrait',
pageMargins: 20,
content: [].concat(header, subHeader, table, subFooter, footer),
styles: {
size06: {
fontSize: 6
},
size07: {
fontSize: 7
},
size08: {
fontSize: 8
},
size09: {
fontSize: 9
},
size10: {
fontSize: 10
},
bold: {
bold: true
},
center: {
alignment: 'center'
},
left: {
alignment: 'left'
},
right: {
alignment: 'right'
},
justify: {
alignment: 'justify'
}
}
};
return dd;
}; | indriHutabalian/dl-module | src/pdf/definitions/garment-intern-note.js | JavaScript | mit | 21,593 |
//
// StoreAppleReceiptParser.hpp
// Pods
//
// Created by eps on 7/3/20.
//
#ifndef EE_X_STORE_APPLE_RECEIPT_PARSER_HPP
#define EE_X_STORE_APPLE_RECEIPT_PARSER_HPP
#include <string>
#include "ee/store/StoreFwd.hpp"
namespace ee {
namespace store {
class AppleReceiptParser {
public:
AppleReceiptParser();
std::shared_ptr<AppleReceipt> parse(const std::string& receiptData);
private:
IMessageBridge& bridge_;
};
} // namespace store
} // namespace ee
#endif /* EE_X_STORE_APPLE_RECEIPT_PARSER_HPP */
| Senspark/ee-x | src/cpp/ee/store/private/StoreAppleReceiptParser.hpp | C++ | mit | 522 |
const multiples =
'(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)'
const here = 'fraction-tagger'
// plural-ordinals like 'hundredths' are already tagged as Fraction by compromise
const tagFractions = function (doc) {
// hundred
doc.match(multiples).tag('#Multiple', here)
// half a penny
doc.match('[(half|quarter)] of? (a|an)', 0).tag('Fraction', 'millionth')
// nearly half
doc.match('#Adverb [half]', 0).tag('Fraction', 'nearly-half')
// half the
doc.match('[half] the', 0).tag('Fraction', 'half-the')
// two-halves
doc.match('#Value (halves|halfs|quarters)').tag('Fraction', 'two-halves')
// ---ordinals as fractions---
// a fifth
doc.match('a #Ordinal').tag('Fraction', 'a-quarter')
// seven fifths
doc.match('(#Fraction && /s$/)').lookBefore('#Cardinal+$').tag('Fraction')
// one third of ..
doc.match('[#Cardinal+ #Ordinal] of .', 0).tag('Fraction', 'ordinal-of')
// 100th of
doc.match('[(#NumericValue && #Ordinal)] of .', 0).tag('Fraction', 'num-ordinal-of')
// a twenty fifth
doc.match('(a|one) #Cardinal?+ #Ordinal').tag('Fraction', 'a-ordinal')
// doc.match('(a|one) [#Ordinal]', 0).tag('Fraction', 'a-ordinal')
// values.if('#Ordinal$').tag('Fraction', '4-fifths')
// seven quarters
// values.tag('Fraction', '4-quarters')
// doc.match('(#Value && !#Ordinal)+ (#Ordinal|#Fraction)').tag('Fraction', '4-fifths')
// 12 and seven fifths
// doc.match('#Value+ and #Value+ (#Ordinal|half|quarter|#Fraction)').tag('Fraction', 'val-and-ord')
// fixups
// doc.match('#Cardinal+? (second|seconds)').unTag('Fraction', '3 seconds')
// doc.match('#Ordinal (half|quarter)').unTag('Fraction', '2nd quarter')
// doc.match('#Ordinal #Ordinal+').unTag('Fraction')
// doc.match('[#Cardinal+? (second|seconds)] of (a|an)', 0).tag('Fraction', here)
// doc.match(multiples).tag('#Multiple', here)
// // '3 out of 5'
doc.match('#Cardinal+ out? of every? #Cardinal').tag('Fraction', here)
// // one and a half
// doc.match('#Cardinal and a (#Fraction && #Value)').tag('Fraction', here)
// fraction - 'a third of a slice'
// TODO:fixme
// m = doc.match(`[(#Cardinal|a) ${ordinals}] of (a|an|the)`, 0).tag('Fraction', 'ord-of')
// tag 'thirds' as a ordinal
// m.match('.$').tag('Ordinal', 'plural-ordinal')
return doc
}
module.exports = tagFractions
| nlp-compromise/nlp_compromise | plugins/numbers/src/tagger/fractions.js | JavaScript | mit | 2,380 |
window._skel_config = {
prefix: 'css/style',
preloadStyleSheets: true,
resetCSS: true,
boxModel: 'border',
grid: { gutters: 30 },
breakpoints: {
wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } },
narrow: { range: '481-1199', containers: 960 },
mobile: { range: '-480', containers: 'fluid', lockViewport: true, grid: { collapse: true } }
}
};
$(document).ready(function () {
$("#calculate").click(function () {
var opOne = $("#opOneID").val();
var opTwo = $("#opTwoID").val();
var selected = $('#mathFunction :selected').val();
if (opOne.length != 0) {
$("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page.
}
else if (opTwo.length != 0) {
$("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page.
}
});
$("#clear").click(function () {
$("#opOneID").val('');
$("#opTwoID").val('');
$("#resultID").val('');
});
$("#pnlRemove").click(function () {
/* this function remove the fron panelof the cube so you can see inside and changes the bottom image which is the manchester United chrest with the image that ]
was the front panel image] this only shows the panels being changed by using code*/
var imageName = 'img/v8liv.PNG';
var changepnl = $('#btmpnl');
var pnlID = $('#v8front');
$(pnlID).hide(); // hide the front panel
$('#btmpnl').attr('src', imageName); // change the bottom image to v8rear.PNG
});
$('#mathFunction :selected').val();
$('#mathFunction').change(function () {
/* this fucntion calls the calucate funtion with the number to be converted with the conversion type which comes from the select tag, eg pk is pounds to kilo's
this function fires when the select dropdown box changes */
var opOne = $("#opOneID").val();
var opTwo = $("#opTwoID").val();
var selected = $('#mathFunction :selected').val();
// console.log($('#conversion :selected').val()); //write it out to the console to verify what was
$("#resultID").val(process(selected, opOne,opTwo)); // puts the convertion into the correct dom element on the page.
}).change();
});
function process(selected, opOne,opTwo) {
switch (selected) {
case "+":
return Calc.AddNo(opOne,opTwo);
break;
case "-":
return Calc.SubNo(opOne, opTwo);
break;
case "/":
return Calc.DivideNo(opOne, opTwo);
break;
case "*":
return Calc.MultplyNo(opOne, opTwo);
break;
default:
return "Error ! ";
// code to be executed if n is different from case 1 and 2
}
} | akabob/ARIA_CA2_Code | js/sk1.js | JavaScript | mit | 3,079 |
(function(app, undefined) {
'use strict';
if(!app) throw new Error('Application "app" namespace not found.');
//----------------------------------------------------------------------------
console.log( 'hello world' );
console.log( 'Application Running...' );
//----------------------------------------------------------------------------
// @begin: renders
app.render.jquery();
app.render.vanilla();
// @end: renders
//----------------------------------------------------------------------------
// @begin: to_jquery
app.to_jquery.run();
// @end: to_jquery
//----------------------------------------------------------------------------
// @begin: mustache
app.menu.render();
app.menu.option.reset();
// @begin: mustache
//----------------------------------------------------------------------------
})(window.app);
| soudev/requirejs-steps | src/01/scripts/app.js | JavaScript | mit | 867 |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KUI.Controls
{
public class FlatAccentButton : FlatButton
{
protected override void OnPaintBackground(PaintEventArgs pevent)
{
pevent.Graphics.FillRectangle(
MouseOver ? Theme.ForeBrush : Theme.AccentBrush, ClientRectangle);
}
public override void DrawShadow(Graphics g)
{
if (HasShadow)
{
for (int i = 0; i < ShadowLevel; i++)
{
g.DrawRectangle(
new Pen(Theme.AccentColor.Shade(Theme.ShadowSize, i)),
ShadeRect(i));
}
}
}
}
}
| TheKronks/KUI | KUI/Controls/FlatAccentButton.cs | C# | mit | 848 |
using MortgageCalc.Models;
using System;
using System.Collections.Generic;
namespace MortgageCalc.Calculators
{
public class InterestOnlyScheduleBuilder
{
private RateCalc _calc = new RateCalc(6); // initialize with 6 decimal places
private decimal _monthlyPayment;
private decimal _principal;
private decimal _rate;
private int _term;
public InterestOnlyScheduleBuilder(decimal principal, decimal rate, int term)
{
this._principal = principal;
this._rate = rate;
this._term = term;
this._monthlyPayment = this._calc.Interest(principal, rate);
}
public Schedule Schedule()
{
return new Schedule
{
MonthlyPayment = Math.Round(this._monthlyPayment, 2),
CostOfCredit = Math.Round(this._monthlyPayment * this._term, 2)
};
}
}
}
| shanegray/mortgage-calc | Calculators/InterestOnlyScheduleBuilder.cs | C# | mit | 947 |
import Ember from 'ember';
import CheckboxMixin from '../mixins/checkbox-mixin';
export default Ember.Component.extend(CheckboxMixin, {
type: 'checkbox',
checked: false,
onChange: function() {
this.set('checked', this.$('input').prop('checked'));
this.sendAction("action", {
checked: this.get('checked'),
value: this.get('value')
});
}
});
| CrshOverride/Semantic-UI-Ember | addon/components/ui-checkbox.js | JavaScript | mit | 374 |
@ParametersAreNonnullByDefault
package org.zalando.problem.spring.web.advice;
import javax.annotation.ParametersAreNonnullByDefault;
| zalando/problem-spring-web | problem-spring-web/src/main/java/org/zalando/problem/spring/web/advice/package-info.java | Java | mit | 135 |
"""
Django settings for ross project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'jtn=n8&nq9jgir8_z1ck40^c1s22d%=)z5qsm*q(bku*_=^sg&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ross.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ross.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
| rossplt/ross-django-utils | ross/settings.py | Python | mit | 3,090 |
////////////////////////////////////////////////////////////////////////////////
//worldgenerator.cs
//Created on: 2015-8-21, 18:18
//
//Project VoxelEngine
//Copyright C bajsko 2015. All rights Reserved.
////////////////////////////////////////////////////////////////////////////////
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VoxelEngine.Game.Blocks;
using VoxelEngine.GameConsole;
using VoxelEngine.Utility;
namespace VoxelEngine.Game
{
public class WorldGenerator
{
private World mWorldRef;
public WorldGenerator(World worldRef)
{
this.mWorldRef = worldRef;
}
public Chunk GenerateChunk(int xp, int yp, int zp)
{
Chunk chunk = null;
chunk = new Chunk(new Vector3(xp, yp, zp));
Vector3 chunkPosBlock = new Vector3(xp, yp, zp) * Chunk.CHUNK_SIZE;
int treeDensity = 2;
float stoneBaseHeight = 0;
float stoneBaseNoise = 0.05f;
float stoneBaseNoiseHeight = 4;
float stoneMountainHeight = 48;
float stoneMountainFrequency = 0.008f;
float stoneMinHeight = -12;
float dirtBaseHeight = 1;
float dirtNoise = 0.04f;
float dirtNoiseHeight = 3;
for (int x = (int)chunkPosBlock.X - 5; x < chunkPosBlock.X + Chunk.CHUNK_SIZE + 5; x++)
{
for(int z = (int)chunkPosBlock.Z - 5; z < chunkPosBlock.Z + Chunk.CHUNK_SIZE + 5; z++)
{
int stoneHeight = (int)Math.Floor(stoneBaseHeight);
stoneHeight += (int)Math.Floor(GetNoiseValue(x, 0, z, stoneMountainFrequency, (int)(stoneMountainHeight)));
if (stoneHeight < stoneMinHeight)
stoneHeight = (int)Math.Floor((stoneMinHeight));
stoneHeight += (int)Math.Floor(GetNoiseValue(x, 0, z, stoneBaseNoise, (int)(stoneBaseNoiseHeight)));
int dirtHeight = stoneHeight + (int)(dirtBaseHeight);
dirtHeight += (int)Math.Floor(GetNoiseValue(x, 100, z, dirtNoise, (int)(dirtNoiseHeight)));
for (int y = (int)chunkPosBlock.Y - 10; y < chunkPosBlock.Y+Chunk.CHUNK_SIZE + 10; y++)
{
//from world block space to local chunk space
int xfactor = (int)chunkPosBlock.X;
int yfactor = (int)chunkPosBlock.Y;
int zfactor = (int)chunkPosBlock.Z;
if (y <= stoneHeight)
chunk.SetBlock(x-xfactor, y-yfactor, z-zfactor, new Block(BlockType.Stone));
else if (y <= dirtHeight)
{
chunk.SetBlock(x - xfactor, y - yfactor, z - zfactor, new Block(BlockType.Grass));
if (y == dirtHeight && GetNoiseValue(x, 0, z, 0.2f, 100) < treeDensity)
{
//CreateTree(x, y, z);
}
}
}
}
}
//chunk.ApplySunlight();
return chunk;
}
public Chunk GenerateChunk(Vector3 position)
{
return GenerateChunk((int)position.X, (int)position.Y, (int)position.Z);
}
private void CreateTree(int x, int y, int z)
{
//TODO:
//major performance hit here...
//fix..
Random random = new Random();
int trunkLength = random.Next(5, 10);
for(int yy = y; yy < y + trunkLength; yy++)
{
mWorldRef.SetBlock(x, yy+1, z, new Block(BlockType.Log));
}
int leavesStart = y+trunkLength;
for(int xi = -3; xi <= 3; xi++)
{
for(int yi = 0; yi <= 1; yi++)
{
for(int zi = -3; zi <= 3; zi++)
{
mWorldRef.SetBlock(x + xi, leavesStart + yi, z + zi, new Block(BlockType.Leaves));
}
}
}
for(int xi = -2; xi <= 2; xi++)
{
for(int zi = -2; zi <= 2; zi++)
{
mWorldRef.SetBlock(x + xi, leavesStart + 2, z + zi, new Block(BlockType.Leaves));
}
}
mWorldRef.SetBlock(x - 1, leavesStart + 3, z, new Block(BlockType.Leaves));
mWorldRef.SetBlock(x + 1, leavesStart + 3, z, new Block(BlockType.Leaves));
mWorldRef.SetBlock(x, leavesStart + 3, z - 1, new Block(BlockType.Leaves));
mWorldRef.SetBlock(x, leavesStart + 3, z + 1, new Block(BlockType.Leaves));
}
private int GetNoiseValue(int x, int z, float scale, int max)
{
int value = (int)((Noise.Generate(x*scale, 0, z*scale)) * (max / 2f));
return value;
}
private float GetNoiseValue(int x, int y, int z, float scale, int max)
{
int value = (int)Math.Floor((Noise.Generate(x * scale, y * scale, z * scale) + 1f) * (max / 2f));
return value;
}
}
}
| bajsko/VoxelEngine | Game/WorldGenerator.cs | C# | mit | 5,364 |
"use strict"
var express = require('express');
var app = express();
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
var router = express.Router();
router.get('/accidents', function(req, res) {
var query = {
index: 'wildmap',
type: 'accidents',
size: 10000,
body: {
query: {
bool: {
must: [
{
match_all: {}
}
]
}
}
}
}
var animal_type = req.query.animal_type;
var day_type = req.query.day_type;
var season = req.query.season;
if(animal_type && animal_type!="all"){
query.body.query.bool.must.push({
term: {
"accidents.pin.animal_type": animal_type
}
});
}
if(day_type && day_type!="all"){
query.body.query.bool.must.push({
term: {
"accidents.pin.day_type": day_type
}
});
}
if(season && season!="all"){
query.body.query.bool.must.push({
term: {
"accidents.pin.season": season
}
});
}
console.log(query);
client.search(query).then(function (resp) {
console.log(resp.hits.hits);
var response = resp.hits.hits.map(function(e){
return e._source.pin;
})
res.send(response);
}, function (err) {
console.log(err.message);
res.status(500).end();
});
});
app.use('/api', router);
var port = process.env.PORT || 8080;
app.listen(port);
console.log("Backend is running on port " + port); | Jugendhackt/wildmap | backend/index.js | JavaScript | mit | 1,488 |
var generatetask = require('../source/ajgenesis/tasks/generate'),
createtask = require('../create'),
path = require('path'),
fs = require('fs'),
ajgenesis = require('ajgenesis');
exports['generate'] = function (test) {
test.async();
var cwd = process.cwd();
process.chdir('test');
var model = ajgenesis.loadModel();
test.ok(model.entities);
test.ok(Array.isArray(model.entities));
test.equal(model.entities.length, 4);
if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db')))
removeDirSync('build');
ajgenesis.createDirectory('build');
process.chdir('build');
generatetask(model, [], ajgenesis, function (err, result) {
test.equal(err, null);
test.equal(result, null);
test.ok(fs.existsSync('app.rb'));
test.ok(fs.existsSync('public'));
//test.ok(fs.existsSync(path.join('views', 'index.erb')));
test.ok(fs.existsSync('views'));
test.ok(fs.existsSync(path.join('views', 'customerlist.erb')));
test.ok(fs.existsSync(path.join('views', 'customernew.erb')));
test.ok(fs.existsSync(path.join('views', 'customerview.erb')));
test.ok(fs.existsSync(path.join('views', 'customeredit.erb')));
test.ok(fs.existsSync(path.join('views', 'supplierlist.erb')));
test.ok(fs.existsSync(path.join('views', 'suppliernew.erb')));
test.ok(fs.existsSync(path.join('views', 'supplierview.erb')));
test.ok(fs.existsSync(path.join('views', 'supplieredit.erb')));
test.ok(fs.existsSync(path.join('views', 'departmentlist.erb')));
test.ok(fs.existsSync(path.join('views', 'departmentnew.erb')));
test.ok(fs.existsSync(path.join('views', 'departmentview.erb')));
test.ok(fs.existsSync(path.join('views', 'departmentedit.erb')));
test.ok(fs.existsSync(path.join('views', 'employeelist.erb')));
test.ok(fs.existsSync(path.join('views', 'employeenew.erb')));
test.ok(fs.existsSync(path.join('views', 'employeeview.erb')));
test.ok(fs.existsSync(path.join('views', 'employeeedit.erb')));
test.ok(fs.existsSync(path.join('entities')));
test.ok(fs.existsSync(path.join('entities', 'customer.rb')));
test.ok(fs.existsSync(path.join('entities', 'supplier.rb')));
test.ok(fs.existsSync(path.join('entities', 'department.rb')));
test.ok(fs.existsSync(path.join('entities', 'employee.rb')));
test.ok(fs.existsSync('controllers'));
test.ok(fs.existsSync(path.join('controllers', 'customer.rb')));
test.ok(fs.existsSync(path.join('controllers', 'supplier.rb')));
test.ok(fs.existsSync(path.join('controllers', 'department.rb')));
test.ok(fs.existsSync(path.join('controllers', 'employee.rb')));
process.chdir(cwd);
test.done();
});
}
exports['generate in directory'] = function (test) {
test.async();
var cwd = process.cwd();
process.chdir('test');
var model = ajgenesis.loadModel();
test.ok(model.entities);
test.ok(Array.isArray(model.entities));
test.equal(model.entities.length, 4);
model.builddir = 'build';
if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db')))
removeDirSync('build');
generatetask(model, [], ajgenesis, function (err, result) {
test.equal(err, null);
test.equal(result, null);
test.ok(fs.existsSync(path.join('build', 'app.rb')));
test.ok(fs.existsSync(path.join('build', 'public')));
test.ok(fs.existsSync(path.join('build', 'views')));
//test.ok(fs.existsSync(path.join('views', 'index.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'customerlist.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'customernew.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'customerview.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'customeredit.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'supplierlist.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'suppliernew.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'supplierview.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'supplieredit.erb')));
test.ok(fs.existsSync(path.join('build', 'entities')));
test.ok(fs.existsSync(path.join('build', 'entities', 'customer.rb')));
test.ok(fs.existsSync(path.join('build', 'entities', 'supplier.rb')));
test.ok(fs.existsSync(path.join('build', 'entities', 'department.rb')));
test.ok(fs.existsSync(path.join('build', 'entities', 'employee.rb')));
test.ok(fs.existsSync(path.join('build', 'controllers')));
test.ok(fs.existsSync(path.join('build', 'controllers', 'customer.rb')));
test.ok(fs.existsSync(path.join('build', 'controllers', 'supplier.rb')));
test.ok(fs.existsSync(path.join('build', 'controllers', 'department.rb')));
test.ok(fs.existsSync(path.join('build', 'controllers', 'employee.rb')));
process.chdir(cwd);
test.done();
});
}
exports['create and generate'] = function (test) {
test.async();
var cwd = process.cwd();
process.chdir('test');
var model = ajgenesis.loadModel();
test.ok(model.entities);
test.ok(Array.isArray(model.entities));
test.equal(model.entities.length, 4);
if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db')))
removeDirSync('build');
createtask(null, ['build'], ajgenesis, function (err, result) {
test.equal(err, null);
test.ok(fs.existsSync('build'));
model.builddir = 'build';
generatetask(model, [], ajgenesis, function (err, result) {
test.equal(err, null);
test.equal(result, null);
test.ok(fs.existsSync(path.join('build', 'app.rb')));
test.ok(fs.existsSync(path.join('build', 'public')));
test.ok(fs.existsSync(path.join('build', 'views')));
test.ok(fs.existsSync(path.join('build', 'views', 'index.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'customerlist.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'customernew.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'customerview.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'customeredit.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'supplierlist.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'suppliernew.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'supplierview.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'supplieredit.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'departmentlist.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'departmentnew.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'departmentview.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'departmentedit.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'employeelist.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'employeenew.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'employeeview.erb')));
test.ok(fs.existsSync(path.join('build', 'views', 'employeeedit.erb')));
test.ok(fs.existsSync(path.join('build', 'entities')));
test.ok(fs.existsSync(path.join('build', 'entities', 'customer.rb')));
test.ok(fs.existsSync(path.join('build', 'entities', 'supplier.rb')));
test.ok(fs.existsSync(path.join('build', 'entities', 'department.rb')));
test.ok(fs.existsSync(path.join('build', 'entities', 'employee.rb')));
test.ok(fs.existsSync(path.join('build', 'controllers')));
test.ok(fs.existsSync(path.join('build', 'controllers', 'customer.rb')));
test.ok(fs.existsSync(path.join('build', 'controllers', 'supplier.rb')));
test.ok(fs.existsSync(path.join('build', 'controllers', 'department.rb')));
test.ok(fs.existsSync(path.join('build', 'controllers', 'employee.rb')));
process.chdir(cwd);
test.done();
});
});
}
function removeDirSync(dirname) {
var filenames = fs.readdirSync(dirname);
filenames.forEach(function (filename) {
filename = path.join(dirname, filename);
if (isDirectory(filename))
removeDirSync(filename);
else
removeFileSync(filename);
});
fs.rmdirSync(dirname);
}
function removeFileSync(filename) {
fs.unlinkSync(filename);
}
function isDirectory(filename)
{
try {
var stats = fs.lstatSync(filename);
return stats.isDirectory();
}
catch (err)
{
return false;
}
}
| ajlopez/AjGenesisNode-Sinatra | test/generate.js | JavaScript | mit | 9,507 |
package com.virtualfactory.screen.layer.components;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.controls.ButtonClickedEvent;
import de.lessvoid.nifty.controls.Controller;
import de.lessvoid.nifty.controls.window.WindowControl;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.elements.render.ImageRenderer;
import de.lessvoid.nifty.input.NiftyInputEvent;
import de.lessvoid.nifty.render.NiftyImage;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.tools.SizeValue;
import de.lessvoid.xml.xpp3.Attributes;
import com.virtualfactory.engine.GameEngine;
import com.virtualfactory.utils.CommonBuilders;
import com.virtualfactory.utils.Pair;
import java.util.Properties;
/**
*
* @author David
*/
public class FlowChartScreenController implements Controller {
private Nifty nifty;
private Screen screen;
private WindowControl winControls;
private boolean isVisible;
private GameEngine gameEngine;
final CommonBuilders common = new CommonBuilders();
private NiftyImage flowChartImage;
@Override
public void bind(
final Nifty nifty,
final Screen screen,
final Element element,
final Properties parameter,
final Attributes controlDefinitionAttributes) {
this.nifty = nifty;
this.screen = screen;
this.winControls = screen.findNiftyControl("winFlowChartControl", WindowControl.class);
Attributes x = new Attributes();
x.set("hideOnClose", "true");
this.winControls.bind(nifty, screen, winControls.getElement(), null, x);
isVisible = false;
}
public boolean isIsVisible() {
return isVisible;
}
public void setIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
@Override
public void init(Properties parameter, Attributes controlDefinitionAttributes) {
}
@Override
public void onStartScreen() {
}
@Override
public void onFocus(boolean getFocus) {
}
@Override
public boolean inputEvent(final NiftyInputEvent inputEvent) {
return false;
}
public void loadWindowControl(GameEngine game,int index, Pair<Integer,Integer> position){
this.gameEngine = game;
if (index == -1){
winControls.getElement().setVisible(false);
winControls.getContent().hide();
isVisible = false;
}else{
winControls.getElement().setVisible(true);
winControls.getContent().show();
isVisible = true;
if (position != null){
if (winControls.getWidth() + position.getFirst() > gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getWidth())
position.setFirst(gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getWidth() - winControls.getWidth());
if (winControls.getHeight() + position.getSecond() > gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getHeight())
position.setSecond(gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getHeight() - winControls.getHeight());
winControls.getElement().setConstraintX(new SizeValue(position.getFirst() + "px"));
winControls.getElement().setConstraintY(new SizeValue(position.getSecond() + "px"));
winControls.getElement().getParent().layoutElements();
}
winControls.getElement().setConstraintX(null);
winControls.getElement().setConstraintY(null);
}
loadValues(index);
}
private void loadValues(int index){
if (index == -1){
flowChartImage = nifty.createImage("Models/Flows/none.png", false);
screen.findElementByName("imageFlowOfActivities").getRenderer(ImageRenderer.class).setImage(flowChartImage);
}else{
flowChartImage = nifty.createImage("Models/Flows/" + gameEngine.getGameData().getCurrentGame().getFlowImage(), false);
screen.findElementByName("imageFlowOfActivities").getRenderer(ImageRenderer.class).setImage(flowChartImage);
}
}
@NiftyEventSubscriber(id="closeFlowChart")
public void onCloseFlowChartButtonClicked(final String id, final ButtonClickedEvent event) {
gameEngine.updateLastActivitySystemTime();
loadWindowControl(gameEngine, -1, null);
}
}
| uprm-gaming/virtual-factory | src/com/virtualfactory/screen/layer/components/FlowChartScreenController.java | Java | mit | 4,455 |
const S$ = require('S$');
function loadSrc(obj, src) {
throw src;
}
const cookies = S$.symbol('Cookie', '');
const world = {};
if (cookies) {
if (/iPhone/.exec(cookies)) {
loadSrc(world, '/resources/' + cookies);
}
loadSrc(world, '/resources/unknown');
} else {
loadSrc(world, '/resources/fresh');
}
| ExpoSEJS/ExpoSE | tests/regex/cookies/t1.js | JavaScript | mit | 332 |
module.exports = function (seneca, util) {
//var Joi = util.Joi
}
| senecajs/seneca-dynamo-store | dynamo-store-doc.js | JavaScript | mit | 68 |
package Digivolver;
public class Digivolution{
private Digimon digimon;
private int minDp = 0;
private int maxDp = 0;
public boolean isWithinDp(int minDp, int maxDp){
return this.minDp<=maxDp && this.maxDp>=minDp;
}
public Digivolution(Digimon digimon, int minDp, int maxDp) {
this.digimon = digimon;
this.minDp = minDp;
this.maxDp = maxDp;
}
public Digimon getDigimon() {
return digimon;
}
public void setDigimon(Digimon digimon) {
this.digimon = digimon;
}
public int getMinDp(){
return minDp;
}
public int getMaxDp(){
return maxDp;
}
}
| mp-pinheiro/DW2Digivolver | src/Digivolver/Digivolution.java | Java | mit | 580 |
import re
import hashlib
FNAME_MATCH = re.compile(r'/([^/]+)$') # From the last slash to the end of the string
PREFIX = re.compile(r'([^:]+://)(/)?(.+)') # Check for a prefix like data://
def getParentAndBase(path):
match = PREFIX.match(path)
if match is None:
if path.endswith('/'):
stripped_path = path[:-1]
else:
stripped_path = path
base = FNAME_MATCH.search(stripped_path)
if base is None:
raise ValueError('Invalid path')
parent = FNAME_MATCH.sub('', stripped_path)
return parent, base.group(1)
else:
prefix, leading_slash, uri = match.groups()
parts = uri.split('/')
parent_path = '/'.join(parts[:-1])
if leading_slash is not None:
parent_path = '{prefix}/{uri}'.format(prefix=prefix, uri='/'.join(parts[:-1]))
else:
parent_path = '{prefix}{uri}'.format(prefix=prefix, uri='/'.join(parts[:-1]))
return parent_path, parts[-1]
def pathJoin(parent, base):
if parent.endswith('/'):
return parent + base
return parent + '/' + base
def md5_for_file(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return str(hash_md5.hexdigest())
def md5_for_str(content):
hash_md5 = hashlib.md5()
hash_md5.update(content.encode())
return str(hash_md5.hexdigest())
| algorithmiaio/algorithmia-python | Algorithmia/util.py | Python | mit | 1,473 |
/**
* @file query.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2021 TileDB, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* This file implements class Query.
*/
#include "tiledb/sm/query/query.h"
#include "tiledb/common/heap_memory.h"
#include "tiledb/common/logger.h"
#include "tiledb/common/memory.h"
#include "tiledb/sm/array/array.h"
#include "tiledb/sm/enums/query_status.h"
#include "tiledb/sm/enums/query_type.h"
#include "tiledb/sm/fragment/fragment_metadata.h"
#include "tiledb/sm/misc/parse_argument.h"
#include "tiledb/sm/query/dense_reader.h"
#include "tiledb/sm/query/global_order_writer.h"
#include "tiledb/sm/query/ordered_writer.h"
#include "tiledb/sm/query/query_condition.h"
#include "tiledb/sm/query/reader.h"
#include "tiledb/sm/query/sparse_global_order_reader.h"
#include "tiledb/sm/query/sparse_unordered_with_dups_reader.h"
#include "tiledb/sm/query/unordered_writer.h"
#include "tiledb/sm/rest/rest_client.h"
#include "tiledb/sm/storage_manager/storage_manager.h"
#include "tiledb/sm/tile/writer_tile.h"
#include <cassert>
#include <iostream>
#include <sstream>
using namespace tiledb::common;
using namespace tiledb::sm::stats;
namespace tiledb {
namespace sm {
/* ****************************** */
/* CONSTRUCTORS & DESTRUCTORS */
/* ****************************** */
Query::Query(StorageManager* storage_manager, Array* array, URI fragment_uri)
: array_(array)
, array_schema_(array->array_schema_latest_ptr())
, layout_(Layout::ROW_MAJOR)
, storage_manager_(storage_manager)
, stats_(storage_manager_->stats()->create_child("Query"))
, logger_(storage_manager->logger()->clone("Query", ++logger_id_))
, has_coords_buffer_(false)
, has_zipped_coords_buffer_(false)
, coord_buffer_is_set_(false)
, coord_data_buffer_is_set_(false)
, coord_offsets_buffer_is_set_(false)
, data_buffer_name_("")
, offsets_buffer_name_("")
, disable_check_global_order_(false)
, fragment_uri_(fragment_uri) {
assert(array->is_open());
auto st = array->get_query_type(&type_);
assert(st.ok());
if (type_ == QueryType::WRITE) {
subarray_ = Subarray(array, stats_, logger_);
} else {
subarray_ = Subarray(array, Layout::ROW_MAJOR, stats_, logger_);
}
fragment_metadata_ = array->fragment_metadata();
coords_info_.coords_buffer_ = nullptr;
coords_info_.coords_buffer_size_ = nullptr;
coords_info_.coords_num_ = 0;
coords_info_.has_coords_ = false;
callback_ = nullptr;
callback_data_ = nullptr;
status_ = QueryStatus::UNINITIALIZED;
if (storage_manager != nullptr)
config_ = storage_manager->config();
// Set initial subarray configuration
subarray_.set_config(config_);
rest_scratch_ = make_shared<Buffer>(HERE());
}
Query::~Query() {
bool found = false;
bool use_malloc_trim = false;
const Status& st =
config_.get<bool>("sm.mem.malloc_trim", &use_malloc_trim, &found);
if (st.ok() && found && use_malloc_trim) {
tdb_malloc_trim();
}
};
/* ****************************** */
/* API */
/* ****************************** */
Status Query::add_range(
unsigned dim_idx, const void* start, const void* end, const void* stride) {
if (dim_idx >= array_schema_->dim_num())
return logger_->status(
Status_QueryError("Cannot add range; Invalid dimension index"));
if (start == nullptr || end == nullptr)
return logger_->status(
Status_QueryError("Cannot add range; Invalid range"));
if (stride != nullptr)
return logger_->status(Status_QueryError(
"Cannot add range; Setting range stride is currently unsupported"));
if (array_schema_->domain()->dimension(dim_idx)->var_size())
return logger_->status(
Status_QueryError("Cannot add range; Range must be fixed-sized"));
// Prepare a temp range
std::vector<uint8_t> range;
auto coord_size = array_schema_->dimension(dim_idx)->coord_size();
range.resize(2 * coord_size);
std::memcpy(&range[0], start, coord_size);
std::memcpy(&range[coord_size], end, coord_size);
bool read_range_oob_error = true;
if (type_ == QueryType::READ) {
// Get read_range_oob config setting
bool found = false;
std::string read_range_oob = config_.get("sm.read_range_oob", &found);
assert(found);
if (read_range_oob != "error" && read_range_oob != "warn")
return logger_->status(Status_QueryError(
"Invalid value " + read_range_oob +
" for sm.read_range_obb. Acceptable values are 'error' or 'warn'."));
read_range_oob_error = read_range_oob == "error";
} else {
if (!array_schema_->dense())
return logger_->status(
Status_QueryError("Adding a subarray range to a write query is not "
"supported in sparse arrays"));
if (subarray_.is_set(dim_idx))
return logger_->status(
Status_QueryError("Cannot add range; Multi-range dense writes "
"are not supported"));
}
// Add range
Range r(&range[0], 2 * coord_size);
return subarray_.add_range(dim_idx, std::move(r), read_range_oob_error);
}
Status Query::add_range_var(
unsigned dim_idx,
const void* start,
uint64_t start_size,
const void* end,
uint64_t end_size) {
if (dim_idx >= array_schema_->dim_num())
return logger_->status(
Status_QueryError("Cannot add range; Invalid dimension index"));
if ((start == nullptr && start_size != 0) ||
(end == nullptr && end_size != 0))
return logger_->status(
Status_QueryError("Cannot add range; Invalid range"));
if (!array_schema_->domain()->dimension(dim_idx)->var_size())
return logger_->status(
Status_QueryError("Cannot add range; Range must be variable-sized"));
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot add range; Function applicable only to reads"));
// Get read_range_oob config setting
bool found = false;
std::string read_range_oob = config_.get("sm.read_range_oob", &found);
assert(found);
if (read_range_oob != "error" && read_range_oob != "warn")
return logger_->status(Status_QueryError(
"Invalid value " + read_range_oob +
" for sm.read_range_obb. Acceptable values are 'error' or 'warn'."));
// Add range
Range r;
r.set_range_var(start, start_size, end, end_size);
return subarray_.add_range(dim_idx, std::move(r), read_range_oob == "error");
}
Status Query::get_range_num(unsigned dim_idx, uint64_t* range_num) const {
if (type_ == QueryType::WRITE && !array_schema_->dense())
return logger_->status(
Status_QueryError("Getting the number of ranges from a write query "
"is not applicable to sparse arrays"));
return subarray_.get_range_num(dim_idx, range_num);
}
Status Query::get_range(
unsigned dim_idx,
uint64_t range_idx,
const void** start,
const void** end,
const void** stride) const {
if (type_ == QueryType::WRITE && !array_schema_->dense())
return logger_->status(
Status_QueryError("Getting a range from a write query is not "
"applicable to sparse arrays"));
*stride = nullptr;
return subarray_.get_range(dim_idx, range_idx, start, end);
}
Status Query::get_range_var_size(
unsigned dim_idx,
uint64_t range_idx,
uint64_t* start_size,
uint64_t* end_size) const {
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Getting a var range size from a write query is not applicable"));
return subarray_.get_range_var_size(dim_idx, range_idx, start_size, end_size);
;
}
Status Query::get_range_var(
unsigned dim_idx, uint64_t range_idx, void* start, void* end) const {
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Getting a var range from a write query is not applicable"));
uint64_t start_size = 0;
uint64_t end_size = 0;
subarray_.get_range_var_size(dim_idx, range_idx, &start_size, &end_size);
const void* range_start;
const void* range_end;
const void* stride;
RETURN_NOT_OK(
get_range(dim_idx, range_idx, &range_start, &range_end, &stride));
std::memcpy(start, range_start, start_size);
std::memcpy(end, range_end, end_size);
return Status::Ok();
}
Status Query::add_range_by_name(
const std::string& dim_name,
const void* start,
const void* end,
const void* stride) {
unsigned dim_idx;
RETURN_NOT_OK(
array_schema_->domain()->get_dimension_index(dim_name, &dim_idx));
return add_range(dim_idx, start, end, stride);
}
Status Query::add_range_var_by_name(
const std::string& dim_name,
const void* start,
uint64_t start_size,
const void* end,
uint64_t end_size) {
unsigned dim_idx;
RETURN_NOT_OK(
array_schema_->domain()->get_dimension_index(dim_name, &dim_idx));
return add_range_var(dim_idx, start, start_size, end, end_size);
}
Status Query::get_range_num_from_name(
const std::string& dim_name, uint64_t* range_num) const {
unsigned dim_idx;
RETURN_NOT_OK(
array_schema_->domain()->get_dimension_index(dim_name, &dim_idx));
return get_range_num(dim_idx, range_num);
}
Status Query::get_range_from_name(
const std::string& dim_name,
uint64_t range_idx,
const void** start,
const void** end,
const void** stride) const {
unsigned dim_idx;
RETURN_NOT_OK(
array_schema_->domain()->get_dimension_index(dim_name, &dim_idx));
return get_range(dim_idx, range_idx, start, end, stride);
}
Status Query::get_range_var_size_from_name(
const std::string& dim_name,
uint64_t range_idx,
uint64_t* start_size,
uint64_t* end_size) const {
unsigned dim_idx;
RETURN_NOT_OK(
array_schema_->domain()->get_dimension_index(dim_name, &dim_idx));
return get_range_var_size(dim_idx, range_idx, start_size, end_size);
}
Status Query::get_range_var_from_name(
const std::string& dim_name,
uint64_t range_idx,
void* start,
void* end) const {
unsigned dim_idx;
RETURN_NOT_OK(
array_schema_->domain()->get_dimension_index(dim_name, &dim_idx));
return get_range_var(dim_idx, range_idx, start, end);
}
Status Query::get_est_result_size(const char* name, uint64_t* size) {
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Operation currently "
"unsupported for write queries"));
if (name == nullptr)
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Name cannot be null"));
if (name == constants::coords &&
!array_schema_->domain()->all_dims_same_type())
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Not applicable to zipped "
"coordinates in arrays with heterogeneous domain"));
if (name == constants::coords && !array_schema_->domain()->all_dims_fixed())
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Not applicable to zipped "
"coordinates in arrays with domains with variable-sized dimensions"));
if (array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string(
"Cannot get estimated result size; Input attribute/dimension '") +
name + "' is nullable"));
if (array_->is_remote() && !subarray_.est_result_size_computed()) {
auto rest_client = storage_manager_->rest_client();
if (rest_client == nullptr)
return logger_->status(
Status_QueryError("Error in query estimate result size; remote "
"array with no rest client."));
RETURN_NOT_OK(
rest_client->get_query_est_result_sizes(array_->array_uri(), this));
}
return subarray_.get_est_result_size_internal(
name, size, &config_, storage_manager_->compute_tp());
}
Status Query::get_est_result_size(
const char* name, uint64_t* size_off, uint64_t* size_val) {
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Operation currently "
"unsupported for write queries"));
if (array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string(
"Cannot get estimated result size; Input attribute/dimension '") +
name + "' is nullable"));
if (array_->is_remote() && !subarray_.est_result_size_computed()) {
auto rest_client = storage_manager_->rest_client();
if (rest_client == nullptr)
return logger_->status(
Status_QueryError("Error in query estimate result size; remote "
"array with no rest client."));
RETURN_NOT_OK(
rest_client->get_query_est_result_sizes(array_->array_uri(), this));
}
return subarray_.get_est_result_size(
name, size_off, size_val, &config_, storage_manager_->compute_tp());
}
Status Query::get_est_result_size_nullable(
const char* name, uint64_t* size_val, uint64_t* size_validity) {
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Operation currently "
"unsupported for write queries"));
if (name == nullptr)
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Name cannot be null"));
if (!array_schema_->attribute(name))
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Nullable API is only"
"applicable to attributes"));
if (!array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot get estimated result size; Input attribute '") +
name + "' is not nullable"));
if (array_->is_remote() && !subarray_.est_result_size_computed()) {
auto rest_client = storage_manager_->rest_client();
if (rest_client == nullptr)
return logger_->status(
Status_QueryError("Error in query estimate result size; remote "
"array with no rest client."));
return logger_->status(
Status_QueryError("Error in query estimate result size; unimplemented "
"for nullable attributes in remote arrays."));
}
return subarray_.get_est_result_size_nullable(
name, size_val, size_validity, &config_, storage_manager_->compute_tp());
}
Status Query::get_est_result_size_nullable(
const char* name,
uint64_t* size_off,
uint64_t* size_val,
uint64_t* size_validity) {
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Operation currently "
"unsupported for write queries"));
if (!array_schema_->attribute(name))
return logger_->status(Status_QueryError(
"Cannot get estimated result size; Nullable API is only"
"applicable to attributes"));
if (!array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot get estimated result size; Input attribute '") +
name + "' is not nullable"));
if (array_->is_remote() && !subarray_.est_result_size_computed()) {
auto rest_client = storage_manager_->rest_client();
if (rest_client == nullptr)
return logger_->status(
Status_QueryError("Error in query estimate result size; remote "
"array with no rest client."));
return logger_->status(
Status_QueryError("Error in query estimate result size; unimplemented "
"for nullable attributes in remote arrays."));
}
return subarray_.get_est_result_size_nullable(
name,
size_off,
size_val,
size_validity,
&config_,
storage_manager_->compute_tp());
}
std::unordered_map<std::string, Subarray::ResultSize>
Query::get_est_result_size_map() {
return subarray_.get_est_result_size_map(
&config_, storage_manager_->compute_tp());
}
std::unordered_map<std::string, Subarray::MemorySize>
Query::get_max_mem_size_map() {
return subarray_.get_max_mem_size_map(
&config_, storage_manager_->compute_tp());
}
Status Query::get_written_fragment_num(uint32_t* num) const {
if (type_ != QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot get number of fragments; Applicable only to WRITE mode"));
*num = (uint32_t)written_fragment_info_.size();
return Status::Ok();
}
Status Query::get_written_fragment_uri(uint32_t idx, const char** uri) const {
if (type_ != QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot get fragment URI; Applicable only to WRITE mode"));
auto num = (uint32_t)written_fragment_info_.size();
if (idx >= num)
return logger_->status(
Status_QueryError("Cannot get fragment URI; Invalid fragment index"));
*uri = written_fragment_info_[idx].uri_.c_str();
return Status::Ok();
}
Status Query::get_written_fragment_timestamp_range(
uint32_t idx, uint64_t* t1, uint64_t* t2) const {
if (type_ != QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot get fragment timestamp range; Applicable only to WRITE mode"));
auto num = (uint32_t)written_fragment_info_.size();
if (idx >= num)
return logger_->status(Status_QueryError(
"Cannot get fragment timestamp range; Invalid fragment index"));
*t1 = written_fragment_info_[idx].timestamp_range_.first;
*t2 = written_fragment_info_[idx].timestamp_range_.second;
return Status::Ok();
}
const Array* Query::array() const {
return array_;
}
Array* Query::array() {
return array_;
}
const ArraySchema& Query::array_schema() const {
return *(array_schema_.get());
}
std::vector<std::string> Query::buffer_names() const {
std::vector<std::string> ret;
// Add to the buffer names the attributes, as well as the dimensions only if
// coords_buffer_ has not been set
for (const auto& it : buffers_) {
if (!array_schema_->is_dim(it.first) || (!coords_info_.coords_buffer_))
ret.push_back(it.first);
}
// Special zipped coordinates name
if (coords_info_.coords_buffer_)
ret.push_back(constants::coords);
return ret;
}
QueryBuffer Query::buffer(const std::string& name) const {
// Special zipped coordinates
if (type_ == QueryType::WRITE && name == constants::coords)
return QueryBuffer(
coords_info_.coords_buffer_,
nullptr,
coords_info_.coords_buffer_size_,
nullptr);
// Attribute or dimension
auto buf = buffers_.find(name);
if (buf != buffers_.end())
return buf->second;
// Named buffer does not exist
return QueryBuffer{};
}
Status Query::finalize() {
if (status_ == QueryStatus::UNINITIALIZED)
return Status::Ok();
if (array_->is_remote()) {
auto rest_client = storage_manager_->rest_client();
if (rest_client == nullptr)
return logger_->status(Status_QueryError(
"Error in query finalize; remote array with no rest client."));
return rest_client->finalize_query_to_rest(array_->array_uri(), this);
}
RETURN_NOT_OK(strategy_->finalize());
status_ = QueryStatus::COMPLETED;
return Status::Ok();
}
Status Query::get_buffer(
const char* name, void** buffer, uint64_t** buffer_size) const {
// Check attribute
if (name != constants::coords) {
if (array_schema_->attribute(name) == nullptr &&
array_schema_->dimension(name) == nullptr)
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; Invalid attribute/dimension name '") +
name + "'"));
}
if (array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; '") + name + "' is var-sized"));
return get_data_buffer(name, buffer, buffer_size);
}
Status Query::get_buffer(
const char* name,
uint64_t** buffer_off,
uint64_t** buffer_off_size,
void** buffer_val,
uint64_t** buffer_val_size) const {
// Check attribute
if (name == constants::coords) {
return logger_->status(
Status_QueryError("Cannot get buffer; Coordinates are not var-sized"));
}
if (array_schema_->attribute(name) == nullptr &&
array_schema_->dimension(name) == nullptr)
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; Invalid attribute/dimension name '") +
name + "'"));
if (!array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; '") + name + "' is fixed-sized"));
// Attribute or dimension
auto it = buffers_.find(name);
if (it != buffers_.end()) {
*buffer_off = (uint64_t*)it->second.buffer_;
*buffer_off_size = it->second.buffer_size_;
*buffer_val = it->second.buffer_var_;
*buffer_val_size = it->second.buffer_var_size_;
return Status::Ok();
}
// Named buffer does not exist
*buffer_off = nullptr;
*buffer_off_size = nullptr;
*buffer_val = nullptr;
*buffer_val_size = nullptr;
return Status::Ok();
}
Status Query::get_offsets_buffer(
const char* name, uint64_t** buffer_off, uint64_t** buffer_off_size) const {
// Check attribute
if (name == constants::coords) {
return logger_->status(
Status_QueryError("Cannot get buffer; Coordinates are not var-sized"));
}
if (array_schema_->attribute(name) == nullptr &&
array_schema_->dimension(name) == nullptr)
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; Invalid attribute/dimension name '") +
name + "'"));
if (!array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; '") + name + "' is fixed-sized"));
// Attribute or dimension
auto it = buffers_.find(name);
if (it != buffers_.end()) {
*buffer_off = (uint64_t*)it->second.buffer_;
*buffer_off_size = it->second.buffer_size_;
return Status::Ok();
}
// Named buffer does not exist
*buffer_off = nullptr;
*buffer_off_size = nullptr;
return Status::Ok();
}
Status Query::get_data_buffer(
const char* name, void** buffer, uint64_t** buffer_size) const {
// Check attribute
if (name != constants::coords) {
if (array_schema_->attribute(name) == nullptr &&
array_schema_->dimension(name) == nullptr)
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; Invalid attribute/dimension name '") +
name + "'"));
}
// Special zipped coordinates
if (type_ == QueryType::WRITE && name == constants::coords) {
*buffer = coords_info_.coords_buffer_;
*buffer_size = coords_info_.coords_buffer_size_;
return Status::Ok();
}
// Attribute or dimension
auto it = buffers_.find(name);
if (it != buffers_.end()) {
if (!array_schema_->var_size(name)) {
*buffer = it->second.buffer_;
*buffer_size = it->second.buffer_size_;
} else {
*buffer = it->second.buffer_var_;
*buffer_size = it->second.buffer_var_size_;
}
return Status::Ok();
}
// Named buffer does not exist
*buffer = nullptr;
*buffer_size = nullptr;
return Status::Ok();
}
Status Query::get_validity_buffer(
const char* name,
uint8_t** buffer_validity_bytemap,
uint64_t** buffer_validity_bytemap_size) const {
// Check attribute
if (!array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; '") + name + "' is non-nullable"));
// Attribute or dimension
auto it = buffers_.find(name);
if (it != buffers_.end()) {
auto vv = &it->second.validity_vector_;
*buffer_validity_bytemap = vv->bytemap();
*buffer_validity_bytemap_size = vv->bytemap_size();
}
return Status::Ok();
}
Status Query::get_buffer_vbytemap(
const char* name,
uint64_t** buffer_off,
uint64_t** buffer_off_size,
void** buffer_val,
uint64_t** buffer_val_size,
uint8_t** buffer_validity_bytemap,
uint64_t** buffer_validity_bytemap_size) const {
const ValidityVector* vv = nullptr;
RETURN_NOT_OK(get_buffer(
name, buffer_off, buffer_off_size, buffer_val, buffer_val_size, &vv));
if (vv != nullptr) {
*buffer_validity_bytemap = vv->bytemap();
*buffer_validity_bytemap_size = vv->bytemap_size();
}
return Status::Ok();
}
Status Query::get_buffer_vbytemap(
const char* name,
void** buffer,
uint64_t** buffer_size,
uint8_t** buffer_validity_bytemap,
uint64_t** buffer_validity_bytemap_size) const {
const ValidityVector* vv = nullptr;
RETURN_NOT_OK(get_buffer(name, buffer, buffer_size, &vv));
if (vv != nullptr) {
*buffer_validity_bytemap = vv->bytemap();
*buffer_validity_bytemap_size = vv->bytemap_size();
}
return Status::Ok();
}
Status Query::get_buffer(
const char* name,
void** buffer,
uint64_t** buffer_size,
const ValidityVector** validity_vector) const {
// Check nullable attribute
if (array_schema_->attribute(name) == nullptr)
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; Invalid attribute name '") + name +
"'"));
if (array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; '") + name + "' is var-sized"));
if (!array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; '") + name + "' is non-nullable"));
// Attribute or dimension
auto it = buffers_.find(name);
if (it != buffers_.end()) {
*buffer = it->second.buffer_;
*buffer_size = it->second.buffer_size_;
*validity_vector = &it->second.validity_vector_;
return Status::Ok();
}
// Named buffer does not exist
*buffer = nullptr;
*buffer_size = nullptr;
*validity_vector = nullptr;
return Status::Ok();
}
Status Query::get_buffer(
const char* name,
uint64_t** buffer_off,
uint64_t** buffer_off_size,
void** buffer_val,
uint64_t** buffer_val_size,
const ValidityVector** validity_vector) const {
// Check attribute
if (array_schema_->attribute(name) == nullptr)
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; Invalid attribute name '") + name +
"'"));
if (!array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; '") + name + "' is fixed-sized"));
if (!array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot get buffer; '") + name + "' is non-nullable"));
// Attribute or dimension
auto it = buffers_.find(name);
if (it != buffers_.end()) {
*buffer_off = (uint64_t*)it->second.buffer_;
*buffer_off_size = it->second.buffer_size_;
*buffer_val = it->second.buffer_var_;
*buffer_val_size = it->second.buffer_var_size_;
*validity_vector = &it->second.validity_vector_;
return Status::Ok();
}
// Named buffer does not exist
*buffer_off = nullptr;
*buffer_off_size = nullptr;
*buffer_val = nullptr;
*buffer_val_size = nullptr;
*validity_vector = nullptr;
return Status::Ok();
}
Status Query::get_attr_serialization_state(
const std::string& attribute, SerializationState::AttrState** state) {
*state = &serialization_state_.attribute_states[attribute];
return Status::Ok();
}
bool Query::has_results() const {
if (status_ == QueryStatus::UNINITIALIZED || type_ == QueryType::WRITE)
return false;
for (const auto& it : buffers_) {
if (*(it.second.buffer_size_) != 0)
return true;
}
return false;
}
Status Query::init() {
// Only if the query has not been initialized before
if (status_ == QueryStatus::UNINITIALIZED) {
// Check if the array got closed
if (array_ == nullptr || !array_->is_open())
return logger_->status(Status_QueryError(
"Cannot init query; The associated array is not open"));
// Check if the array got re-opened with a different query type
QueryType array_query_type;
RETURN_NOT_OK(array_->get_query_type(&array_query_type));
if (array_query_type != type_) {
std::stringstream errmsg;
errmsg << "Cannot init query; "
<< "Associated array query type does not match query type: "
<< "(" << query_type_str(array_query_type)
<< " != " << query_type_str(type_) << ")";
return logger_->status(Status_QueryError(errmsg.str()));
}
RETURN_NOT_OK(check_buffer_names());
RETURN_NOT_OK(create_strategy());
RETURN_NOT_OK(strategy_->init());
}
status_ = QueryStatus::INPROGRESS;
return Status::Ok();
}
URI Query::first_fragment_uri() const {
if (type_ == QueryType::WRITE || fragment_metadata_.empty())
return URI();
return fragment_metadata_.front()->fragment_uri();
}
URI Query::last_fragment_uri() const {
if (type_ == QueryType::WRITE || fragment_metadata_.empty())
return URI();
return fragment_metadata_.back()->fragment_uri();
}
Layout Query::layout() const {
return layout_;
}
const QueryCondition* Query::condition() const {
if (type_ == QueryType::WRITE)
return nullptr;
return &condition_;
}
Status Query::cancel() {
status_ = QueryStatus::FAILED;
return Status::Ok();
}
Status Query::process() {
if (status_ == QueryStatus::UNINITIALIZED)
return logger_->status(
Status_QueryError("Cannot process query; Query is not initialized"));
status_ = QueryStatus::INPROGRESS;
// Process query
Status st = strategy_->dowork();
// Handle error
if (!st.ok()) {
status_ = QueryStatus::FAILED;
return st;
}
if (type_ == QueryType::WRITE && layout_ == Layout::GLOBAL_ORDER) {
// reset coord buffer marker at end of global write
// this will allow for the user to properly set the next write batch
coord_buffer_is_set_ = false;
coord_data_buffer_is_set_ = false;
coord_offsets_buffer_is_set_ = false;
}
// Check if the query is complete
bool completed = !strategy_->incomplete();
// Handle callback and status
if (completed) {
if (callback_ != nullptr)
callback_(callback_data_);
status_ = QueryStatus::COMPLETED;
} else { // Incomplete
status_ = QueryStatus::INCOMPLETE;
}
return Status::Ok();
}
Status Query::create_strategy() {
if (type_ == QueryType::WRITE) {
if (layout_ == Layout::COL_MAJOR || layout_ == Layout::ROW_MAJOR) {
strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new(
OrderedWriter,
stats_->create_child("Writer"),
logger_,
storage_manager_,
array_,
config_,
buffers_,
subarray_,
layout_,
written_fragment_info_,
disable_check_global_order_,
coords_info_,
fragment_uri_));
} else if (layout_ == Layout::UNORDERED) {
strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new(
UnorderedWriter,
stats_->create_child("Writer"),
logger_,
storage_manager_,
array_,
config_,
buffers_,
subarray_,
layout_,
written_fragment_info_,
disable_check_global_order_,
coords_info_,
fragment_uri_));
} else if (layout_ == Layout::GLOBAL_ORDER) {
strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new(
GlobalOrderWriter,
stats_->create_child("Writer"),
logger_,
storage_manager_,
array_,
config_,
buffers_,
subarray_,
layout_,
written_fragment_info_,
disable_check_global_order_,
coords_info_,
fragment_uri_));
} else {
assert(false);
}
} else {
bool use_default = true;
if (use_refactored_sparse_unordered_with_dups_reader() &&
!array_schema_->dense() && layout_ == Layout::UNORDERED &&
array_schema_->allows_dups()) {
use_default = false;
auto&& [st, non_overlapping_ranges]{Query::non_overlapping_ranges()};
RETURN_NOT_OK(st);
if (*non_overlapping_ranges || !subarray_.is_set() ||
subarray_.range_num() == 1) {
strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new(
SparseUnorderedWithDupsReader<uint8_t>,
stats_->create_child("Reader"),
logger_,
storage_manager_,
array_,
config_,
buffers_,
subarray_,
layout_,
condition_));
} else {
strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new(
SparseUnorderedWithDupsReader<uint64_t>,
stats_->create_child("Reader"),
logger_,
storage_manager_,
array_,
config_,
buffers_,
subarray_,
layout_,
condition_));
}
} else if (
use_refactored_sparse_global_order_reader() &&
!array_schema_->dense() &&
(layout_ == Layout::GLOBAL_ORDER ||
(layout_ == Layout::UNORDERED && subarray_.range_num() <= 1))) {
// Using the reader for unordered queries to do deduplication.
use_default = false;
strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new(
SparseGlobalOrderReader,
stats_->create_child("Reader"),
logger_,
storage_manager_,
array_,
config_,
buffers_,
subarray_,
layout_,
condition_));
} else if (use_refactored_dense_reader() && array_schema_->dense()) {
bool all_dense = true;
for (auto& frag_md : fragment_metadata_)
all_dense &= frag_md->dense();
if (all_dense) {
use_default = false;
strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new(
DenseReader,
stats_->create_child("Reader"),
logger_,
storage_manager_,
array_,
config_,
buffers_,
subarray_,
layout_,
condition_));
}
}
if (use_default) {
strategy_ = tdb_unique_ptr<IQueryStrategy>(tdb_new(
Reader,
stats_->create_child("Reader"),
logger_,
storage_manager_,
array_,
config_,
buffers_,
subarray_,
layout_,
condition_));
}
}
if (strategy_ == nullptr)
return logger_->status(
Status_QueryError("Cannot create strategy; allocation failed"));
return Status::Ok();
}
IQueryStrategy* Query::strategy() {
if (strategy_ == nullptr) {
create_strategy();
}
return strategy_.get();
}
void Query::clear_strategy() {
strategy_ = nullptr;
}
Status Query::disable_check_global_order() {
if (status_ != QueryStatus::UNINITIALIZED)
return logger_->status(Status_QueryError(
"Cannot disable checking global order after initialization"));
if (type_ == QueryType::READ)
return logger_->status(Status_QueryError(
"Cannot disable checking global order; Applicable only to writes"));
disable_check_global_order_ = true;
return Status::Ok();
}
Status Query::check_buffer_names() {
if (type_ == QueryType::WRITE) {
// If the array is sparse, the coordinates must be provided
if (!array_schema_->dense() && !coords_info_.has_coords_)
return logger_->status(Status_WriterError(
"Sparse array writes expect the coordinates of the "
"cells to be written"));
// If the layout is unordered, the coordinates must be provided
if (layout_ == Layout::UNORDERED && !coords_info_.has_coords_)
return logger_->status(
Status_WriterError("Unordered writes expect the coordinates of the "
"cells to be written"));
// All attributes/dimensions must be provided
auto expected_num = array_schema_->attribute_num();
expected_num += (coord_buffer_is_set_ || coord_data_buffer_is_set_ ||
coord_offsets_buffer_is_set_) ?
array_schema_->dim_num() :
0;
if (buffers_.size() != expected_num)
return logger_->status(
Status_WriterError("Writes expect all attributes (and coordinates in "
"the sparse/unordered case) to be set"));
}
return Status::Ok();
}
Status Query::check_set_fixed_buffer(const std::string& name) {
if (name == constants::coords &&
!array_schema_->domain()->all_dims_same_type())
return logger_->status(Status_QueryError(
"Cannot set buffer; Setting a buffer for zipped coordinates is not "
"applicable to heterogeneous domains"));
if (name == constants::coords && !array_schema_->domain()->all_dims_fixed())
return logger_->status(Status_QueryError(
"Cannot set buffer; Setting a buffer for zipped coordinates is not "
"applicable to domains with variable-sized dimensions"));
return Status::Ok();
}
Status Query::set_config(const Config& config) {
config_ = config;
// Refresh memory budget configuration.
if (strategy_ != nullptr)
RETURN_NOT_OK(strategy_->initialize_memory_budget());
// Set subarray's config for backwards compatibility
// Users expect the query config to effect the subarray based on existing
// behavior before subarray was exposed directly
subarray_.set_config(config_);
return Status::Ok();
}
Status Query::set_coords_buffer(void* buffer, uint64_t* buffer_size) {
// Set zipped coordinates buffer
coords_info_.coords_buffer_ = buffer;
coords_info_.coords_buffer_size_ = buffer_size;
coords_info_.has_coords_ = true;
return Status::Ok();
}
Status Query::set_buffer(
const std::string& name,
void* const buffer,
uint64_t* const buffer_size,
const bool check_null_buffers) {
RETURN_NOT_OK(check_set_fixed_buffer(name));
// Check buffer
if (check_null_buffers && buffer == nullptr)
return logger_->status(
Status_QueryError("Cannot set buffer; " + name + " buffer is null"));
// Check buffer size
if (check_null_buffers && buffer_size == nullptr)
return logger_->status(
Status_QueryError("Cannot set buffer; " + name + " buffer is null"));
// For easy reference
const bool is_dim = array_schema_->is_dim(name);
const bool is_attr = array_schema_->is_attr(name);
// Check that attribute/dimension exists
if (name != constants::coords && !is_dim && !is_attr)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Invalid attribute/dimension '") + name +
"'"));
// Must not be nullable
if (array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute/dimension '") + name +
"' is nullable"));
// Check that attribute/dimension is fixed-sized
const bool var_size =
(name != constants::coords && array_schema_->var_size(name));
if (var_size)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute/dimension '") + name +
"' is var-sized"));
// Check if zipped coordinates coexist with separate coordinate buffers
if ((is_dim && has_zipped_coords_buffer_) ||
(name == constants::coords && has_coords_buffer_))
return logger_->status(Status_QueryError(
std::string("Cannot set separate coordinate buffers and "
"a zipped coordinate buffer in the same query")));
// Error if setting a new attribute/dimension after initialization
const bool exists = buffers_.find(name) != buffers_.end();
if (status_ != QueryStatus::UNINITIALIZED && !exists)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer for new attribute/dimension '") + name +
"' after initialization"));
if (name == constants::coords) {
has_zipped_coords_buffer_ = true;
// Set special function for zipped coordinates buffer
if (type_ == QueryType::WRITE)
return set_coords_buffer(buffer, buffer_size);
}
if (is_dim && type_ == QueryType::WRITE) {
// Check number of coordinates
uint64_t coords_num = *buffer_size / array_schema_->cell_size(name);
if (coord_buffer_is_set_ && coords_num != coords_info_.coords_num_)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input buffer for dimension '") +
name +
"' has a different number of coordinates than previously "
"set coordinate buffers"));
coords_info_.coords_num_ = coords_num;
coord_buffer_is_set_ = true;
coords_info_.has_coords_ = true;
}
has_coords_buffer_ |= is_dim;
// Set attribute buffer
buffers_[name].set_data_buffer(buffer, buffer_size);
return Status::Ok();
}
Status Query::set_data_buffer(
const std::string& name,
void* const buffer,
uint64_t* const buffer_size,
const bool check_null_buffers) {
RETURN_NOT_OK(check_set_fixed_buffer(name));
// Check buffer
if (check_null_buffers && buffer == nullptr)
if (type_ != QueryType::WRITE || *buffer_size != 0)
return logger_->status(
Status_QueryError("Cannot set buffer; " + name + " buffer is null"));
// Check buffer size
if (check_null_buffers && buffer_size == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " buffer size is null"));
// For easy reference
const bool is_dim = array_schema_->is_dim(name);
const bool is_attr = array_schema_->is_attr(name);
// Check that attribute/dimension exists
if (name != constants::coords && !is_dim && !is_attr)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Invalid attribute/dimension '") + name +
"'"));
if (array_schema_->dense() && type_ == QueryType::WRITE && !is_attr) {
return logger_->status(Status_QueryError(
std::string("Dense write queries cannot set dimension buffers")));
}
// Check if zipped coordinates coexist with separate coordinate buffers
if ((is_dim && has_zipped_coords_buffer_) ||
(name == constants::coords && has_coords_buffer_))
return logger_->status(Status_QueryError(
std::string("Cannot set separate coordinate buffers and "
"a zipped coordinate buffer in the same query")));
// Error if setting a new attribute/dimension after initialization
const bool exists = buffers_.find(name) != buffers_.end();
if (status_ != QueryStatus::UNINITIALIZED && !exists)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer for new attribute/dimension '") + name +
"' after initialization"));
if (name == constants::coords) {
has_zipped_coords_buffer_ = true;
// Set special function for zipped coordinates buffer
if (type_ == QueryType::WRITE)
return set_coords_buffer(buffer, buffer_size);
}
if (is_dim && type_ == QueryType::WRITE) {
// Check number of coordinates
uint64_t coords_num = *buffer_size / array_schema_->cell_size(name);
if (coord_data_buffer_is_set_ && coords_num != coords_info_.coords_num_ &&
name == data_buffer_name_)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input buffer for dimension '") +
name +
"' has a different number of coordinates than previously "
"set coordinate buffers"));
coords_info_.coords_num_ = coords_num;
coord_data_buffer_is_set_ = true;
data_buffer_name_ = name;
coords_info_.has_coords_ = true;
}
has_coords_buffer_ |= is_dim;
// Set attribute/dimension buffer on the appropriate buffer
if (!array_schema_->var_size(name))
// Fixed size data buffer
buffers_[name].set_data_buffer(buffer, buffer_size);
else
// Var sized data buffer
buffers_[name].set_data_var_buffer(buffer, buffer_size);
return Status::Ok();
}
Status Query::set_offsets_buffer(
const std::string& name,
uint64_t* const buffer_offsets,
uint64_t* const buffer_offsets_size,
const bool check_null_buffers) {
RETURN_NOT_OK(check_set_fixed_buffer(name));
// Check buffer
if (check_null_buffers && buffer_offsets == nullptr)
return logger_->status(
Status_QueryError("Cannot set buffer; " + name + " buffer is null"));
// Check buffer size
if (check_null_buffers && buffer_offsets_size == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " buffer size is null"));
// For easy reference
const bool is_dim = array_schema_->is_dim(name);
const bool is_attr = array_schema_->is_attr(name);
// Neither a dimension nor an attribute
if (!is_dim && !is_attr)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Invalid buffer name '") + name +
"' (it should be an attribute or dimension)"));
// Error if it is fixed-sized
if (!array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute/dimension '") + name +
"' is fixed-sized"));
// Error if setting a new attribute/dimension after initialization
bool exists = buffers_.find(name) != buffers_.end();
if (status_ != QueryStatus::UNINITIALIZED && !exists)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer for new attribute/dimension '") + name +
"' after initialization"));
if (is_dim && type_ == QueryType::WRITE) {
// Check number of coordinates
uint64_t coords_num =
*buffer_offsets_size / constants::cell_var_offset_size;
if (coord_offsets_buffer_is_set_ &&
coords_num != coords_info_.coords_num_ && name == offsets_buffer_name_)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input buffer for dimension '") +
name +
"' has a different number of coordinates than previously "
"set coordinate buffers"));
coords_info_.coords_num_ = coords_num;
coord_offsets_buffer_is_set_ = true;
coords_info_.has_coords_ = true;
offsets_buffer_name_ = name;
}
has_coords_buffer_ |= is_dim;
// Set attribute/dimension buffer
buffers_[name].set_offsets_buffer(buffer_offsets, buffer_offsets_size);
return Status::Ok();
}
Status Query::set_validity_buffer(
const std::string& name,
uint8_t* const buffer_validity_bytemap,
uint64_t* const buffer_validity_bytemap_size,
const bool check_null_buffers) {
RETURN_NOT_OK(check_set_fixed_buffer(name));
ValidityVector validity_vector;
RETURN_NOT_OK(validity_vector.init_bytemap(
buffer_validity_bytemap, buffer_validity_bytemap_size));
// Check validity buffer
if (check_null_buffers && validity_vector.buffer() == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " validity buffer is null"));
// Check validity buffer size
if (check_null_buffers && validity_vector.buffer_size() == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " validity buffer size is null"));
// Must be an attribute
if (!array_schema_->is_attr(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Buffer name '") + name +
"' is not an attribute"));
// Must be nullable
if (!array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute '") + name +
"' is not nullable"));
// Error if setting a new attribute after initialization
const bool exists = buffers_.find(name) != buffers_.end();
if (status_ != QueryStatus::UNINITIALIZED && !exists)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer for new attribute '") + name +
"' after initialization"));
// Set attribute/dimension buffer
buffers_[name].set_validity_buffer(std::move(validity_vector));
return Status::Ok();
}
Status Query::set_buffer(
const std::string& name,
uint64_t* const buffer_off,
uint64_t* const buffer_off_size,
void* const buffer_val,
uint64_t* const buffer_val_size,
const bool check_null_buffers) {
// Check buffer
if (check_null_buffers && buffer_val == nullptr)
if (type_ != QueryType::WRITE || *buffer_val_size != 0)
return logger_->status(
Status_QueryError("Cannot set buffer; " + name + " buffer is null"));
// Check buffer size
if (check_null_buffers && buffer_val_size == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " buffer size is null"));
// Check offset buffer
if (check_null_buffers && buffer_off == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " offset buffer is null"));
// Check offset buffer size
if (check_null_buffers && buffer_off_size == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " offset buffer size is null"));
// For easy reference
const bool is_dim = array_schema_->is_dim(name);
const bool is_attr = array_schema_->is_attr(name);
// Check that attribute/dimension exists
if (!is_dim && !is_attr)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Invalid attribute/dimension '") + name +
"'"));
// Must not be nullable
if (array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute/dimension '") + name +
"' is nullable"));
// Check that attribute/dimension is var-sized
if (!array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute/dimension '") + name +
"' is fixed-sized"));
// Error if setting a new attribute/dimension after initialization
const bool exists = buffers_.find(name) != buffers_.end();
if (status_ != QueryStatus::UNINITIALIZED && !exists)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer for new attribute/dimension '") + name +
"' after initialization"));
if (is_dim && type_ == QueryType::WRITE) {
// Check number of coordinates
uint64_t coords_num = *buffer_off_size / constants::cell_var_offset_size;
if (coord_buffer_is_set_ && coords_num != coords_info_.coords_num_)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input buffer for dimension '") +
name +
"' has a different number of coordinates than previously "
"set coordinate buffers"));
coords_info_.coords_num_ = coords_num;
coord_buffer_is_set_ = true;
coords_info_.has_coords_ = true;
}
// Set attribute/dimension buffer
buffers_[name].set_data_var_buffer(buffer_val, buffer_val_size);
buffers_[name].set_offsets_buffer(buffer_off, buffer_off_size);
return Status::Ok();
}
Status Query::set_buffer_vbytemap(
const std::string& name,
void* const buffer,
uint64_t* const buffer_size,
uint8_t* const buffer_validity_bytemap,
uint64_t* const buffer_validity_bytemap_size,
const bool check_null_buffers) {
// Convert the bytemap into a ValidityVector.
ValidityVector vv;
RETURN_NOT_OK(
vv.init_bytemap(buffer_validity_bytemap, buffer_validity_bytemap_size));
return set_buffer(
name, buffer, buffer_size, std::move(vv), check_null_buffers);
}
Status Query::set_buffer_vbytemap(
const std::string& name,
uint64_t* const buffer_off,
uint64_t* const buffer_off_size,
void* const buffer_val,
uint64_t* const buffer_val_size,
uint8_t* const buffer_validity_bytemap,
uint64_t* const buffer_validity_bytemap_size,
const bool check_null_buffers) {
// Convert the bytemap into a ValidityVector.
ValidityVector vv;
RETURN_NOT_OK(
vv.init_bytemap(buffer_validity_bytemap, buffer_validity_bytemap_size));
return set_buffer(
name,
buffer_off,
buffer_off_size,
buffer_val,
buffer_val_size,
std::move(vv),
check_null_buffers);
}
Status Query::set_buffer(
const std::string& name,
void* const buffer,
uint64_t* const buffer_size,
ValidityVector&& validity_vector,
const bool check_null_buffers) {
RETURN_NOT_OK(check_set_fixed_buffer(name));
// Check buffer
if (check_null_buffers && buffer == nullptr)
return logger_->status(
Status_QueryError("Cannot set buffer; " + name + " buffer is null"));
// Check buffer size
if (check_null_buffers && buffer_size == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " buffer size is null"));
// Check validity buffer offset
if (check_null_buffers && validity_vector.buffer() == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " validity buffer is null"));
// Check validity buffer size
if (check_null_buffers && validity_vector.buffer_size() == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " validity buffer size is null"));
// Must be an attribute
if (!array_schema_->is_attr(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Buffer name '") + name +
"' is not an attribute"));
// Must be fixed-size
if (array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute '") + name +
"' is var-sized"));
// Must be nullable
if (!array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute '") + name +
"' is not nullable"));
// Error if setting a new attribute/dimension after initialization
const bool exists = buffers_.find(name) != buffers_.end();
if (status_ != QueryStatus::UNINITIALIZED && !exists)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer for new attribute '") + name +
"' after initialization"));
// Set attribute buffer
buffers_[name].set_data_buffer(buffer, buffer_size);
buffers_[name].set_validity_buffer(std::move(validity_vector));
return Status::Ok();
}
Status Query::set_buffer(
const std::string& name,
uint64_t* const buffer_off,
uint64_t* const buffer_off_size,
void* const buffer_val,
uint64_t* const buffer_val_size,
ValidityVector&& validity_vector,
const bool check_null_buffers) {
// Check buffer
if (check_null_buffers && buffer_val == nullptr)
if (type_ != QueryType::WRITE || *buffer_val_size != 0)
return logger_->status(
Status_QueryError("Cannot set buffer; " + name + " buffer is null"));
// Check buffer size
if (check_null_buffers && buffer_val_size == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " buffer size is null"));
// Check buffer offset
if (check_null_buffers && buffer_off == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " offset buffer is null"));
// Check buffer offset size
if (check_null_buffers && buffer_off_size == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " offset buffer size is null"));
;
// Check validity buffer offset
if (check_null_buffers && validity_vector.buffer() == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " validity buffer is null"));
// Check validity buffer size
if (check_null_buffers && validity_vector.buffer_size() == nullptr)
return logger_->status(Status_QueryError(
"Cannot set buffer; " + name + " validity buffer size is null"));
// Must be an attribute
if (!array_schema_->is_attr(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Buffer name '") + name +
"' is not an attribute"));
// Must be var-size
if (!array_schema_->var_size(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute '") + name +
"' is fixed-sized"));
// Must be nullable
if (!array_schema_->is_nullable(name))
return logger_->status(Status_QueryError(
std::string("Cannot set buffer; Input attribute '") + name +
"' is not nullable"));
// Error if setting a new attribute after initialization
const bool exists = buffers_.find(name) != buffers_.end();
if (status_ != QueryStatus::UNINITIALIZED && !exists)
return logger_->status(Status_QueryError(
std::string("Cannot set buffer for new attribute '") + name +
"' after initialization"));
// Set attribute/dimension buffer
buffers_[name].set_data_var_buffer(buffer_val, buffer_val_size);
buffers_[name].set_offsets_buffer(buffer_off, buffer_off_size);
buffers_[name].set_validity_buffer(std::move(validity_vector));
return Status::Ok();
}
Status Query::set_est_result_size(
std::unordered_map<std::string, Subarray::ResultSize>& est_result_size,
std::unordered_map<std::string, Subarray::MemorySize>& max_mem_size) {
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot set estimated result size; Operation currently "
"unsupported for write queries"));
return subarray_.set_est_result_size(est_result_size, max_mem_size);
}
Status Query::set_layout_unsafe(Layout layout) {
layout_ = layout;
subarray_.set_layout(layout);
return Status::Ok();
}
Status Query::set_layout(Layout layout) {
if (type_ == QueryType::READ && status_ != QueryStatus::UNINITIALIZED)
return logger_->status(
Status_QueryError("Cannot set layout after initialization"));
if (layout == Layout::HILBERT)
return logger_->status(Status_QueryError(
"Cannot set layout; Hilbert order is not applicable to queries"));
if (type_ == QueryType::WRITE && array_schema_->dense() &&
layout == Layout::UNORDERED) {
return logger_->status(Status_QueryError(
"Unordered writes are only possible for sparse arrays"));
}
layout_ = layout;
subarray_.set_layout(layout);
return Status::Ok();
}
Status Query::set_condition(const QueryCondition& condition) {
if (type_ == QueryType::WRITE)
return logger_->status(Status_QueryError(
"Cannot set query condition; Operation only applicable "
"to read queries"));
condition_ = condition;
return Status::Ok();
}
void Query::set_status(QueryStatus status) {
status_ = status;
}
Status Query::set_subarray(const void* subarray) {
if (!array_schema_->domain()->all_dims_same_type())
return logger_->status(
Status_QueryError("Cannot set subarray; Function not applicable to "
"heterogeneous domains"));
if (!array_schema_->domain()->all_dims_fixed())
return logger_->status(
Status_QueryError("Cannot set subarray; Function not applicable to "
"domains with variable-sized dimensions"));
// Prepare a subarray object
Subarray sub(array_, layout_, stats_, logger_);
if (subarray != nullptr) {
auto dim_num = array_schema_->dim_num();
auto s_ptr = (const unsigned char*)subarray;
uint64_t offset = 0;
bool err_on_range_oob = true;
if (type_ == QueryType::READ) {
// Get read_range_oob config setting
bool found = false;
std::string read_range_oob_str =
config()->get("sm.read_range_oob", &found);
assert(found);
if (read_range_oob_str != "error" && read_range_oob_str != "warn")
return logger_->status(Status_QueryError(
"Invalid value " + read_range_oob_str +
" for sm.read_range_obb. Acceptable values are 'error' or "
"'warn'."));
err_on_range_oob = read_range_oob_str == "error";
}
for (unsigned d = 0; d < dim_num; ++d) {
auto r_size = 2 * array_schema_->dimension(d)->coord_size();
Range range(&s_ptr[offset], r_size);
RETURN_NOT_OK(sub.add_range(d, std::move(range), err_on_range_oob));
offset += r_size;
}
}
if (type_ == QueryType::WRITE) {
// Not applicable to sparse arrays
if (!array_schema_->dense())
return logger_->status(Status_WriterError(
"Setting a subarray is not supported in sparse writes"));
// Subarray must be unary for dense writes
if (sub.range_num() != 1)
return logger_->status(
Status_WriterError("Cannot set subarray; Multi-range dense writes "
"are not supported"));
if (strategy_ != nullptr)
strategy_->reset();
}
subarray_ = sub;
status_ = QueryStatus::UNINITIALIZED;
return Status::Ok();
}
const Subarray* Query::subarray() const {
return &subarray_;
}
Status Query::set_subarray_unsafe(const Subarray& subarray) {
subarray_ = subarray;
return Status::Ok();
}
Status Query::set_subarray(const tiledb::sm::Subarray& subarray) {
auto query_status = status();
if (query_status != tiledb::sm::QueryStatus::UNINITIALIZED &&
query_status != tiledb::sm::QueryStatus::COMPLETED) {
// Can be in this initialized state when query has been de-serialized
// server-side and are trying to perform local submit.
// Don't change anything and return indication of success.
return Status::Ok();
}
// Set subarray
if (!subarray.is_set())
// Nothing useful to set here, will leave query with its current
// settings and consider successful.
return Status::Ok();
auto prev_layout = subarray_.layout();
subarray_ = subarray;
subarray_.set_layout(prev_layout);
status_ = QueryStatus::UNINITIALIZED;
return Status::Ok();
}
Status Query::set_subarray_unsafe(const NDRange& subarray) {
// Prepare a subarray object
Subarray sub(array_, layout_, stats_, logger_);
if (!subarray.empty()) {
auto dim_num = array_schema_->dim_num();
for (unsigned d = 0; d < dim_num; ++d)
RETURN_NOT_OK(sub.add_range_unsafe(d, subarray[d]));
}
assert(layout_ == sub.layout());
subarray_ = sub;
status_ = QueryStatus::UNINITIALIZED;
return Status::Ok();
}
Status Query::check_buffers_correctness() {
// Iterate through each attribute
for (auto& attr : buffer_names()) {
if (array_schema_->var_size(attr)) {
// Check for data buffer under buffer_var and offsets buffer under buffer
if (type_ == QueryType::READ) {
if (buffer(attr).buffer_var_ == nullptr) {
return logger_->status(Status_QueryError(
std::string("Var-Sized input attribute/dimension '") + attr +
"' is not set correctly. \nVar size buffer is not set."));
}
} else {
if (buffer(attr).buffer_var_ == nullptr &&
*buffer(attr).buffer_var_size_ != 0) {
return logger_->status(Status_QueryError(
std::string("Var-Sized input attribute/dimension '") + attr +
"' is not set correctly. \nVar size buffer is not set and buffer "
"size if not 0."));
}
}
if (buffer(attr).buffer_ == nullptr) {
return logger_->status(Status_QueryError(
std::string("Var-Sized input attribute/dimension '") + attr +
"' is not set correctly. \nOffsets buffer is not set."));
}
} else {
// Fixed sized
if (buffer(attr).buffer_ == nullptr) {
return logger_->status(Status_QueryError(
std::string("Fix-Sized input attribute/dimension '") + attr +
"' is not set correctly. \nData buffer is not set."));
}
}
if (array_schema_->is_nullable(attr)) {
bool exists_validity = buffer(attr).validity_vector_.buffer() != nullptr;
if (!exists_validity) {
return logger_->status(Status_QueryError(
std::string("Nullable input attribute/dimension '") + attr +
"' is not set correctly \nValidity buffer is not set"));
}
}
}
return Status::Ok();
}
Status Query::submit() {
// Do not resubmit completed reads.
if (type_ == QueryType::READ && status_ == QueryStatus::COMPLETED) {
return Status::Ok();
}
// Check attribute/dimensions buffers completeness before query submits
RETURN_NOT_OK(check_buffers_correctness());
if (array_->is_remote()) {
auto rest_client = storage_manager_->rest_client();
if (rest_client == nullptr)
return logger_->status(Status_QueryError(
"Error in query submission; remote array with no rest client."));
if (status_ == QueryStatus::UNINITIALIZED) {
RETURN_NOT_OK(create_strategy());
RETURN_NOT_OK(strategy_->init());
}
return rest_client->submit_query_to_rest(array_->array_uri(), this);
}
RETURN_NOT_OK(init());
return storage_manager_->query_submit(this);
}
Status Query::submit_async(
std::function<void(void*)> callback, void* callback_data) {
// Do not resubmit completed reads.
if (type_ == QueryType::READ && status_ == QueryStatus::COMPLETED) {
callback(callback_data);
return Status::Ok();
}
RETURN_NOT_OK(init());
if (array_->is_remote())
return logger_->status(
Status_QueryError("Error in async query submission; async queries not "
"supported for remote arrays."));
callback_ = callback;
callback_data_ = callback_data;
return storage_manager_->query_submit_async(this);
}
QueryStatus Query::status() const {
return status_;
}
QueryStatusDetailsReason Query::status_incomplete_reason() const {
if (strategy_ != nullptr)
return strategy_->status_incomplete_reason();
return QueryStatusDetailsReason::REASON_NONE;
}
QueryType Query::type() const {
return type_;
}
const Config* Query::config() const {
return &config_;
}
stats::Stats* Query::stats() const {
return stats_;
}
tdb_shared_ptr<Buffer> Query::rest_scratch() const {
return rest_scratch_;
}
bool Query::use_refactored_dense_reader() {
bool use_refactored_readers = false;
bool found = false;
// First check for legacy option
config_.get<bool>(
"sm.use_refactored_readers", &use_refactored_readers, &found);
// If the legacy/deprecated option is set use it over the new parameters
// This facilitates backwards compatibility
if (found) {
logger_->warn(
"sm.use_refactored_readers config option is deprecated.\nPlease use "
"'sm.query.dense.reader' with value of 'refactored' or 'legacy'");
return use_refactored_readers;
}
const std::string& val = config_.get("sm.query.dense.reader", &found);
assert(found);
return val == "refactored";
}
bool Query::use_refactored_sparse_global_order_reader() {
bool use_refactored_readers = false;
bool found = false;
// First check for legacy option
config_.get<bool>(
"sm.use_refactored_readers", &use_refactored_readers, &found);
// If the legacy/deprecated option is set use it over the new parameters
// This facilitates backwards compatibility
if (found) {
logger_->warn(
"sm.use_refactored_readers config option is deprecated.\nPlease use "
"'sm.query.sparse_global_order.reader' with value of 'refactored' or "
"'legacy'");
return use_refactored_readers;
}
const std::string& val =
config_.get("sm.query.sparse_global_order.reader", &found);
assert(found);
return val == "refactored";
}
bool Query::use_refactored_sparse_unordered_with_dups_reader() {
bool use_refactored_readers = false;
bool found = false;
// First check for legacy option
config_.get<bool>(
"sm.use_refactored_readers", &use_refactored_readers, &found);
// If the legacy/deprecated option is set use it over the new parameters
// This facilitates backwards compatibility
if (found) {
logger_->warn(
"sm.use_refactored_readers config option is deprecated.\nPlease use "
"'sm.query.sparse_unordered_with_dups.reader' with value of "
"'refactored' or 'legacy'");
return use_refactored_readers;
}
const std::string& val =
config_.get("sm.query.sparse_unordered_with_dups.reader", &found);
assert(found);
return val == "refactored";
}
tuple<Status, optional<bool>> Query::non_overlapping_ranges() {
return subarray_.non_overlapping_ranges(storage_manager_->compute_tp());
}
/* ****************************** */
/* PRIVATE METHODS */
/* ****************************** */
} // namespace sm
} // namespace tiledb
| TileDB-Inc/TileDB | tiledb/sm/query/query.cc | C++ | mit | 69,785 |
class CreateProductMaterials < ActiveRecord::Migration[5.0]
def change
create_table :product_materials do |t|
t.belongs_to :product, index: true
t.string :name
t.string :material
t.string :description
t.timestamps
end
end
end
| Klaital/abandonedforge.com | db/migrate/20160920213323_create_product_materials.rb | Ruby | mit | 269 |
<?php
/**
* [WeEngine System] Copyright (c) 2014 WE7.CC
* WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
*/
defined('IN_IA') or exit('Access Denied');
load()->func('file');
load()->model('article');
load()->model('account');
$dos = array('display', 'post', 'del');
$do = in_array($do, $dos) ? $do : 'display';
permission_check_account_user('platform_site');
$_W['page']['title'] = '文章管理 - 微官网';
$category = pdo_fetchall("SELECT id,parentid,name FROM ".tablename('site_category')." WHERE uniacid = '{$_W['uniacid']}' ORDER BY parentid ASC, displayorder ASC, id ASC ", array(), 'id');
$parent = array();
$children = array();
if (!empty($category)) {
foreach ($category as $cid => $cate) {
if (!empty($cate['parentid'])) {
$children[$cate['parentid']][] = $cate;
} else {
$parent[$cate['id']] = $cate;
}
}
}
if ($do == 'display') {
$pindex = max(1, intval($_GPC['page']));
$psize = 20;
$condition = '';
$params = array();
if (!empty($_GPC['keyword'])) {
$condition .= " AND `title` LIKE :keyword";
$params[':keyword'] = "%{$_GPC['keyword']}%";
}
if (!empty($_GPC['category']['childid'])) {
$cid = intval($_GPC['category']['childid']);
$condition .= " AND ccate = '{$cid}'";
} elseif (!empty($_GPC['category']['parentid'])) {
$cid = intval($_GPC['category']['parentid']);
$condition .= " AND pcate = '{$cid}'";
}
$list = pdo_fetchall("SELECT * FROM ".tablename('site_article')." WHERE uniacid = '{$_W['uniacid']}' $condition ORDER BY displayorder DESC, edittime DESC, id DESC LIMIT ".($pindex - 1) * $psize.','.$psize, $params);
$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('site_article') . " WHERE uniacid = '{$_W['uniacid']}'".$condition, $params);
$pager = pagination($total, $pindex, $psize);
$article_ids = array();
if (!empty($list)) {
foreach ($list as $item) {
$article_ids[] = $item['id'];
}
}
$article_comment = table('sitearticlecomment')->srticleCommentUnread($article_ids);
$setting = uni_setting($_W['uniacid']);
template('site/article-display');
} elseif ($do == 'post') {
$id = intval($_GPC['id']);
$template = uni_templates();
$pcate = intval($_GPC['pcate']);
$ccate = intval($_GPC['ccate']);
if (!empty($id)) {
$item = pdo_fetch("SELECT * FROM ".tablename('site_article')." WHERE id = :id" , array(':id' => $id));
$item['type'] = explode(',', $item['type']);
$pcate = $item['pcate'];
$ccate = $item['ccate'];
if (empty($item)) {
itoast('抱歉,文章不存在或是已经删除!', '', 'error');
}
$key = pdo_fetchall('SELECT content FROM ' . tablename('rule_keyword') . ' WHERE rid = :rid AND uniacid = :uniacid', array(':rid' => $item['rid'], ':uniacid' => $_W['uniacid']));
if (!empty($key)) {
$keywords = array();
foreach ($key as $row) {
$keywords[] = $row['content'];
}
$keywords = implode(',', array_values($keywords));
}
$item['credit'] = iunserializer($item['credit']) ? iunserializer($item['credit']) : array();
if (!empty($item['credit']['limit'])) {
$credit_num = pdo_fetchcolumn('SELECT SUM(credit_value) FROM ' . tablename('mc_handsel') . ' WHERE uniacid = :uniacid AND module = :module AND sign = :sign', array(':uniacid' => $_W['uniacid'], ':module' => 'article', ':sign' => md5(iserializer(array('id' => $id)))));
if (is_null($credit_num)) {
$credit_num = 0;
}
$credit_yu = (($item['credit']['limit'] - $credit_num) < 0) ? 0 : $item['credit']['limit'] - $credit_num;
}
} else {
$item['credit'] = array();
$keywords = '';
}
if (checksubmit('submit')) {
if (empty($_GPC['title'])) {
itoast('标题不能为空,请输入标题!', '', '');
}
$sensitive_title = detect_sensitive_word($_GPC['title']);
if (!empty($sensitive_title)) {
itoast('不能使用敏感词:' . $sensitive_title, '', '');
}
$sensitive_content = detect_sensitive_word($_GPC['content']);
if (!empty($sensitive_content)) {
itoast('不能使用敏感词:' . $sensitive_content, '', '');
}
$data = array(
'uniacid' => $_W['uniacid'],
'iscommend' => intval($_GPC['option']['commend']),
'ishot' => intval($_GPC['option']['hot']),
'pcate' => intval($_GPC['category']['parentid']),
'ccate' => intval($_GPC['category']['childid']),
'template' => addslashes($_GPC['template']),
'title' => addslashes($_GPC['title']),
'description' => addslashes($_GPC['description']),
'content' => safe_gpc_html(htmlspecialchars_decode($_GPC['content'], ENT_QUOTES)),
'incontent' => intval($_GPC['incontent']),
'source' => addslashes($_GPC['source']),
'author' => addslashes($_GPC['author']),
'displayorder' => intval($_GPC['displayorder']),
'linkurl' => addslashes($_GPC['linkurl']),
'createtime' => TIMESTAMP,
'edittime' => TIMESTAMP,
'click' => intval($_GPC['click'])
);
if (!empty($_GPC['thumb'])) {
if (file_is_image($_GPC['thumb'])) {
$data['thumb'] = $_GPC['thumb'];
}
} elseif (!empty($_GPC['autolitpic'])) {
$match = array();
preg_match('/<img.*?src="?(.+\.(jpg|jpeg|gif|bmp|png))"/', $_GPC['content'], $match);
if (!empty($match[1])) {
$url = $match[1];
$file = file_remote_attach_fetch($url);
if (!is_error($file)) {
$data['thumb'] = $file;
file_remote_upload($file);
}
}
} else {
$data['thumb'] = '';
}
$keyword = str_replace(',', ',', trim($_GPC['keyword']));
$keyword = explode(',', $keyword);
if (!empty($keyword)) {
$rule['uniacid'] = $_W['uniacid'];
$rule['name'] = '文章:' . $_GPC['title'] . ' 触发规则';
$rule['module'] = 'news';
$rule['status'] = 1;
$keywords = array();
foreach ($keyword as $key) {
$key = trim($key);
if (empty($key)) continue;
$keywords[] = array(
'uniacid' => $_W['uniacid'],
'module' => 'news',
'content' => $key,
'status' => 1,
'type' => 1,
'displayorder' => 1,
);
}
$reply['title'] = $_GPC['title'];
$reply['description'] = $_GPC['description'];
$reply['thumb'] = $data['thumb'];
$reply['url'] = murl('site/site/detail', array('id' => $id));
}
if (!empty($_GPC['credit']['status'])) {
$credit['status'] = intval($_GPC['credit']['status']);
$credit['limit'] = intval($_GPC['credit']['limit']) ? intval($_GPC['credit']['limit']) : itoast('请设置积分上限', '', '');
$credit['share'] = intval($_GPC['credit']['share']) ? intval($_GPC['credit']['share']) : itoast('请设置分享时赠送积分多少', '', '');
$credit['click'] = intval($_GPC['credit']['click']) ? intval($_GPC['credit']['click']) : itoast('请设置阅读时赠送积分多少', '', '');
$data['credit'] = iserializer($credit);
} else {
$data['credit'] = iserializer(array('status' => 0, 'limit' => 0, 'share' => 0, 'click' => 0));
}
if (empty($id)) {
unset($data['edittime']);
if (!empty($keywords)) {
pdo_insert('rule', $rule);
$rid = pdo_insertid();
foreach ($keywords as $li) {
$li['rid'] = $rid;
pdo_insert('rule_keyword', $li);
}
$reply['rid'] = $rid;
pdo_insert('news_reply', $reply);
$data['rid'] = $rid;
}
pdo_insert('site_article', $data);
$aid = pdo_insertid();
pdo_update('news_reply', array('url' => murl('site/site/detail', array('id' => $aid))), array('rid' => $rid));
} else {
unset($data['createtime']);
pdo_delete('rule', array('id' => $item['rid'], 'uniacid' => $_W['uniacid']));
pdo_delete('rule_keyword', array('rid' => $item['rid'], 'uniacid' => $_W['uniacid']));
pdo_delete('news_reply', array('rid' => $item['rid']));
if (!empty($keywords)) {
pdo_insert('rule', $rule);
$rid = pdo_insertid();
foreach ($keywords as $li) {
$li['rid'] = $rid;
pdo_insert('rule_keyword', $li);
}
$reply['rid'] = $rid;
pdo_insert('news_reply', $reply);
$data['rid'] = $rid;
} else {
$data['rid'] = 0;
$data['kid'] = 0;
}
pdo_update('site_article', $data, array('id' => $id));
}
itoast('文章更新成功!', url('site/article/display'), 'success');
} else {
template('site/article-post');
}
} elseif($do == 'del') {
if (checksubmit('submit')) {
foreach ($_GPC['rid'] as $key => $id) {
$id = intval($id);
$row = pdo_get('site_article', array('id' => $id, 'uniacid' => $_W['uniacid']));
if (empty($row)) {
itoast('抱歉,文章不存在或是已经被删除!', '', '');
}
if (!empty($row['rid'])) {
pdo_delete('rule', array('id' => $row['rid'], 'uniacid' => $_W['uniacid']));
pdo_delete('rule_keyword', array('rid' => $row['rid'], 'uniacid' => $_W['uniacid']));
pdo_delete('news_reply', array('rid' => $row['rid']));
}
pdo_delete('site_article', array('id' => $id, 'uniacid'=>$_W['uniacid']));
}
itoast('批量删除成功!', referer(), 'success');
} else {
$id = intval($_GPC['id']);
$row = pdo_fetch("SELECT id,rid,kid,thumb FROM ".tablename('site_article')." WHERE id = :id", array(':id' => $id));
if (empty($row)) {
itoast('抱歉,文章不存在或是已经被删除!', '', '');
}
if (!empty($row['rid'])) {
pdo_delete('rule', array('id' => $row['rid'], 'uniacid' => $_W['uniacid']));
pdo_delete('rule_keyword', array('rid' => $row['rid'], 'uniacid' => $_W['uniacid']));
pdo_delete('news_reply', array('rid' => $row['rid']));
}
if (pdo_delete('site_article', array('id' => $id,'uniacid'=>$_W['uniacid']))){
itoast('删除成功!', referer(), 'success');
} else {
itoast('删除失败!', referer(), 'error');
}
}
}
| justzheng/test1 | web/source/site/article.ctrl.php | PHP | mit | 9,565 |
<?php
namespace Kr\OAuthClient\Credentials;
class Client extends AbstractCredentials
{
protected $clientId, $clientSecret, $redirectUri;
/**
* Client constructor.
* @param string $clientId
* @param string $clientSecret
* @param string $redirectUri
*/
public function __construct($clientId, $clientSecret, $redirectUri)
{
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
$this->redirectUri = $redirectUri;
}
/**
* @inheritdoc
*/
public function getCredentials()
{
return [
"client_id" => $this->getClientId(),
"client_secret" => $this->getClientSecret(),
"redirect_uri" => $this->getRedirectUri(),
];
}
/**
* @return mixed
*/
public function getClientId()
{
return $this->clientId;
}
/**
* @return mixed
*/
public function getClientSecret()
{
return $this->clientSecret;
}
/**
* @return mixed
*/
public function getRedirectUri()
{
return $this->redirectUri;
}
/**
* @inheritdoc
*/
public static function getType()
{
return "client_credentials";
}
} | koenreiniers/oauth-client | src/Credentials/Client.php | PHP | mit | 1,264 |
$(function () {
$('.imageUploadMultiple').each(function (index, item) {
var $item = $(item);
var $group = $item.closest('.form-group');
var $innerGroup = $item.find('.form-group');
var $errors = $item.find('.errors');
var $input = $item.find('.imageValue');
var flow = new Flow({
target: $item.data('target'),
testChunks: false,
chunkSize: 1024 * 1024 * 1024,
query: {
_token: $item.data('token')
}
});
var updateValue = function () {
var values = [];
$item.find('img[data-value]').each(function () {
values.push($(this).data('value'));
});
$input.val(values.join(','));
};
flow.assignBrowse($item.find('.imageBrowse'));
flow.on('filesSubmitted', function (file) {
flow.upload();
});
flow.on('fileSuccess', function (file, message) {
flow.removeFile(file);
$errors.html('');
$group.removeClass('has-error');
var result = $.parseJSON(message);
$innerGroup.append('<div class="col-xs-6 col-md-3 imageThumbnail"><div class="thumbnail">' +
'<img data-value="' + result.value + '" src="' + result.url + '" />' +
'<a href="#" class="imageRemove">Remove</a></div></div>');
updateValue();
});
flow.on('fileError', function (file, message) {
flow.removeFile(file);
var response = $.parseJSON(message);
var errors = '';
$.each(response, function (index, error) {
errors += '<p class="help-block">' + error + '</p>'
});
$errors.html(errors);
$group.addClass('has-error');
});
$item.on('click', '.imageRemove', function (e) {
e.preventDefault();
$(this).closest('.imageThumbnail').remove();
updateValue();
});
$innerGroup.sortable({
onUpdate: function () {
updateValue();
}
});
});
}); | Asvae/SleepingOwlAdmin | resources/assets/js/form/image/initMultiple.js | JavaScript | mit | 2,178 |
module Schema
include Virtus.module(:constructor => false, :mass_assignment => false)
def initialize
set_default_attributes
end
def attributes
attribute_set.get(self)
end
def to_h
attributes
end
end
| obsidian-btc/schema | lib/schema/schema.rb | Ruby | mit | 228 |
/**
* k-d Tree JavaScript - V 1.01
*
* https://github.com/ubilabs/kd-tree-javascript
*
* @author Mircea Pricop <pricop@ubilabs.net>, 2012
* @author Martin Kleppe <kleppe@ubilabs.net>, 2012
* @author Ubilabs http://ubilabs.net, 2012
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports === 'object') {
factory(exports);
} else {
factory((root.commonJsStrict = {}));
}
}(this, function (exports) {
function Node(obj, dimension, parent) {
this.obj = obj;
this.left = null;
this.right = null;
this.parent = parent;
this.dimension = dimension;
}
function kdTree(points, metric, dimensions) {
var self = this;
function buildTree(points, depth, parent) {
var dim = depth % dimensions.length,
median,
node;
if (points.length === 0) {
return null;
}
if (points.length === 1) {
return new Node(points[0], dim, parent);
}
points.sort(function (a, b) {
return a[dimensions[dim]] - b[dimensions[dim]];
});
median = Math.floor(points.length / 2);
node = new Node(points[median], dim, parent);
node.left = buildTree(points.slice(0, median), depth + 1, node);
node.right = buildTree(points.slice(median + 1), depth + 1, node);
return node;
}
// Reloads a serialied tree
function loadTree (data) {
// Just need to restore the `parent` parameter
self.root = data;
function restoreParent (root) {
if (root.left) {
root.left.parent = root;
restoreParent(root.left);
}
if (root.right) {
root.right.parent = root;
restoreParent(root.right);
}
}
restoreParent(self.root);
}
// If points is not an array, assume we're loading a pre-built tree
if (!Array.isArray(points)) loadTree(points, metric, dimensions);
else this.root = buildTree(points, 0, null);
// Convert to a JSON serializable structure; this just requires removing
// the `parent` property
this.toJSON = function (src) {
if (!src) src = this.root;
var dest = new Node(src.obj, src.dimension, null);
if (src.left) dest.left = self.toJSON(src.left);
if (src.right) dest.right = self.toJSON(src.right);
return dest;
};
this.insert = function (point) {
function innerSearch(node, parent) {
if (node === null) {
return parent;
}
var dimension = dimensions[node.dimension];
if (point[dimension] < node.obj[dimension]) {
return innerSearch(node.left, node);
} else {
return innerSearch(node.right, node);
}
}
var insertPosition = innerSearch(this.root, null),
newNode,
dimension;
if (insertPosition === null) {
this.root = new Node(point, 0, null);
return;
}
newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition);
dimension = dimensions[insertPosition.dimension];
if (point[dimension] < insertPosition.obj[dimension]) {
insertPosition.left = newNode;
} else {
insertPosition.right = newNode;
}
};
this.remove = function (point) {
var node;
function nodeSearch(node) {
if (node === null) {
return null;
}
if (node.obj === point) {
return node;
}
var dimension = dimensions[node.dimension];
if (point[dimension] < node.obj[dimension]) {
return nodeSearch(node.left, node);
} else {
return nodeSearch(node.right, node);
}
}
function removeNode(node) {
var nextNode,
nextObj,
pDimension;
function findMin(node, dim) {
var dimension,
own,
left,
right,
min;
if (node === null) {
return null;
}
dimension = dimensions[dim];
if (node.dimension === dim) {
if (node.left !== null) {
return findMin(node.left, dim);
}
return node;
}
own = node.obj[dimension];
left = findMin(node.left, dim);
right = findMin(node.right, dim);
min = node;
if (left !== null && left.obj[dimension] < own) {
min = left;
}
if (right !== null && right.obj[dimension] < min.obj[dimension]) {
min = right;
}
return min;
}
if (node.left === null && node.right === null) {
if (node.parent === null) {
self.root = null;
return;
}
pDimension = dimensions[node.parent.dimension];
if (node.obj[pDimension] < node.parent.obj[pDimension]) {
node.parent.left = null;
} else {
node.parent.right = null;
}
return;
}
// If the right subtree is not empty, swap with the minimum element on the
// node's dimension. If it is empty, we swap the left and right subtrees and
// do the same.
if (node.right !== null) {
nextNode = findMin(node.right, node.dimension);
nextObj = nextNode.obj;
removeNode(nextNode);
node.obj = nextObj;
} else {
nextNode = findMin(node.left, node.dimension);
nextObj = nextNode.obj;
removeNode(nextNode);
node.right = node.left;
node.left = null;
node.obj = nextObj;
}
}
node = nodeSearch(self.root);
if (node === null) { return; }
removeNode(node);
};
this.nearest = function (point, maxNodes, maxDistance) {
var i,
result,
bestNodes;
bestNodes = new BinaryHeap(
function (e) { return -e[1]; }
);
function nearestSearch(node) {
var bestChild,
dimension = dimensions[node.dimension],
ownDistance = metric(point, node.obj),
linearPoint = {},
linearDistance,
otherChild,
i;
function saveNode(node, distance) {
bestNodes.push([node, distance]);
if (bestNodes.size() > maxNodes) {
bestNodes.pop();
}
}
for (i = 0; i < dimensions.length; i += 1) {
if (i === node.dimension) {
linearPoint[dimensions[i]] = point[dimensions[i]];
} else {
linearPoint[dimensions[i]] = node.obj[dimensions[i]];
}
}
linearDistance = metric(linearPoint, node.obj);
if (node.right === null && node.left === null) {
if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
return;
}
if (node.right === null) {
bestChild = node.left;
} else if (node.left === null) {
bestChild = node.right;
} else {
if (point[dimension] < node.obj[dimension]) {
bestChild = node.left;
} else {
bestChild = node.right;
}
}
nearestSearch(bestChild);
if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {
if (bestChild === node.left) {
otherChild = node.right;
} else {
otherChild = node.left;
}
if (otherChild !== null) {
nearestSearch(otherChild);
}
}
}
if (maxDistance) {
for (i = 0; i < maxNodes; i += 1) {
bestNodes.push([null, maxDistance]);
}
}
if(self.root)
nearestSearch(self.root);
result = [];
for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) {
if (bestNodes.content[i][0]) {
result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);
}
}
return result;
};
this.balanceFactor = function () {
function height(node) {
if (node === null) {
return 0;
}
return Math.max(height(node.left), height(node.right)) + 1;
}
function count(node) {
if (node === null) {
return 0;
}
return count(node.left) + count(node.right) + 1;
}
return height(self.root) / (Math.log(count(self.root)) / Math.log(2));
};
}
// Binary heap implementation from:
// http://eloquentjavascript.net/appendix2.html
function BinaryHeap(scoreFunction){
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function(element) {
// Add the new element to the end of the array.
this.content.push(element);
// Allow it to bubble up.
this.bubbleUp(this.content.length - 1);
},
pop: function() {
// Store the first element so we can return it later.
var result = this.content[0];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it sink down.
if (this.content.length > 0) {
this.content[0] = end;
this.sinkDown(0);
}
return result;
},
peek: function() {
return this.content[0];
},
remove: function(node) {
var len = this.content.length;
// To remove a value, we must search through the array to find
// it.
for (var i = 0; i < len; i++) {
if (this.content[i] == node) {
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
if (i != len - 1) {
this.content[i] = end;
if (this.scoreFunction(end) < this.scoreFunction(node))
this.bubbleUp(i);
else
this.sinkDown(i);
}
return;
}
}
throw new Error("Node not found.");
},
size: function() {
return this.content.length;
},
bubbleUp: function(n) {
// Fetch the element that has to be moved.
var element = this.content[n];
// When at 0, an element can not go up any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor((n + 1) / 2) - 1,
parent = this.content[parentN];
// Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
// Update 'n' to continue at the new position.
n = parentN;
}
// Found a parent that is less, no need to move it further.
else {
break;
}
}
},
sinkDown: function(n) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[n],
elemScore = this.scoreFunction(element);
while(true) {
// Compute the indices of the child elements.
var child2N = (n + 1) * 2, child1N = child2N - 1;
// This is used to store the new position of the element,
// if any.
var swap = null;
// If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N],
child1Score = this.scoreFunction(child1);
// If the score is less than our element's, we need to swap.
if (child1Score < elemScore)
swap = child1N;
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N],
child2Score = this.scoreFunction(child2);
if (child2Score < (swap == null ? elemScore : child1Score)){
swap = child2N;
}
}
// If the element needs to be moved, swap it, and continue.
if (swap != null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
// Otherwise, we are done.
else {
break;
}
}
}
};
this.kdTree = kdTree;
exports.kdTree = kdTree;
exports.BinaryHeap = BinaryHeap;
}));
| tsurantino/roadtrip | lib/kdTree.js | JavaScript | mit | 13,331 |
// function that finds the sum of two parameters
function findSum(firstnr, secondnr){
return firstnr + secondnr;
}
//function that finds the product of two parameters
function findProduct(firstnr, secondnr){
return firstnr * secondnr;
}
/* threeOperation calls the operation parameter as a function so it's able to run and "do" different things
depending on the global function it takes as a parameter when calling it*/
function threeOperation (x, operation){
/*put console.log here so it doesn't only returns the result but also prints it in the console first:
to check if it gives the right answer when it's called*/
console.log(operation(3, x));
return operation(3, x);
}
//Call "threeOperation" with the values of "4" and "findSum"
threeOperation(4, findSum);
//Call "threeOperation" with the values of "5" and "findSum"
threeOperation(5, findSum);
//Call "threeOperation" with the values of "4" and "findProduct"
threeOperation(4, findProduct);
//Call "threeOperation" with the values of "5" and "findProduct"
threeOperation(5, findProduct); | InekeScheffers/NYCDA-individual-assignments | 09-29-2016-Anonymous-Functions-Practice/Anonymous Functions Practice.js | JavaScript | mit | 1,060 |
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
/**
* Public-Key Encrypted Session Key Packets (Tag 1)<br/>
* <br/>
* {@link http://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: A Public-Key Encrypted Session Key packet holds the session key
* used to encrypt a message. Zero or more Public-Key Encrypted Session Key
* packets and/or Symmetric-Key Encrypted Session Key packets may precede a
* Symmetrically Encrypted Data Packet, which holds an encrypted message. The
* message is encrypted with the session key, and the session key is itself
* encrypted and stored in the Encrypted Session Key packet(s). The
* Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
* Session Key packet for each OpenPGP key to which the message is encrypted.
* The recipient of the message finds a session key that is encrypted to their
* public key, decrypts the session key, and then uses the session key to
* decrypt the message.
* @requires crypto
* @requires enums
* @requires type/s2k
* @module packet/sym_encrypted_session_key
*/
var type_s2k = require('../type/s2k.js'),
enums = require('../enums.js'),
crypto = require('../crypto');
module.exports = SymEncryptedSessionKey;
/**
* @constructor
*/
function SymEncryptedSessionKey() {
this.tag = enums.packet.symEncryptedSessionKey;
this.sessionKeyEncryptionAlgorithm = null;
this.sessionKeyAlgorithm = 'aes256';
this.encrypted = null;
this.s2k = new type_s2k();
}
/**
* Parsing function for a symmetric encrypted session key packet (tag 3).
*
* @param {String} input Payload of a tag 1 packet
* @param {Integer} position Position to start reading from the input string
* @param {Integer} len
* Length of the packet or the remaining length of
* input at position
* @return {module:packet/sym_encrypted_session_key} Object representation
*/
SymEncryptedSessionKey.prototype.read = function(bytes) {
// A one-octet version number. The only currently defined version is 4.
this.version = bytes.charCodeAt(0);
// A one-octet number describing the symmetric algorithm used.
var algo = enums.read(enums.symmetric, bytes.charCodeAt(1));
// A string-to-key (S2K) specifier, length as defined above.
var s2klength = this.s2k.read(bytes.substr(2));
// Optionally, the encrypted session key itself, which is decrypted
// with the string-to-key object.
var done = s2klength + 2;
if (done < bytes.length) {
this.encrypted = bytes.substr(done);
this.sessionKeyEncryptionAlgorithm = algo;
} else
this.sessionKeyAlgorithm = algo;
};
SymEncryptedSessionKey.prototype.write = function() {
var algo = this.encrypted === null ?
this.sessionKeyAlgorithm :
this.sessionKeyEncryptionAlgorithm;
var bytes = String.fromCharCode(this.version) +
String.fromCharCode(enums.write(enums.symmetric, algo)) +
this.s2k.write();
if (this.encrypted !== null)
bytes += this.encrypted;
return bytes;
};
/**
* Decrypts the session key (only for public key encrypted session key
* packets (tag 1)
*
* @return {String} The unencrypted session key
*/
SymEncryptedSessionKey.prototype.decrypt = function(passphrase) {
var algo = this.sessionKeyEncryptionAlgorithm !== null ?
this.sessionKeyEncryptionAlgorithm :
this.sessionKeyAlgorithm;
var length = crypto.cipher[algo].keySize;
var key = this.s2k.produce_key(passphrase, length);
if (this.encrypted === null) {
this.sessionKey = key;
} else {
var decrypted = crypto.cfb.decrypt(
this.sessionKeyEncryptionAlgorithm, key, this.encrypted, true);
this.sessionKeyAlgorithm = enums.read(enums.symmetric,
decrypted[0].keyCodeAt());
this.sessionKey = decrypted.substr(1);
}
};
SymEncryptedSessionKey.prototype.encrypt = function(passphrase) {
var length = crypto.getKeyLength(this.sessionKeyEncryptionAlgorithm);
var key = this.s2k.produce_key(passphrase, length);
var private_key = String.fromCharCode(
enums.write(enums.symmetric, this.sessionKeyAlgorithm)) +
crypto.getRandomBytes(
crypto.getKeyLength(this.sessionKeyAlgorithm));
this.encrypted = crypto.cfb.encrypt(
crypto.getPrefixRandom(this.sessionKeyEncryptionAlgorithm),
this.sessionKeyEncryptionAlgorithm, key, private_key, true);
};
/**
* Fix custom types after cloning
*/
SymEncryptedSessionKey.prototype.postCloneTypeFix = function() {
this.s2k = type_s2k.fromClone(this.s2k);
};
| openilabs/crypto | node_modules/openpgp/src/packet/sym_encrypted_session_key.js | JavaScript | mit | 5,248 |
"""
train supervised classifier with what's cooking recipe data
objective - determine recipe type categorical value from 20
"""
import time
from features_bow import *
from features_word2vec import *
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.cross_validation import cross_val_score
""" main entry method """
def main(use_idf=False, random_state=None, std=False, n_jobs=-1, verbose=2):
wc_idf_map = None
if use_idf:
# ingredients inverse document frequencies
wc_components = build_tfidf_wc(verbose=(verbose > 0))
wc_idf = wc_components['model'].idf_
wc_idf_words = wc_components['model'].get_feature_names()
wc_idf_map = dict(zip(wc_idf_words, wc_idf))
# word2vec recipe feature vectors
wc_components = build_word2vec_wc(feature_vec_size=120, avg=True, idf=wc_idf_map, verbose=(verbose > 0))
y_train = wc_components['train']['df']['cuisine_code'].as_matrix()
X_train = wc_components['train']['features_matrix']
# standardize features aka mean ~ 0, std ~ 1
if std:
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
# random forest supervised classifier
time_0 = time.time()
clf = RandomForestClassifier(n_estimators=100, max_depth=None,
n_jobs=n_jobs, random_state=random_state, verbose=verbose)
# perform cross validation
cv_n_fold = 8
print 'cross validating %s ways...' % cv_n_fold
scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=-1)
print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2)
time_1 = time.time()
elapsed_time = time_1 - time_0
print 'cross validation took %.3f seconds' % elapsed_time
if __name__ == '__main__':
main()
| eifuentes/kaggle_whats_cooking | train_word2vec_rf.py | Python | mit | 1,909 |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class SettingController
*
* @author The scaffold-interface created at 2016-08-25 01:07:35am
* @link https://github.com/amranidev/scaffold-interface
*/
class Setting extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'avatars';
}
| UnrulyNatives/helpers-for-laravel-projects | src/unstarter_models/Avatar.php | PHP | mit | 408 |
package net.robobalasko.dfa.gui;
import net.robobalasko.dfa.core.Automaton;
import net.robobalasko.dfa.core.exceptions.NodeConnectionMissingException;
import net.robobalasko.dfa.core.exceptions.StartNodeMissingException;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame {
private final Automaton automaton;
private JButton checkButton;
public MainFrame(final Automaton automaton) throws HeadlessException {
super("DFA Simulator");
this.automaton = automaton;
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel containerPanel = new JPanel();
containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS));
containerPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
setContentPane(containerPanel);
CanvasPanel canvasPanel = new CanvasPanel(this, automaton);
containerPanel.add(canvasPanel);
JPanel checkInputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
containerPanel.add(checkInputPanel);
final JTextField inputText = new JTextField(40);
Document document = inputText.getDocument();
document.addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
checkButton.setEnabled(e.getDocument().getLength() > 0);
}
@Override
public void removeUpdate(DocumentEvent e) {
checkButton.setEnabled(e.getDocument().getLength() > 0);
}
@Override
public void changedUpdate(DocumentEvent e) {
checkButton.setEnabled(e.getDocument().getLength() > 0);
}
});
checkInputPanel.add(inputText);
checkButton = new JButton("Check");
checkButton.setEnabled(false);
checkButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
JOptionPane.showMessageDialog(MainFrame.this,
automaton.acceptsString(inputText.getText())
? "Input accepted."
: "Input rejected.");
} catch (StartNodeMissingException ex) {
JOptionPane.showMessageDialog(MainFrame.this, "Missing start node.");
} catch (NodeConnectionMissingException ex) {
JOptionPane.showMessageDialog(MainFrame.this, "Not a good string. Automat doesn't accept it.");
}
}
});
checkInputPanel.add(checkButton);
setResizable(false);
setVisible(true);
pack();
}
}
| robobalasko/DFA-Simulator | src/main/java/net/robobalasko/dfa/gui/MainFrame.java | Java | mit | 3,007 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "init.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
// Return average network hashes per second based on the last 'lookup' blocks,
// or from the last difficulty change if 'lookup' is nonpositive.
// If 'height' is nonnegative, compute the estimate at the time when a given block was found.
Value GetNetworkHashPS(int lookup, int height) {
CBlockIndex *pb = pindexBest;
if (height >= 0 && height < nBestHeight)
pb = FindBlockByHeight(height);
if (pb == NULL || !pb->nHeight)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0)
lookup = pb->nHeight % 2016 + 1;
// If lookup is larger than chain, then set it to chain length.
if (lookup > pb->nHeight)
lookup = pb->nHeight;
CBlockIndex *pb0 = pb;
int64 minTime = pb0->GetBlockTime();
int64 maxTime = minTime;
for (int i = 0; i < lookup; i++) {
pb0 = pb0->pprev;
int64 time = pb0->GetBlockTime();
minTime = std::min(time, minTime);
maxTime = std::max(time, maxTime);
}
// In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
if (minTime == maxTime)
return 0;
uint256 workDiff = pb->nChainWork - pb0->nChainWork;
int64 timeDiff = maxTime - minTime;
return (boost::int64_t)(workDiff.getdouble() / timeDiff);
}
Value getnetworkhashps(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getnetworkhashps [blocks] [height]\n"
"Returns the estimated network hashes per second based on the last 120 blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
"Pass in [height] to estimate the network speed at the time when a certain block was found.");
return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
}
// Key used by getwork/getblocktemplate miners.
// Allocated in InitRPCMining, free'd in ShutdownRPCMining
static CReserveKey* pMiningKey = NULL;
void InitRPCMining()
{
if (!pwalletMain)
return;
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
}
void ShutdownRPCMining()
{
if (!pMiningKey)
return;
delete pMiningKey; pMiningKey = NULL;
}
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
if (!pMiningKey)
return false;
return GetBoolArg("-gen");
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
assert(pwalletMain != NULL);
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Riestercoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Riestercoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
printf("%s\n", merkleh.ToString().c_str());
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0];
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Riestercoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Riestercoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
assert(pwalletMain != NULL);
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Riestercoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Riestercoin is downloading blocks...");
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblocktemplate)
{
delete pblocktemplate;
pblocktemplate = NULL;
}
CScript scriptDummy = CScript() << OP_TRUE;
pblocktemplate = CreateNewBlock(scriptDummy);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
Array deps;
BOOST_FOREACH (const CTxIn &in, tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = i - 1;
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock pblock;
try {
ssBlock >> pblock;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
CValidationState state;
bool fAccepted = ProcessBlock(state, NULL, &pblock);
if (!fAccepted)
return "rejected"; // TODO: report validation state
return Value::null;
}
| frontibit/riestercoin | src/rpcmining.cpp | C++ | mit | 21,117 |
#ifndef _PARSER_HPP
#define _PARSER_HPP
#include <cassert>
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include "toyobj.hpp"
#include "lexer.hpp"
#include "toy.hpp"
#include "ast.hpp"
class ParserContext {
public:
explicit ParserContext(LexerContext &lexer)
: lexer_(lexer) { lexer_.fetchtok(); }
AST *parse_ast(bool);
private:
Statement *parse_statement();
Statement *parse_while();
Statement *parse_if();
Statement *parse_return();
Statement *parse_def();
Expression *parse_expression();
Expression *parse_primary();
Expression *parse_binary_op_expression(Expression*, int);
Expression *parse_paren_expression();
Expression *parse_number();
Expression *parse_string();
Expression *parse_word_expression();
AST *parse_block();
int get_prec(TokenType) const;
inline const Token *curtok() { return lexer_.curtok(); }
inline void eat_token(TokenType type) {
if (type != curtok()->type()) {
std::cout << "I was expecting " << Token::token_type_name(type) << " but got " << curtok()->name() << std::endl;
exit(1);
}
lexer_.fetchtok();
}
LexerContext &lexer_;
DISALLOW_COPY_AND_ASSIGN(ParserContext);
};
#endif
| helgefmi/Toy | src/parser.hpp | C++ | mit | 1,288 |
require 'aws-sdk'
require 'awspec/resource_reader'
require 'awspec/helper/finder'
module Awspec::Type
class Base
include Awspec::Helper::Finder
include Awspec::BlackListForwardable
attr_accessor :account
def resource_via_client
raise 'this method must be override!'
end
def to_s
type = self.class.name.demodulize.underscore
"#{type} '#{@display_name}'"
end
def inspect
to_s
end
def self.tags_allowed
define_method :has_tag? do |key, value|
begin
tags = resource_via_client.tags
rescue NoMethodError
tags = resource_via_client.tag_set
end
return false unless tags
tags.any? { |t| t['key'] == key && t['value'] == value }
end
end
def method_missing(name)
name_str = name.to_s if name.class == Symbol
describe = name_str.tr('-', '_').to_sym
if !resource_via_client.nil? && resource_via_client.members.include?(describe)
resource_via_client[describe]
else
super unless self.respond_to?(:resource)
method_missing_via_black_list(name, delegate_to: resource)
end
end
end
end
| AgarFu/awspec | lib/awspec/type/base.rb | Ruby | mit | 1,180 |
export default {
FETCH_TAGS_PENDING: Symbol("FETCH_TAGS_PENDING"),
FETCH_TAGS_SUCCESS: Symbol("FETCH_TAGS_SUCCESS"),
FETCH_TAGS_FAILURE: Symbol("FETCH_TAGS_FAILURE"),
FILTER_TAGS: Symbol("FILTER_TAGS"),
ORDER_TAGS: Symbol("ORDER_TAGS")
};
| danjac/photoshare | ui/actionTypes/tags.js | JavaScript | mit | 251 |
<?php
/**
* summary
*/
class Product extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('product_model');
}
function index(){
$total = $this->product_model->get_total();
$this->data['total'] = $total;
//load thu vien phan trang
$this->load->library('pagination');
$config = array();
$config['base_url'] = admin_url('product/index');
$config['total_rows'] = $total;
$config['per_page'] = 5;
$config['uri_segment'] = 4;
$config['next_link'] = "Trang ke tiep";
$config['prev_link'] = "Trang truoc";
$this->pagination->initialize($config);
/*end phan trang*/
/*load trang*/
$segment = $this->uri->segment(4);
$segment = intval($segment);
$input = array();
$input['limit'] = array($config['per_page'],$segment);
/*loc theo id*/
$id = $this->input->get('id');
$id = intval($id);
$input['where'] = array();
if ($id > 0) {
$input['where']['id'] = $id;
}
/*loc theo ten*/
$name = $this->input->get('name');
if ($name) {
$input['like'] = array('name',$name);
}
/*loc theo danh muc*/
$catalog_id = $this->input->get('catalog');
$catalog_id = intval($catalog_id);
if ($catalog_id > 0) {
$input['where']['catalog_id'] = $catalog_id;
}
$list = $this->product_model->get_list($input);
$this->data['list'] = $list;
/* end loc */
/* end load phan trang*/
/*lay danh muc san pham*/
$this->load->model('catalog_model');
$input = array();
$input['where'] = array('parent_id'=> 0);
$catalogs = $this->catalog_model->get_list($input);
foreach ($catalogs as $row) {
$input['where'] = array('parent_id'=> $row->id);
$subs = $this->catalog_model->get_list($input);
$row->subs = $subs;
}
$this->data['catalogs'] = $catalogs;
/*end lay danh muc*/
$message = $this->session->flashdata('message');
$this->data['message'] = $message;
$this->data['temp'] = 'admin/product/index';
$this->load->view('admin/main', $this->data);
}
function add(){
/*lay danh muc san pham*/
$this->load->model('catalog_model');
$input = array();
$input['where'] = array('parent_id'=> 0);
$catalogs = $this->catalog_model->get_list($input);
foreach ($catalogs as $row) {
$input['where'] = array('parent_id'=> $row->id);
$subs = $this->catalog_model->get_list($input);
$row->subs = $subs;
}
$this->data['catalogs'] = $catalogs;
/*end lay danh muc*/
$message = $this->session->flashdata('message');
$this->data['message'] = $message;
$this->load->library('form_validation');
$this->load->helper('form');
//neu ma co du lieu post len thi kiem tra
if($this->input->post())
{
$this->form_validation->set_rules('name', 'Tên', 'required');
$this->form_validation->set_rules('price', 'Gia', 'required');
$this->form_validation->set_rules('catalog', 'Thể loại', 'required');
//nhập liệu chính xác
if($this->form_validation->run())
{
//them vao csdl
$name = $this->input->post('name');
$price = $this->input->post('price');
$price = str_replace(',', '', $price);
$discount = $this->input->post('discount');
$discount = str_replace(',', '', $discount);
/*up hinh anh dai dien*/
$this->load->library('upload_library');
$upload_path = './upload/product';
$upload_data = $this->upload_library->upload($upload_path,'image' );
$image_link = '';
if (isset($upload_data['file_name']))
{
$image_link = $upload_data['file_name'];
}
/*Upload hinh anh kem theo*/
$image_list = array();
$image_list = $this->upload_library->upload_file($upload_path, 'image_list');
$image_list_json = json_encode($image_list);
$data = array(
'name' => $name,
'price' => $price,
'discount' => $discount,
'warranty' => $this->input->post('warranty'),
'gifts' => $this->input->post('gitfs'),
'meta_desc' => $this->input->post('meta_desc'),
'meta_key' => $this->input->post('meta_key'),
'site_title' => $this->input->post('site_title'),
'content' => $this->input->post('content'),
'catalog_id' => $this->input->post('catalog')
);
if($image_link != '')
{
$data['image_link'] = $image_link;
}
if(!empty($image_list))
{
$data['image_list'] = $image_list_json;
}
if($this->product_model->create($data))
{
//tạo ra nội dung thông báo
$this->session->set_flashdata('message', 'Thêm mới san pham thành công');
}else{
$this->session->set_flashdata('message', 'Không thêm được');
}
//chuyen tới trang danh sách san pham
redirect(admin_url('product'));
}
}
$this->data['temp'] = 'admin/product/add';
$this->load->view('admin/main', $this->data);
}
function edit()
{
$id = $this->uri->rsegment('3');
$product = $this->product_model->get_info($id);
if(!$product)
{
//tạo ra nội dung thông báo
$this->session->set_flashdata('message', 'Không tồn tại sản phẩm này');
redirect(admin_url('product'));
}
$this->data['product'] = $product;
//lay danh sach danh muc san pham
$this->load->model('catalog_model');
$input = array();
$input['where'] = array('parent_id' => 0);
$catalogs = $this->catalog_model->get_list($input);
foreach ($catalogs as $row)
{
$input['where'] = array('parent_id' => $row->id);
$subs = $this->catalog_model->get_list($input);
$row->subs = $subs;
}
$this->data['catalogs'] = $catalogs;
//load thư viện validate dữ liệu
$this->load->library('form_validation');
$this->load->helper('form');
//neu ma co du lieu post len thi kiem tra
if($this->input->post())
{
$this->form_validation->set_rules('name', 'Tên', 'required');
$this->form_validation->set_rules('catalog', 'Thể loại', 'required');
$this->form_validation->set_rules('price', 'Giá', 'required');
//nhập liệu chính xác
if($this->form_validation->run())
{
//them vao csdl
$name = $this->input->post('name');
$catalog_id = $this->input->post('catalog');
$price = $this->input->post('price');
$price = str_replace(',', '', $price);
$discount = $this->input->post('discount');
$discount = str_replace(',', '', $discount);
//lay ten file anh minh hoa duoc update len
$this->load->library('upload_library');
$upload_path = './upload/product';
$upload_data = $this->upload_library->upload($upload_path, 'image');
$image_link = '';
if(isset($upload_data['file_name']))
{
$image_link = $upload_data['file_name'];
}
//upload cac anh kem theo
$image_list = array();
$image_list = $this->upload_library->upload_file($upload_path, 'image_list');
$image_list_json = json_encode($image_list);
//luu du lieu can them
$data = array(
'name' => $name,
'catalog_id' => $catalog_id,
'price' => $price,
'discount' => $discount,
'warranty' => $this->input->post('warranty'),
'gifts' => $this->input->post('gifts'),
'site_title' => $this->input->post('site_title'),
'meta_desc' => $this->input->post('meta_desc'),
'meta_key' => $this->input->post('meta_key'),
'content' => $this->input->post('content'),
);
if($image_link != '')
{
$data['image_link'] = $image_link;
}
if(!empty($image_list))
{
$data['image_list'] = $image_list_json;
}
//them moi vao csdl
if($this->product_model->update($product->id, $data))
{
//tạo ra nội dung thông báo
$this->session->set_flashdata('message', 'Cập nhật dữ liệu thành công');
}else{
$this->session->set_flashdata('message', 'Không cập nhật được');
}
//chuyen tới trang danh sách
redirect(admin_url('product'));
}
}
//load view
$this->data['temp'] = 'admin/product/edit';
$this->load->view('admin/main', $this->data);
}
function del(){
$id = $this->uri->rsegment('3');
$this->_del($id);
$this->session->set_flashdata('message', 'Xoa thanh cong ');
redirect(admin_url('product'));
}
function delete_all(){
$ids = $this->input->post('ids');
foreach ($ids as $id) {
$this->_del($id);
}
$this->session->set_flashdata('message', 'Xoa thanh cong cac san pham ');
redirect(admin_url('product'));
}
private function _del($id){
$product = $this->product_model->get_info($id);
if(!$product)
{
//tạo ra nội dung thông báo
$this->session->set_flashdata('message', 'Không tồn tại sản phẩm này');
redirect(admin_url('product'));
}
$this->data['product'] = $product;
$this->product_model->delete($id);
$image_link = './upload/product'.$product->image_link;
if (file_exists($image_link)) {
unlink($image_link);
}
$image_list = json_decode($product->image_list);
foreach ($image_list as $img) {
$image_link = '.upload/product'.$img;
if (file_exists($image_link)) {
unlink($image_link);
}
}
}
}
?> | mrthanhtan22/vemaybay | application/controllers/admin/Product.php | PHP | mit | 11,577 |
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import {Http, Headers} from '@angular/http';
import {Router } from '@angular/router';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
submission: FirebaseListObservable<any>;
constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase, private router: Router){
console.log("Authentication service started");
console.log(firebase.auth());
}
login(email, pass){
this.afAuth.auth.signInWithEmailAndPassword(email, pass)
.then(res => {
console.log('Nice, logging you in!!!');
this.router.navigate(['/admin']);
});
}
checkAuth(){
this.afAuth.authState.subscribe(res => {
if (res && res.uid) {
console.log('user is logged in');
return true;
} else {
console.log('user not logged in...redirecting to welcome..');
this.router.navigate(['/login']);
return false;
}
});
}
logout() {
this.afAuth.auth.signOut();
this.router.navigate(['/']);
}
}
| alimcharaniya/uniformlab-v3 | src/services/auth.service.ts | TypeScript | mit | 1,321 |
/**
*
* @function
* @param {Array|arraylike} value
* @param {Function} cmd
* @param {any} context
* @returns {?}
*/
export default function eachValue(value, cmd, context, keepReverse) {
if (value === undefined || value === null) return undefined;
const size = (0 | value.length) - 1;
for (let index = size; index > -1; index -= 1) {
const i = keepReverse ? index : size - index;
const item = value[i];
const resolve = cmd.call(context || item, item, i, value, i);
if (resolve === undefined === false) {
return resolve;
}
}
return undefined;
}
| adriancmiranda/describe-type | internal/eachValue.next.js | JavaScript | mit | 568 |
const should = require('should'),
sinon = require('sinon'),
_ = require('lodash'),
settingsCache = require('../../../../server/services/settings/cache'),
common = require('../../../../server/lib/common'),
controllers = require('../../../../server/services/routing/controllers'),
TaxonomyRouter = require('../../../../server/services/routing/TaxonomyRouter'),
RESOURCE_CONFIG = require('../../../../server/services/routing/assets/resource-config'),
sandbox = sinon.sandbox.create();
describe('UNIT - services/routing/TaxonomyRouter', function () {
let req, res, next;
beforeEach(function () {
sandbox.stub(settingsCache, 'get').withArgs('permalinks').returns('/:slug/');
sandbox.stub(common.events, 'emit');
sandbox.stub(common.events, 'on');
sandbox.spy(TaxonomyRouter.prototype, 'mountRoute');
sandbox.spy(TaxonomyRouter.prototype, 'mountRouter');
req = sandbox.stub();
res = sandbox.stub();
next = sandbox.stub();
res.locals = {};
});
afterEach(function () {
sandbox.restore();
});
it('instantiate', function () {
const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/');
should.exist(taxonomyRouter.router);
should.exist(taxonomyRouter.rssRouter);
taxonomyRouter.taxonomyKey.should.eql('tag');
taxonomyRouter.getPermalinks().getValue().should.eql('/tag/:slug/');
common.events.emit.calledOnce.should.be.true();
common.events.emit.calledWith('router.created', taxonomyRouter).should.be.true();
taxonomyRouter.mountRouter.callCount.should.eql(1);
taxonomyRouter.mountRouter.args[0][0].should.eql('/tag/:slug/');
taxonomyRouter.mountRouter.args[0][1].should.eql(taxonomyRouter.rssRouter.router());
taxonomyRouter.mountRoute.callCount.should.eql(3);
// permalink route
taxonomyRouter.mountRoute.args[0][0].should.eql('/tag/:slug/');
taxonomyRouter.mountRoute.args[0][1].should.eql(controllers.channel);
// pagination feature
taxonomyRouter.mountRoute.args[1][0].should.eql('/tag/:slug/page/:page(\\d+)');
taxonomyRouter.mountRoute.args[1][1].should.eql(controllers.channel);
// edit feature
taxonomyRouter.mountRoute.args[2][0].should.eql('/tag/:slug/edit');
taxonomyRouter.mountRoute.args[2][1].should.eql(taxonomyRouter._redirectEditOption.bind(taxonomyRouter));
});
it('fn: _prepareContext', function () {
const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/');
taxonomyRouter._prepareContext(req, res, next);
next.calledOnce.should.eql(true);
res.locals.routerOptions.should.eql({
name: 'tag',
permalinks: '/tag/:slug/',
type: RESOURCE_CONFIG.QUERY.tag.resource,
data: {tag: _.omit(RESOURCE_CONFIG.QUERY.tag, 'alias')},
filter: RESOURCE_CONFIG.TAXONOMIES.tag.filter,
context: ['tag'],
slugTemplate: true,
identifier: taxonomyRouter.identifier
});
res._route.type.should.eql('channel');
});
});
| dbalders/Ghost | core/test/unit/services/routing/TaxonomyRouter_spec.js | JavaScript | mit | 3,184 |
<?php
/*==============================================================================
* (C) Copyright 2016,2020 John J Kauflin, All rights reserved.
*----------------------------------------------------------------------------
* DESCRIPTION: Functions to validate Admin operations (i.e. check permissions
* parameters, timing, etc.)
*----------------------------------------------------------------------------
* Modification History
* 2016-04-05 JJK Added check for AddAssessments
* 2020-08-01 JJK Re-factored to use jjklogin for authentication
* 2020-12-21 JJK Re-factored to use jjklogin package
*============================================================================*/
// Define a super global constant for the log file (this will be in scope for all functions)
define("LOG_FILE", "./php.log");
require_once 'vendor/autoload.php';
// Figure out how many levels up to get to the "public_html" root folder
$webRootDirOffset = substr_count(strstr(dirname(__FILE__),"public_html"),DIRECTORY_SEPARATOR) + 1;
// Get settings and credentials from a file in a directory outside of public_html
// (assume a settings file in the "external_includes" folder one level up from "public_html")
$extIncludePath = dirname(__FILE__, $webRootDirOffset+1).DIRECTORY_SEPARATOR.'external_includes'.DIRECTORY_SEPARATOR;
require_once $extIncludePath.'hoadbSecrets.php';
require_once $extIncludePath.'jjkloginSettings.php';
// Common functions
require_once 'php_secure/commonUtil.php';
// Common database functions and table record classes
require_once 'php_secure/hoaDbCommon.php';
use \jkauflin\jjklogin\LoginAuth;
$adminRec = new AdminRec();
try {
$userRec = LoginAuth::getUserRec($cookieNameJJKLogin,$cookiePathJJKLogin,$serverKeyJJKLogin);
if ($userRec->userName == null || $userRec->userName == '') {
throw new Exception('User is NOT logged in', 500);
}
if ($userRec->userLevel < 1) {
throw new Exception('User is NOT authorized (contact Administrator)', 500);
}
$currTimestampStr = date("Y-m-d H:i:s");
//JJK test, date = 2015-04-22 19:45:09
$adminRec->result = "Not Valid";
$adminRec->message = "";
$adminRec->userName = $userRec->userName;
$adminRec->userLevel = $userRec->userLevel;
$adminLevel = $userRec->userLevel;
$action = getParamVal("action");
$fy = getParamVal("fy");
$duesAmt = strToUSD(getParamVal("duesAmt"));
if ($adminLevel < 2) {
$adminRec->message = "You do not have permissions for this function";
$adminRec->result = "Not Valid";
} else {
$adminRec->result = "Valid";
$adminRec->message = "Continue with " . $action . "?";
if ($action == "AddAssessments") {
if (empty($duesAmt) || empty($fy)) {
$adminRec->message = "You must enter Dues Amount and Fiscal Year.";
$adminRec->result = "Not Valid";
} else {
$adminRec->message = "Are you sure you want to add assessment for Fiscal Year " . $fy . ' with Dues Amount of $' . $duesAmt .'?';
}
} else if ($action == "MarkMailed") {
$adminRec->message = "Continue to record Communication to mark paper notices as mailed?";
} else if ($action == "DuesEmailsTest") {
$adminRec->message = "Continue with TEST email of Dues Notices to show the list and send the first one to the test address?";
} else if ($action == "DuesEmails") {
$adminRec->message = "Continue with email of Dues Notices? This will create a Communication record for each email to send";
}
}
echo json_encode($adminRec);
} catch(Exception $e) {
//error_log(date('[Y-m-d H:i] '). "in " . basename(__FILE__,".php") . ", Exception = " . $e->getMessage() . PHP_EOL, 3, LOG_FILE);
$adminRec->message = $e->getMessage();
$adminRec->result = "Not Valid";
echo json_encode($adminRec);
/*
echo json_encode(
array(
'error' => $e->getMessage(),
'error_code' => $e->getCode()
)
);
*/
}
?>
| jkauflin/hoadb | adminValidate.php | PHP | mit | 3,993 |
<h1>Access Denied</h1>
<p>You have logged in correctly, but you have tried to access a page without a high enough level of security clearance.</p> | tonymarklove/wool | views/user/admin_denied.php | PHP | mit | 147 |
import React from 'react';
import $ from 'jquery';
import _ from 'lodash';
import Block from './Block';
export default class BlockGrid extends React.Component {
constructor() {
super();
this.setDefaults();
this.setContainerWidth = this.setContainerWidth.bind(this);
this.handleWindowResize = this.handleWindowResize.bind(this);
this.resizeTimer = null;
// throttle call to this func whenever an image is loaded
this.throttledSetContainerWidth = _.throttle(this.setContainerWidth, 500);
}
setDefaults(){
this.blockWidth = 260; // initial desired block width
this.borderWidth = 5;
this.wrapperWidth = 0;
this.colCount = 0;
this.blocks = [];
this.blockCount = 0;
}
handleWindowResize(){
clearTimeout(this.resizeTimer);
const _this = this;
this.resizeTimer = setTimeout(function() {
$('.block-container').css('width', '100%');
_this.setDefaults();
_this.setContainerWidth();
// above code computes false height of blocks
// so as a lose patch re-position blocks after 500 ms
setTimeout(_this.setContainerWidth, 700);
}, 200);
}
componentDidMount(){
this.setContainerWidth();
/*
height of each block is measured with an error the first time so there are some
space between blocks specially the top values of the grid.
Only solution seems like re calculating positions of the block after few seconds
*/
// _.delay(this.setContainerWidth, 3000);
// reset all blocks when window resized
$(window).resize(this.handleWindowResize);
}
componentWillReceiveProps(nextProps){
// after clicking Load More there will be newProps here
// Re calculate block positions so no error occurs when there are
// all image less blocks
// _.delay(this.setContainerWidth, 2000);
}
componentDidUpdate(prevProps, prevState){
if(this.blockCount != this.props.data.length){
this.setDefaults();
this.setContainerWidth();
}
}
componentWillUnmount(){
$(window).off("resize", this.handleWindowResize);
}
setContainerWidth(){
// setContainerWidth only first time we recieve BlockList data
if(this.wrapperWidth == 0){
this.wrapperWidth = $('.block-container').outerWidth();
this.colCount = Math.round(this.wrapperWidth/this.blockWidth);
$('.block').css('width', this.blockWidth);
this.blockCount = document.getElementsByClassName('block').length;
if(this.blockCount < this.colCount){
this.wrapperWidth = (this.blockWidth*this.blockCount) - ( (this.blockCount - 1) * this.borderWidth);
this.colCount = this.blockCount;
} else {
this.wrapperWidth = (this.blockWidth*this.colCount) - ( (this.colCount - 1) * this.borderWidth);
}
$('.block-container').css('width', this.wrapperWidth);
}
// if wrapperWidth is already calculated than just reset block positions
for( var i = 0; i < this.colCount; i++ )
this.blocks[i] = 0;
this.setBlocks();
}
setBlocks() {
const component = this;
$('.block').each(function(){
var min = Math.min.apply(Math, component.blocks);
var index = $.inArray(min, component.blocks);
var left = index * (component.blockWidth - component.borderWidth) - component.borderWidth;
// for the first blocks that needs to overlap container border
if(left == 0)
left = - component.borderWidth;
// start with overlap on top container border
var top = min + 10 - component.borderWidth;
$(this).css({
'top' : top + 'px',
'left' : left + 'px'
});
component.blocks[index] = top + this.offsetHeight;
});
// set wrapper height
var wrapperHeight = Math.max.apply(Math, this.blocks);
wrapperHeight += this.borderWidth; // block borders
$(".block-container").css("height",wrapperHeight + 'px');
}
renderBlocks() {
const { data } = this.props;
return data.map((pin) => {
return <Block {...pin} key={pin._id} loadHandler={this.throttledSetContainerWidth}/>;
});
}
render() {
return(
<div class="row">
<div class="col-sm-offset-2 col-sm-8 col-xs-offset-1 col-xs-10">
<div class="block-container">
{ this.renderBlocks() }
</div>
</div>
</div>
);
}
}
| Dishant15/TechIntrest | frontend/react/components/BlockGrid.js | JavaScript | mit | 4,139 |
<?php
namespace Eni\MainBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Eni\MainBundle\Entity\Question;
use Eni\MainBundle\Entity\ReponseProposee;
class LoadReponseProposeeData extends AbstractFixture implements OrderedFixtureInterface {
public function getOrder() {
return 6;
}
public function load(ObjectManager $oManager) {
//
//Question1
//
$oQuestion1 = $this->getReference('question1');
/* @var $oQuestion1 Question */
$tReponsesProposees = [
['enonce' => 'Dim', 'valide' => true],
['enonce' => 'Public', 'valide' => false],
['enonce' => 'Aucun mot-clé', 'valide' => false],
];
foreach ($tReponsesProposees as $tReponseProposee) {
$oReponseProposee = new ReponseProposee();
$oReponseProposee
->setQuestion($oQuestion1)
->setEnonce($tReponseProposee['enonce'])
->setValide($tReponseProposee['valide']);
$oQuestion1->addReponsesProposee($oReponseProposee);
$oManager->persist($oReponseProposee);
}
//
//Question2
//
$oQuestion2 = $this->getReference('question2');
/* @var $oQuestion2 Question */
$tReponsesProposees2 = [
['enonce' => 'VS refusera de compiler la dernière ligne de code', 'valide' => false],
['enonce' => ' La valeur de Res restera à True', 'valide' => false],
['enonce' => 'La valeur de Res sera False', 'valide' => true],
['enonce' => 'Res = 4', 'valide' => false],
];
foreach ($tReponsesProposees2 as $tReponseProposee) {
$oReponseProposee = new ReponseProposee();
$oReponseProposee
->setQuestion($oQuestion2)
->setEnonce($tReponseProposee['enonce'])
->setValide($tReponseProposee['valide']);
$oQuestion2->addReponsesProposee($oReponseProposee);
$oManager->persist($oReponseProposee);
}
//
//Question3
//
$oQuestion3 = $this->getReference('question3');
/* @var $oQuestion3 Question */
$tReponsesProposees3 = [
['enonce' => 'Un', 'valide' => false],
['enonce' => 'Deux', 'valide' => true],
['enonce' => 'Trois', 'valide' => false],
];
foreach ($tReponsesProposees3 as $tReponseProposee) {
$oReponseProposee = new ReponseProposee();
$oReponseProposee
->setQuestion($oQuestion3)
->setEnonce($tReponseProposee['enonce'])
->setValide($tReponseProposee['valide']);
$oQuestion3->addReponsesProposee($oReponseProposee);
$oManager->persist($oReponseProposee);
}
//
//Question4
//
$oQuestion4 = $this->getReference('question4');
/* @var $oQuestion4 Question */
$tReponsesProposees4 = [
['enonce' => 'Vrai', 'valide' => true],
['enonce' => 'Faux', 'valide' => false],
];
foreach ($tReponsesProposees4 as $tReponseProposee) {
$oReponseProposee = new ReponseProposee();
$oReponseProposee
->setQuestion($oQuestion4)
->setEnonce($tReponseProposee['enonce'])
->setValide($tReponseProposee['valide']);
$oQuestion4->addReponsesProposee($oReponseProposee);
$oManager->persist($oReponseProposee);
}
$oManager->flush();
}
}
| mneute/qcm-eni | src/Eni/MainBundle/DataFixtures/ORM/LoadReponseProposeeData.php | PHP | mit | 3,106 |
package com.exasol.adapter.dialects.bigquery;
import java.sql.Connection;
import java.sql.Types;
import com.exasol.adapter.AdapterProperties;
import com.exasol.adapter.dialects.IdentifierConverter;
import com.exasol.adapter.jdbc.BaseColumnMetadataReader;
import com.exasol.adapter.jdbc.JdbcTypeDescription;
import com.exasol.adapter.metadata.DataType;
/**
* This class implements BigQuery-specific reading of column metadata.
*/
public class BigQueryColumnMetadataReader extends BaseColumnMetadataReader {
/**
* Create a new instance of the {@link BigQueryColumnMetadataReader}.
*
* @param connection connection to the remote data source
* @param properties user-defined adapter properties
* @param identifierConverter converter between source and Exasol identifiers
*/
public BigQueryColumnMetadataReader(final Connection connection, final AdapterProperties properties,
final IdentifierConverter identifierConverter) {
super(connection, properties, identifierConverter);
}
@Override
public DataType mapJdbcType(final JdbcTypeDescription jdbcTypeDescription) {
if (jdbcTypeDescription.getJdbcType() == Types.TIME) {
return DataType.createVarChar(30, DataType.ExaCharset.UTF8);
}
return super.mapJdbcType(jdbcTypeDescription);
}
}
| EXASOL/virtual-schemas | src/main/java/com/exasol/adapter/dialects/bigquery/BigQueryColumnMetadataReader.java | Java | mit | 1,364 |
using System;
using Windows.Devices.Enumeration;
using Windows.Devices.Spi;
using Windows.Foundation.Metadata;
namespace ABElectronics_Win10IOT_Libraries
{
/// <summary>
/// Class for accessing the ADCDAC Pi from AB Electronics UK.
/// </summary>
public class ADCDACPi : IDisposable
{
private const string SPI_CONTROLLER_NAME = "SPI0";
private const Int32 ADC_CHIP_SELECT_LINE = 0; // ADC on SPI channel select CE0
private const Int32 DAC_CHIP_SELECT_LINE = 1; // ADC on SPI channel select CE1
private SpiDevice adc;
private double ADCReferenceVoltage = 3.3;
private SpiDevice dac;
/// <summary>
/// Event triggers when a connection is established.
/// </summary>
public bool IsConnected { get; private set; }
// Flag: Has Dispose already been called?
bool disposed = false;
// Instantiate a SafeHandle instance.
System.Runtime.InteropServices.SafeHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(IntPtr.Zero, true);
/// <summary>
/// Open a connection to the ADCDAC Pi.
/// </summary>
public async void Connect()
{
if (IsConnected)
{
return; // Already connected
}
if(!ApiInformation.IsTypePresent("Windows.Devices.Spi.SpiDevice"))
{
return; // This system does not support this feature: can't connect
}
try
{
// Create SPI initialization settings for the ADC
var adcsettings =
new SpiConnectionSettings(ADC_CHIP_SELECT_LINE)
{
ClockFrequency = 10000000, // SPI clock frequency of 10MHz
Mode = SpiMode.Mode0
};
var spiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME); // Find the selector string for the SPI bus controller
var devicesInfo = await DeviceInformation.FindAllAsync(spiAqs); // Find the SPI bus controller device with our selector string
if (devicesInfo.Count == 0)
{
return; // Controller not found
}
adc = await SpiDevice.FromIdAsync(devicesInfo[0].Id, adcsettings); // Create an ADC connection with our bus controller and SPI settings
// Create SPI initialization settings for the DAC
var dacSettings =
new SpiConnectionSettings(DAC_CHIP_SELECT_LINE)
{
ClockFrequency = 2000000, // SPI clock frequency of 20MHz
Mode = SpiMode.Mode0
};
dac = await SpiDevice.FromIdAsync(devicesInfo[0].Id, dacSettings); // Create a DAC connection with our bus controller and SPI settings
IsConnected = true; // connection established, set IsConnected to true.
// Fire the Connected event handler
Connected?.Invoke(this, EventArgs.Empty);
}
/* If initialization fails, display the exception and stop running */
catch (Exception ex)
{
IsConnected = false;
throw new Exception("SPI Initialization Failed", ex);
}
}
/// <summary>
/// Event occurs when connection is made.
/// </summary>
public event EventHandler Connected;
/// <summary>
/// Read the voltage from the selected <paramref name="channel" /> on the ADC.
/// </summary>
/// <param name="channel">1 or 2</param>
/// <returns>voltage</returns>
public double ReadADCVoltage(byte channel)
{
if (channel < 1 || channel > 2)
{
throw new ArgumentOutOfRangeException(nameof(channel));
}
var raw = ReadADCRaw(channel);
var voltage = ADCReferenceVoltage / 4096 * raw; // convert the raw value into a voltage based on the reference voltage.
return voltage;
}
/// <summary>
/// Read the raw value from the selected <paramref name="channel" /> on the ADC.
/// </summary>
/// <param name="channel">1 or 2</param>
/// <returns>Integer</returns>
public int ReadADCRaw(byte channel)
{
if (channel < 1 || channel > 2)
{
throw new ArgumentOutOfRangeException(nameof(channel));
}
CheckConnected();
var writeArray = new byte[] { 0x01, (byte) ((1 + channel) << 6), 0x00}; // create the write bytes based on the input channel
var readBuffer = new byte[3]; // this holds the output data
adc.TransferFullDuplex(writeArray, readBuffer); // transfer the adc data
var ret = (short) (((readBuffer[1] & 0x0F) << 8) + readBuffer[2]); // combine the two bytes into a single 16bit integer
return ret;
}
/// <summary>
/// Set the reference <paramref name="voltage" /> for the analogue to digital converter.
/// The ADC uses the raspberry pi 3.3V power as a <paramref name="voltage" /> reference
/// so using this method to set the reference to match the exact output
/// <paramref name="voltage" /> from the 3.3V regulator will increase the accuracy of
/// the ADC readings.
/// </summary>
/// <param name="voltage">double</param>
public void SetADCrefVoltage(double voltage)
{
CheckConnected();
if (voltage < 0.0 || voltage > 7.0)
{
throw new ArgumentOutOfRangeException(nameof(voltage), "Reference voltage must be between 0.0V and 7.0V.");
}
ADCReferenceVoltage = voltage;
}
/// <summary>
/// Set the <paramref name="voltage" /> for the selected channel on the DAC.
/// </summary>
/// <param name="channel">1 or 2</param>
/// <param name="voltage">Voltage can be between 0 and 2.047 volts</param>
public void SetDACVoltage(byte channel, double voltage)
{
// Check for valid channel and voltage variables
if (channel < 1 || channel > 2)
{
throw new ArgumentOutOfRangeException();
}
if (voltage >= 0.0 && voltage < 2.048)
{
var rawval = Convert.ToInt16(voltage / 2.048 * 4096); // convert the voltage into a raw value
SetDACRaw(channel, rawval);
}
else
{
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Set the raw <paramref name="value" /> from the selected <paramref name="channel" /> on the DAC.
/// </summary>
/// <param name="channel">1 or 2</param>
/// <param name="value">Value between 0 and 4095</param>
public void SetDACRaw(byte channel, short value)
{
CheckConnected();
if (channel < 1 || channel > 2)
{
throw new ArgumentOutOfRangeException();
}
// split the raw value into two bytes and send it to the DAC.
var lowByte = (byte) (value & 0xff);
var highByte = (byte) (((value >> 8) & 0xff) | ((channel - 1) << 7) | (0x1 << 5) | (1 << 4));
var writeBuffer = new [] { highByte, lowByte};
dac.Write(writeBuffer);
}
private void CheckConnected()
{
if (!IsConnected)
{
throw new InvalidOperationException("Not connected. You must call .Connect() first.");
}
}
/// <summary>
/// Dispose of the resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected implementation of Dispose pattern
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
adc?.Dispose();
adc = null;
dac?.Dispose();
dac = null;
IsConnected = false;
}
// Free any unmanaged objects here.
//
disposed = true;
}
}
} | abelectronicsuk/ABElectronics_Win10IOT_Libraries | ABElectronics_Win10IOT_Libraries/ADCDACPi.cs | C# | mit | 8,804 |
var system = require('system');
var args = system.args;
var url = "http://"+args[1],
filename = args[2]+".png",
timeout = args[3],
savePath = args[4],
page = require('webpage').create();
//setTimeout(function(){phantom.exit();}, timeout)
page.viewportSize = { width: 1200, height: 700 };
page.clipRect = { top: 0, left: 0, width: 1200, height: 700 };
var f = false;
page.onLoadFinished = function(status) {
console.log('Status: ' + status);
setTimeout(function(){
render(page);
phantom.exit();
}, 15000)
};
page.onResourceReceived = function(response) {
if (response.url === url && !f) {
setTimeout(function(){
render(page);
phantom.exit();
}, 15000)
f = true
}
};
function render(page) {
var resPath
if (savePath == "") {
resPath = filename
} else {
resPath = savePath + "/" + filename
}
page.render(resPath)
}
console.log("start get " + url)
page.open(url, function() {
}); | zhuharev/shot | assets/rasterize.js | JavaScript | mit | 936 |
class SiteController < ApplicationController
skip_before_filter :verify_authenticity_token
no_login_required
cattr_writer :cache_timeout
def self.cache_timeout
@@cache_timeout ||= 5.minutes
end
def show_page
url = params[:url]
if Array === url
url = url.join('/')
else
url = url.to_s
end
if @page = find_page(url)
batch_page_status_refresh if (url == "/" || url == "")
process_page(@page)
set_cache_control
@performed_render ||= true
else
render :template => 'site/not_found', :status => 404
end
rescue Page::MissingRootPageError
redirect_to welcome_url
end
private
def batch_page_status_refresh
@changed_pages = []
@pages = Page.find(:all, :conditions => {:status_id => 90})
@pages.each do |page|
if page.published_at <= Time.now
page.status_id = 100
page.save
@changed_pages << page.id
end
end
expires_in nil, :private=>true, "no-cache" => true if @changed_pages.length > 0
end
def set_cache_control
if (request.head? || request.get?) && @page.cache? && live?
expires_in self.class.cache_timeout, :public => true, :private => false
else
expires_in nil, :private => true, "no-cache" => true
headers['ETag'] = ''
end
end
def find_page(url)
found = Page.find_by_url(url, live?)
found if found and (found.published? or dev?)
end
def process_page(page)
page.process(request, response)
end
def dev?
if dev_host = @config['dev.host']
request.host == dev_host
else
request.host =~ /^dev\./
end
end
def live?
not dev?
end
end
| mikehale/halefamilyfarm | vendor/radiant/app/controllers/site_controller.rb | Ruby | mit | 1,781 |
namespace Vulcan.Core.DataAccess.Migrations.MigrationProviders
{
public enum ExecutionType
{
Insert,
InsertWithIdentity,
Update,
Delete
}
}
| SachiraChin/Vulcan | Vulcan.Core.DataAccess/Migrations/MigrationProviders/ExecutionType.cs | C# | mit | 187 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mithril_Kendo_WebApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mithril_Kendo_WebApp")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1489ca50-41a3-42be-8e92-4cac9b1762d5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| brakmic/Mithril_Kendo | Properties/AssemblyInfo.cs | C# | mit | 1,371 |
<!-- Jumbotron Header -->
<header class="jumbotron hero-spacer" style="padding: 2em; text-align: center;">
<img style="max-width:100%; max-height:100%;" src="<?=base_url()?>assets/img/slogan.png">
<!--
<h1>Read and let read!</h1>
<p>
Welcome to Discipulus, your humble start up for buying and selling books. We’re dedicated to giving you the very best experience on this website, with a focus on look, feel, functionality, and great community of likeminded people.Welcome to Discipulus, your humble start up for buying and selling books. We’re dedicated to giving you the very best experience on this website, with a focus on look, feel, functionality, and great community of likeminded people.
</p>
-->
<!-- <p><a class="btn btn-primary btn-large">Call to action!</a>-->
<!-- </p>-->
</header>
<hr>
<!-- Title -->
<!-- <div class="row">-->
<!-- <div class="col-lg-12">-->
<!-- <h3>Latest Features</h3>-->
<!-- </div>-->
<!-- </div>-->
<!-- /.row -->
<!-- Page Features -->
<div class="row text-center">
<?php
if(count($products) == 0){
echo '<center><i><h3>No data available</h3></i></center>';
}
foreach($products as $product){
?>
<div class="col-sm-3 col-lg-3 col-md-3">
<div class="thumbnail">
<div class="thumbnailx">
<img src="<?=$product->img?>" style="" alt="">
</div>
<div class="caption-ownad">
<h4><a href="<?=base_url().'shop/viewProduct/'.$product->id?>"><?=$product->title?></a></h4>
<span style="font-weight: bold;">P<?=$product->price?>.00</span>
<p style="margin-top: 0.3em;"><?=$product->description?></p>
</div>
</div>
</div>
<?php
}
?>
</div>
<!-- /.row -->
| jjsarmiento/itecm | application/views/shop/home.php | PHP | mit | 2,046 |
//
// PgpMimeTests.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2022 .NET Foundation and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Bcpg.OpenPgp;
using MimeKit;
using MimeKit.IO;
using MimeKit.IO.Filters;
using MimeKit.Cryptography;
namespace UnitTests.Cryptography {
[TestFixture]
public class PgpMimeTests
{
static PgpMimeTests ()
{
Environment.SetEnvironmentVariable ("GNUPGHOME", Path.GetFullPath ("."));
var dataDir = Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp");
CryptographyContext.Register (typeof (DummyOpenPgpContext));
foreach (var name in new [] { "pubring.gpg", "pubring.gpg~", "secring.gpg", "secring.gpg~", "gpg.conf" }) {
if (File.Exists (name))
File.Delete (name);
}
using (var ctx = new DummyOpenPgpContext ()) {
using (var seckeys = File.OpenRead (Path.Combine (dataDir, "mimekit.gpg.sec"))) {
using (var armored = new ArmoredInputStream (seckeys))
ctx.Import (new PgpSecretKeyRingBundle (armored));
}
using (var pubkeys = File.OpenRead (Path.Combine (dataDir, "mimekit.gpg.pub")))
ctx.Import (pubkeys);
}
File.Copy (Path.Combine (dataDir, "gpg.conf"), "gpg.conf", true);
}
static bool IsSupported (EncryptionAlgorithm algorithm)
{
switch (algorithm) {
case EncryptionAlgorithm.RC2128:
case EncryptionAlgorithm.RC264:
case EncryptionAlgorithm.RC240:
case EncryptionAlgorithm.Seed:
return false;
default:
return true;
}
}
[Test]
public void TestPreferredAlgorithms ()
{
using (var ctx = new DummyOpenPgpContext ()) {
var encryptionAlgorithms = ctx.EnabledEncryptionAlgorithms;
Assert.AreEqual (4, encryptionAlgorithms.Length);
Assert.AreEqual (EncryptionAlgorithm.Aes256, encryptionAlgorithms[0]);
Assert.AreEqual (EncryptionAlgorithm.Aes192, encryptionAlgorithms[1]);
Assert.AreEqual (EncryptionAlgorithm.Aes128, encryptionAlgorithms[2]);
Assert.AreEqual (EncryptionAlgorithm.TripleDes, encryptionAlgorithms[3]);
var digestAlgorithms = ctx.EnabledDigestAlgorithms;
Assert.AreEqual (3, digestAlgorithms.Length);
Assert.AreEqual (DigestAlgorithm.Sha256, digestAlgorithms[0]);
Assert.AreEqual (DigestAlgorithm.Sha512, digestAlgorithms[1]);
Assert.AreEqual (DigestAlgorithm.Sha1, digestAlgorithms[2]);
}
}
[Test]
public void TestKeyEnumeration ()
{
using (var ctx = new DummyOpenPgpContext ()) {
var unknownMailbox = new MailboxAddress ("Snarky McSnarkypants", "snarky@snarkypants.net");
var knownMailbox = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
int count = ctx.EnumeratePublicKeys ().Count ();
// Note: the count will be 8 if run as a complete unit test or 2 if run individually
Assert.IsTrue (count == 8 || count == 2, "Unexpected number of public keys");
Assert.AreEqual (0, ctx.EnumeratePublicKeys (unknownMailbox).Count (), "Unexpected number of public keys for an unknown mailbox");
Assert.AreEqual (2, ctx.EnumeratePublicKeys (knownMailbox).Count (), "Unexpected number of public keys for a known mailbox");
Assert.AreEqual (2, ctx.EnumerateSecretKeys ().Count (), "Unexpected number of secret keys");
Assert.AreEqual (0, ctx.EnumerateSecretKeys (unknownMailbox).Count (), "Unexpected number of secret keys for an unknown mailbox");
Assert.AreEqual (2, ctx.EnumerateSecretKeys (knownMailbox).Count (), "Unexpected number of secret keys for a known mailbox");
Assert.IsTrue (ctx.CanSign (knownMailbox));
Assert.IsFalse (ctx.CanSign (unknownMailbox));
Assert.IsTrue (ctx.CanEncrypt (knownMailbox));
Assert.IsFalse (ctx.CanEncrypt (unknownMailbox));
}
}
[Test]
public void TestKeyGeneration ()
{
using (var ctx = new DummyOpenPgpContext ()) {
var mailbox = new MailboxAddress ("Snarky McSnarkypants", "snarky@snarkypants.net");
int publicKeyRings = ctx.EnumeratePublicKeyRings ().Count ();
int secretKeyRings = ctx.EnumerateSecretKeyRings ().Count ();
ctx.GenerateKeyPair (mailbox, "password", DateTime.Now.AddYears (1), EncryptionAlgorithm.Cast5);
var pubring = ctx.EnumeratePublicKeyRings (mailbox).FirstOrDefault ();
Assert.IsNotNull (pubring, "Expected to find the generated public keyring");
ctx.Delete (pubring);
Assert.AreEqual (publicKeyRings, ctx.EnumeratePublicKeyRings ().Count (), "Unexpected number of public keyrings");
var secring = ctx.EnumerateSecretKeyRings (mailbox).FirstOrDefault ();
Assert.IsNotNull (secring, "Expected to find the generated secret keyring");
ctx.Delete (secring);
Assert.AreEqual (secretKeyRings, ctx.EnumerateSecretKeyRings ().Count (), "Unexpected number of secret keyrings");
}
}
[Test]
public void TestKeySigning ()
{
using (var ctx = new DummyOpenPgpContext ()) {
var seckey = ctx.EnumerateSecretKeys (new MailboxAddress ("", "mimekit@example.com")).FirstOrDefault ();
var mailbox = new MailboxAddress ("Snarky McSnarkypants", "snarky@snarkypants.net");
ctx.GenerateKeyPair (mailbox, "password", DateTime.Now.AddYears (1), EncryptionAlgorithm.Cast5);
// delete the secret keyring, we don't need it
var secring = ctx.EnumerateSecretKeyRings (mailbox).FirstOrDefault ();
ctx.Delete (secring);
var pubring = ctx.EnumeratePublicKeyRings (mailbox).FirstOrDefault ();
var pubkey = pubring.GetPublicKey ();
int sigCount = 0;
foreach (PgpSignature sig in pubkey.GetKeySignatures ())
sigCount++;
Assert.AreEqual (0, sigCount);
ctx.SignKey (seckey, pubkey, DigestAlgorithm.Sha256, OpenPgpKeyCertification.CasualCertification);
pubring = ctx.EnumeratePublicKeyRings (mailbox).FirstOrDefault ();
pubkey = pubring.GetPublicKey ();
sigCount = 0;
foreach (PgpSignature sig in pubkey.GetKeySignatures ()) {
Assert.AreEqual (seckey.KeyId, sig.KeyId);
Assert.AreEqual (HashAlgorithmTag.Sha256, sig.HashAlgorithm);
Assert.AreEqual ((int) OpenPgpKeyCertification.CasualCertification, sig.SignatureType);
sigCount++;
}
Assert.AreEqual (1, sigCount);
ctx.Delete (pubring);
}
}
[Test]
public void TestMimeMessageSign ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body is set
Assert.Throws<InvalidOperationException> (() => message.Sign (ctx));
message.Body = body;
// throws because no sender is set
Assert.Throws<InvalidOperationException> (() => message.Sign (ctx));
message.From.Add (self);
// ok, now we can sign
message.Sign (ctx);
Assert.IsInstanceOf<MultipartSigned> (message.Body);
var multipart = (MultipartSigned) message.Body;
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
var signatures = multipart.Verify (ctx);
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
var signature = signatures[0];
Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name);
Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email);
Assert.AreEqual ("44CD48EEC90D8849961F36BA50DCD107AB0821A2", signature.SignerCertificate.Fingerprint);
Assert.AreEqual (new DateTime (2013, 11, 3, 18, 32, 27), signature.SignerCertificate.CreationDate, "CreationDate");
Assert.AreEqual (DateTime.MaxValue, signature.SignerCertificate.ExpirationDate, "ExpirationDate");
Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.SignerCertificate.PublicKeyAlgorithm);
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMimeMessageSignAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body is set
Assert.Throws<InvalidOperationException> (() => message.Sign (ctx));
message.Body = body;
// throws because no sender is set
Assert.Throws<InvalidOperationException> (() => message.Sign (ctx));
message.From.Add (self);
// ok, now we can sign
message.Sign (ctx);
Assert.IsInstanceOf<MultipartSigned> (message.Body);
var multipart = (MultipartSigned) message.Body;
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
var signatures = await multipart.VerifyAsync (ctx);
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
var signature = signatures[0];
Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name);
Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email);
Assert.AreEqual ("44CD48EEC90D8849961F36BA50DCD107AB0821A2", signature.SignerCertificate.Fingerprint);
Assert.AreEqual (new DateTime (2013, 11, 3, 18, 32, 27), signature.SignerCertificate.CreationDate, "CreationDate");
Assert.AreEqual (DateTime.MaxValue, signature.SignerCertificate.ExpirationDate, "ExpirationDate");
Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.SignerCertificate.PublicKeyAlgorithm);
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestMultipartSignedVerifyExceptions ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
var signed = MultipartSigned.Create (ctx, self, DigestAlgorithm.Sha256, body);
var protocol = signed.ContentType.Parameters["protocol"];
signed.ContentType.Parameters.Remove ("protocol");
Assert.Throws<FormatException> (() => signed.Verify (), "Verify() w/o protocol parameter");
Assert.Throws<FormatException> (() => signed.Verify (ctx), "Verify(ctx) w/o protocol parameter");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (), "VerifyAsync() w/o protocol parameter");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/o protocol parameter");
signed.ContentType.Parameters.Add ("protocol", "invalid-protocol");
Assert.Throws<NotSupportedException> (() => signed.Verify (), "Verify() w/ invalid protocol parameter");
Assert.Throws<NotSupportedException> (() => signed.Verify (ctx), "Verify(ctx) w/ invalid protocol parameter");
Assert.ThrowsAsync<NotSupportedException> (() => signed.VerifyAsync (), "VerifyAsync() w/ invalid protocol parameter");
Assert.ThrowsAsync<NotSupportedException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/ invalid protocol parameter");
signed.ContentType.Parameters["protocol"] = protocol;
var signature = signed[1];
signed.RemoveAt (1);
Assert.Throws<FormatException> (() => signed.Verify (), "Verify() w/ < 2 parts");
Assert.Throws<FormatException> (() => signed.Verify (ctx), "Verify(ctx) w/ < 2 parts");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (), "VerifyAsync() w/ < 2 parts");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/ < 2 parts");
var emptySignature = new MimePart ("application", "octet-stream");
signed.Add (emptySignature);
Assert.Throws<FormatException> (() => signed.Verify (), "Verify() w/ invalid signature part");
Assert.Throws<FormatException> (() => signed.Verify (ctx), "Verify(ctx) w/ invalid signature part");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (), "VerifyAsync() w/ invalid signature part");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/ invalid signature part");
var invalidContent = new MimePart ("image", "jpeg") {
Content = new MimeContent (new MemoryStream (Array.Empty<byte> (), false))
};
signed[1] = invalidContent;
Assert.Throws<NotSupportedException> (() => signed.Verify (), "Verify() w/ invalid content part");
Assert.Throws<NotSupportedException> (() => signed.Verify (ctx), "Verify(ctx) w/ invalid content part");
Assert.ThrowsAsync<NotSupportedException> (() => signed.VerifyAsync (), "VerifyAsync() w/ invalid content part");
Assert.ThrowsAsync<NotSupportedException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/ invalid content part");
}
}
[Test]
public void TestMultipartSignedSignUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
signer = ctx.GetSigningKey (self);
foreach (DigestAlgorithm digest in Enum.GetValues (typeof (DigestAlgorithm))) {
if (digest == DigestAlgorithm.None ||
digest == DigestAlgorithm.DoubleSha ||
digest == DigestAlgorithm.Tiger192 ||
digest == DigestAlgorithm.Haval5160 ||
digest == DigestAlgorithm.MD4)
continue;
var multipart = MultipartSigned.Create (signer, digest, body);
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual ("application/pgp-signature", protocol, "The multipart/signed protocol does not match.");
var micalg = multipart.ContentType.Parameters["micalg"];
var algorithm = ctx.GetDigestAlgorithm (micalg);
Assert.AreEqual (digest, algorithm, "The multipart/signed micalg does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
var signatures = multipart.Verify ();
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
}
}
[Test]
public async Task TestMultipartSignedSignUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
signer = ctx.GetSigningKey (self);
foreach (DigestAlgorithm digest in Enum.GetValues (typeof (DigestAlgorithm))) {
if (digest == DigestAlgorithm.None ||
digest == DigestAlgorithm.DoubleSha ||
digest == DigestAlgorithm.Tiger192 ||
digest == DigestAlgorithm.Haval5160 ||
digest == DigestAlgorithm.MD4)
continue;
var multipart = await MultipartSigned.CreateAsync (signer, digest, body);
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual ("application/pgp-signature", protocol, "The multipart/signed protocol does not match.");
var micalg = multipart.ContentType.Parameters["micalg"];
var algorithm = ctx.GetDigestAlgorithm (micalg);
Assert.AreEqual (digest, algorithm, "The multipart/signed micalg does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
var signatures = await multipart.VerifyAsync ();
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
}
}
[Test]
public void TestMimeMessageEncrypt ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body has been set
Assert.Throws<InvalidOperationException> (() => message.Encrypt (ctx));
message.Body = body;
// throws because no recipients have been set
Assert.Throws<InvalidOperationException> (() => message.Encrypt (ctx));
message.From.Add (self);
message.To.Add (self);
message.Encrypt (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
var encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
// now do the same thing, but encrypt to the Resent-To headers
message.From.Clear ();
message.To.Clear ();
message.From.Add (new MailboxAddress ("Dummy Sender", "dummy@sender.com"));
message.To.Add (new MailboxAddress ("Dummy Recipient", "dummy@recipient.com"));
message.ResentFrom.Add (self);
message.ResentTo.Add (self);
message.Body = body;
message.Encrypt (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
[Test]
public async Task TestMimeMessageEncryptAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body has been set
Assert.ThrowsAsync<InvalidOperationException> (() => message.EncryptAsync (ctx));
message.Body = body;
// throws because no recipients have been set
Assert.ThrowsAsync<InvalidOperationException> (() => message.EncryptAsync (ctx));
message.From.Add (self);
message.To.Add (self);
await message.EncryptAsync (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
var encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
// now do the same thing, but encrypt to the Resent-To headers
message.From.Clear ();
message.To.Clear ();
message.From.Add (new MailboxAddress ("Dummy Sender", "dummy@sender.com"));
message.To.Add (new MailboxAddress ("Dummy Recipient", "dummy@recipient.com"));
message.ResentFrom.Add (self);
message.ResentTo.Add (self);
message.Body = body;
await message.EncryptAsync (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
[Test]
public void TestMultipartEncryptedDecryptExceptions ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var encrypted = MultipartEncrypted.Encrypt (new[] { self }, body);
using (var ctx = new DummyOpenPgpContext ()) {
var protocol = encrypted.ContentType.Parameters["protocol"];
encrypted.ContentType.Parameters.Remove ("protocol");
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/o protocol parameter");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/o protocol parameter");
encrypted.ContentType.Parameters.Add ("protocol", "invalid-protocol");
//Assert.Throws<NotSupportedException> (() => encrypted.Decrypt (), "Decrypt() w/ invalid protocol parameter");
Assert.Throws<NotSupportedException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ invalid protocol parameter");
encrypted.ContentType.Parameters["protocol"] = protocol;
var version = encrypted[0];
encrypted.RemoveAt (0);
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/ < 2 parts");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ < 2 parts");
var invalidVersion = new MimePart ("application", "octet-stream") {
Content = new MimeContent (new MemoryStream (Array.Empty<byte> (), false))
};
encrypted.Insert (0, invalidVersion);
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/ invalid version part");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ invalid version part");
var emptyContent = new MimePart ("application", "octet-stream");
var content = encrypted[1];
encrypted[1] = emptyContent;
encrypted[0] = version;
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/ empty content part");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ empty content part");
var invalidContent = new MimePart ("image", "jpeg") {
Content = new MimeContent (new MemoryStream (Array.Empty<byte> (), false))
};
encrypted[1] = invalidContent;
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/ invalid content part");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ invalid content part");
}
}
[Test]
public void TestMultipartEncryptedEncrypt ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var encrypted = MultipartEncrypted.Encrypt (new [] { self }, body);
using (var stream = new MemoryStream ()) {
encrypted.WriteTo (stream);
stream.Position = 0;
var entity = MimeEntity.Load (stream);
Assert.IsInstanceOf<MultipartEncrypted> (entity, "Encrypted part is not the expected type");
encrypted = (MultipartEncrypted) entity;
Assert.IsInstanceOf<ApplicationPgpEncrypted> (encrypted[0], "First child of multipart/encrypted is not the expected type");
Assert.IsInstanceOf<MimePart> (encrypted[1], "Second child of multipart/encrypted is not the expected type");
Assert.AreEqual ("application/octet-stream", encrypted[1].ContentType.MimeType, "Second child of multipart/encrypted is not the expected mime-type");
}
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
[Test]
public async Task TestMultipartEncryptedEncryptAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var encrypted = await MultipartEncrypted.EncryptAsync (new[] { self }, body);
using (var stream = new MemoryStream ()) {
await encrypted.WriteToAsync (stream);
stream.Position = 0;
var entity = await MimeEntity.LoadAsync (stream);
Assert.IsInstanceOf<MultipartEncrypted> (entity, "Encrypted part is not the expected type");
encrypted = (MultipartEncrypted) entity;
Assert.IsInstanceOf<ApplicationPgpEncrypted> (encrypted[0], "First child of multipart/encrypted is not the expected type");
Assert.IsInstanceOf<MimePart> (encrypted[1], "Second child of multipart/encrypted is not the expected type");
Assert.AreEqual ("application/octet-stream", encrypted[1].ContentType.MimeType, "Second child of multipart/encrypted is not the expected mime-type");
}
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
[Test]
public void TestMultipartEncryptedEncryptUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
IList<PgpPublicKey> recipients;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = ctx.GetPublicKeys (new [] { self });
}
var encrypted = MultipartEncrypted.Encrypt (recipients, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
[Test]
public async Task TestMultipartEncryptedEncryptUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
IList<PgpPublicKey> recipients;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = await ctx.GetPublicKeysAsync (new[] { self });
}
var encrypted = await MultipartEncrypted.EncryptAsync (recipients, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
[Test]
public void TestMultipartEncryptedEncryptAlgorithm ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm))
continue;
var encrypted = MultipartEncrypted.Encrypt (algorithm, new [] { self }, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
}
[Test]
public async Task TestMultipartEncryptedEncryptAlgorithmAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm))
continue;
var encrypted = await MultipartEncrypted.EncryptAsync (algorithm, new[] { self }, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
}
[Test]
public void TestMultipartEncryptedEncryptAlgorithmUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
IList<PgpPublicKey> recipients;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = ctx.GetPublicKeys (new [] { self });
}
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm))
continue;
var encrypted = MultipartEncrypted.Encrypt (algorithm, recipients, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
[Test]
public async Task TestMultipartEncryptedEncryptAlgorithmUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
IList<PgpPublicKey> recipients;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = await ctx.GetPublicKeysAsync (new[] { self });
}
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm))
continue;
var encrypted = await MultipartEncrypted.EncryptAsync (algorithm, recipients, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
[Test]
public void TestMimeMessageSignAndEncrypt ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
DigitalSignatureCollection signatures;
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body has been set
Assert.Throws<InvalidOperationException> (() => message.SignAndEncrypt (ctx));
message.Body = body;
// throws because no sender has been set
Assert.Throws<InvalidOperationException> (() => message.SignAndEncrypt (ctx));
message.From.Add (self);
message.To.Add (self);
message.SignAndEncrypt (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
var encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (ctx, out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
// now do the same thing, but encrypt to the Resent-To headers
message.From.Clear ();
message.To.Clear ();
message.From.Add (new MailboxAddress ("Dummy Sender", "dummy@sender.com"));
message.To.Add (new MailboxAddress ("Dummy Recipient", "dummy@recipient.com"));
message.ResentFrom.Add (self);
message.ResentTo.Add (self);
message.Body = body;
message.SignAndEncrypt (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
decrypted = encrypted.Decrypt (ctx, out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
}
[Test]
public async Task TestMimeMessageSignAndEncryptAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
DigitalSignatureCollection signatures;
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body has been set
Assert.ThrowsAsync<InvalidOperationException> (() => message.SignAndEncryptAsync (ctx));
message.Body = body;
// throws because no sender has been set
Assert.ThrowsAsync<InvalidOperationException> (() => message.SignAndEncryptAsync (ctx));
message.From.Add (self);
message.To.Add (self);
await message.SignAndEncryptAsync (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
var encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (ctx, out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
// now do the same thing, but encrypt to the Resent-To headers
message.From.Clear ();
message.To.Clear ();
message.From.Add (new MailboxAddress ("Dummy Sender", "dummy@sender.com"));
message.To.Add (new MailboxAddress ("Dummy Recipient", "dummy@recipient.com"));
message.ResentFrom.Add (self);
message.ResentTo.Add (self);
message.Body = body;
await message.SignAndEncryptAsync (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
decrypted = encrypted.Decrypt (ctx, out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
}
[Test]
public void TestMultipartEncryptedSignAndEncrypt ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
var encrypted = MultipartEncrypted.SignAndEncrypt (self, DigestAlgorithm.Sha1, new [] { self }, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMultipartEncryptedSignAndEncryptAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
var encrypted = await MultipartEncrypted.SignAndEncryptAsync (self, DigestAlgorithm.Sha1, new[] { self }, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestMultipartEncryptedSignAndEncryptUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
IList<PgpPublicKey> recipients;
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = ctx.GetPublicKeys (new [] { self });
signer = ctx.GetSigningKey (self);
}
var encrypted = MultipartEncrypted.SignAndEncrypt (signer, DigestAlgorithm.Sha1, recipients, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMultipartEncryptedSignAndEncryptUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
IList<PgpPublicKey> recipients;
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = await ctx.GetPublicKeysAsync (new[] { self });
signer = await ctx.GetSigningKeyAsync (self);
}
var encrypted = await MultipartEncrypted.SignAndEncryptAsync (signer, DigestAlgorithm.Sha1, recipients, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestMultipartEncryptedSignAndEncryptAlgorithm ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
var encrypted = MultipartEncrypted.SignAndEncrypt (self, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, new [] { self }, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMultipartEncryptedSignAndEncryptAlgorithmAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
var encrypted = await MultipartEncrypted.SignAndEncryptAsync (self, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, new[] { self }, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestMultipartEncryptedSignAndEncryptAlgorithmUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
IList<PgpPublicKey> recipients;
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = ctx.GetPublicKeys (new [] { self });
signer = ctx.GetSigningKey (self);
}
var encrypted = MultipartEncrypted.SignAndEncrypt (signer, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, recipients, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMultipartEncryptedSignAndEncryptAlgorithmUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
IList<PgpPublicKey> recipients;
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = await ctx.GetPublicKeysAsync (new[] { self });
signer = await ctx.GetSigningKeyAsync (self);
}
var encrypted = await MultipartEncrypted.SignAndEncryptAsync (signer, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, recipients, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestAutoKeyRetrieve ()
{
var message = MimeMessage.Load (Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp", "[Announce] GnuPG 2.1.20 released.eml"));
var multipart = (MultipartSigned) ((Multipart) message.Body)[0];
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual ("application/pgp-signature", protocol, "The multipart/signed protocol does not match.");
var micalg = multipart.ContentType.Parameters["micalg"];
Assert.AreEqual ("pgp-sha1", micalg, "The multipart/signed micalg does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
DigitalSignatureCollection signatures;
try {
signatures = multipart.Verify ();
} catch (IOException ex) {
if (ex.Message == "unknown PGP public key algorithm encountered") {
Assert.Ignore ("Known issue: {0}", ex.Message);
return;
}
throw;
}
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException) {
// Note: Werner Koch's keyring has an EdDSA subkey which breaks BouncyCastle's
// PgpPublicKeyRingBundle reader. If/when one of the round-robin keys.gnupg.net
// key servers returns this particular keyring, we can expect to get an exception
// about being unable to find Werner's public key.
//Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestAutoKeyRetrieveAsync ()
{
var message = await MimeMessage.LoadAsync (Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp", "[Announce] GnuPG 2.1.20 released.eml"));
var multipart = (MultipartSigned) ((Multipart) message.Body)[0];
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual ("application/pgp-signature", protocol, "The multipart/signed protocol does not match.");
var micalg = multipart.ContentType.Parameters["micalg"];
Assert.AreEqual ("pgp-sha1", micalg, "The multipart/signed micalg does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
DigitalSignatureCollection signatures;
try {
signatures = await multipart.VerifyAsync ();
} catch (IOException ex) {
if (ex.Message == "unknown PGP public key algorithm encountered") {
Assert.Ignore ("Known issue: {0}", ex.Message);
return;
}
throw;
}
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException) {
// Note: Werner Koch's keyring has an EdDSA subkey which breaks BouncyCastle's
// PgpPublicKeyRingBundle reader. If/when one of the round-robin keys.gnupg.net
// key servers returns this particular keyring, we can expect to get an exception
// about being unable to find Werner's public key.
//Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestExport ()
{
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
Assert.AreEqual ("application/pgp-keys", ctx.KeyExchangeProtocol, "The key-exchange protocol does not match.");
var keys = ctx.EnumeratePublicKeys (self).ToList ();
var exported = ctx.Export (new [] { self });
Assert.IsNotNull (exported, "The exported MIME part should not be null.");
Assert.IsInstanceOf<MimePart> (exported, "The exported MIME part should be a MimePart.");
Assert.AreEqual ("application/pgp-keys", exported.ContentType.MimeType);
exported = ctx.Export (keys);
Assert.IsNotNull (exported, "The exported MIME part should not be null.");
Assert.IsInstanceOf<MimePart> (exported, "The exported MIME part should be a MimePart.");
Assert.AreEqual ("application/pgp-keys", exported.ContentType.MimeType);
using (var stream = new MemoryStream ()) {
ctx.Export (new[] { self }, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
foreach (var keyring in ctx.EnumeratePublicKeyRings (self)) {
using (var stream = new MemoryStream ()) {
ctx.Export (new[] { self }, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
}
using (var stream = new MemoryStream ()) {
ctx.Export (keys, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
}
}
[Test]
public async Task TestExportAsync ()
{
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
Assert.AreEqual ("application/pgp-keys", ctx.KeyExchangeProtocol, "The key-exchange protocol does not match.");
var keys = ctx.EnumeratePublicKeys (self).ToList ();
var exported = await ctx.ExportAsync (new[] { self });
Assert.IsNotNull (exported, "The exported MIME part should not be null.");
Assert.IsInstanceOf<MimePart> (exported, "The exported MIME part should be a MimePart.");
Assert.AreEqual ("application/pgp-keys", exported.ContentType.MimeType);
exported = await ctx.ExportAsync (keys);
Assert.IsNotNull (exported, "The exported MIME part should not be null.");
Assert.IsInstanceOf<MimePart> (exported, "The exported MIME part should be a MimePart.");
Assert.AreEqual ("application/pgp-keys", exported.ContentType.MimeType);
using (var stream = new MemoryStream ()) {
await ctx.ExportAsync (new[] { self }, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
foreach (var keyring in ctx.EnumeratePublicKeyRings (self)) {
using (var stream = new MemoryStream ()) {
await ctx.ExportAsync (new[] { self }, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
}
using (var stream = new MemoryStream ()) {
await ctx.ExportAsync (keys, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
}
}
[Test]
public void TestDefaultEncryptionAlgorithm ()
{
using (var ctx = new DummyOpenPgpContext ()) {
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm)) {
Assert.Throws<NotSupportedException> (() => ctx.DefaultEncryptionAlgorithm = algorithm);
continue;
}
ctx.DefaultEncryptionAlgorithm = algorithm;
Assert.AreEqual (algorithm, ctx.DefaultEncryptionAlgorithm, "Default encryption algorithm does not match.");
}
}
}
[Test]
public void TestSupports ()
{
var supports = new [] { "application/pgp-encrypted", "application/pgp-signature", "application/pgp-keys",
"application/x-pgp-encrypted", "application/x-pgp-signature", "application/x-pgp-keys" };
using (var ctx = new DummyOpenPgpContext ()) {
for (int i = 0; i < supports.Length; i++)
Assert.IsTrue (ctx.Supports (supports[i]), supports[i]);
Assert.IsFalse (ctx.Supports ("application/octet-stream"), "application/octet-stream");
Assert.IsFalse (ctx.Supports ("text/plain"), "text/plain");
}
}
[Test]
public void TestAlgorithmMappings ()
{
using (var ctx = new DummyOpenPgpContext ()) {
foreach (DigestAlgorithm digest in Enum.GetValues (typeof (DigestAlgorithm))) {
if (digest == DigestAlgorithm.None || digest == DigestAlgorithm.DoubleSha)
continue;
var name = ctx.GetDigestAlgorithmName (digest);
var algo = ctx.GetDigestAlgorithm (name);
Assert.AreEqual (digest, algo);
}
Assert.AreEqual (DigestAlgorithm.MD5, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.MD5));
Assert.AreEqual (DigestAlgorithm.Sha1, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha1));
Assert.AreEqual (DigestAlgorithm.RipeMD160, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.RipeMD160));
Assert.AreEqual (DigestAlgorithm.DoubleSha, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.DoubleSha));
Assert.AreEqual (DigestAlgorithm.MD2, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.MD2));
Assert.AreEqual (DigestAlgorithm.Tiger192, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Tiger192));
Assert.AreEqual (DigestAlgorithm.Haval5160, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Haval5pass160));
Assert.AreEqual (DigestAlgorithm.Sha256, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha256));
Assert.AreEqual (DigestAlgorithm.Sha384, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha384));
Assert.AreEqual (DigestAlgorithm.Sha512, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha512));
Assert.AreEqual (DigestAlgorithm.Sha224, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha224));
Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.RsaGeneral));
Assert.AreEqual (PublicKeyAlgorithm.RsaEncrypt, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.RsaEncrypt));
Assert.AreEqual (PublicKeyAlgorithm.RsaSign, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.RsaSign));
Assert.AreEqual (PublicKeyAlgorithm.ElGamalGeneral, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.ElGamalGeneral));
Assert.AreEqual (PublicKeyAlgorithm.ElGamalEncrypt, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.ElGamalEncrypt));
Assert.AreEqual (PublicKeyAlgorithm.Dsa, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.Dsa));
Assert.AreEqual (PublicKeyAlgorithm.EllipticCurve, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.ECDH));
Assert.AreEqual (PublicKeyAlgorithm.EllipticCurveDsa, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.ECDsa));
Assert.AreEqual (PublicKeyAlgorithm.DiffieHellman, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.DiffieHellman));
//Assert.AreEqual (PublicKeyAlgorithm.EdwardsCurveDsa, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.EdDSA));
}
}
[Test]
public void TestArgumentExceptions ()
{
Assert.Throws<ArgumentNullException> (() => CryptographyContext.Create (null));
Assert.Throws<ArgumentNullException> (() => CryptographyContext.Register ((Type) null));
Assert.Throws<ArgumentNullException> (() => CryptographyContext.Register ((Func<OpenPgpContext>) null));
Assert.Throws<ArgumentNullException> (() => CryptographyContext.Register ((Func<SecureMimeContext>) null));
using (var ctx = new DummyOpenPgpContext ()) {
var clientEastwood = new MailboxAddress ("Man with No Name", "client.eastwood@fistfullofdollars.com");
var mailboxes = new [] { new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com") };
var emptyMailboxes = new MailboxAddress[0];
var pubkeys = ctx.GetPublicKeys (mailboxes);
var key = ctx.GetSigningKey (mailboxes[0]);
var emptyPubkeys = new PgpPublicKey[0];
DigitalSignatureCollection signatures;
var stream = new MemoryStream ();
var entity = new MimePart ();
Assert.Throws<ArgumentException> (() => ctx.KeyServer = new Uri ("relative/uri", UriKind.Relative));
Assert.Throws<ArgumentNullException> (() => ctx.GetDigestAlgorithm (null));
Assert.Throws<ArgumentOutOfRangeException> (() => ctx.GetDigestAlgorithmName (DigestAlgorithm.DoubleSha));
Assert.Throws<NotSupportedException> (() => OpenPgpContext.GetHashAlgorithm (DigestAlgorithm.DoubleSha));
Assert.Throws<NotSupportedException> (() => OpenPgpContext.GetHashAlgorithm (DigestAlgorithm.Tiger192));
Assert.Throws<NotSupportedException> (() => OpenPgpContext.GetHashAlgorithm (DigestAlgorithm.Haval5160));
Assert.Throws<NotSupportedException> (() => OpenPgpContext.GetHashAlgorithm (DigestAlgorithm.MD4));
Assert.Throws<ArgumentOutOfRangeException> (() => OpenPgpContext.GetDigestAlgorithm ((Org.BouncyCastle.Bcpg.HashAlgorithmTag) 1024));
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpEncrypted ((MimeEntityConstructorArgs) null));
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpSignature ((MimeEntityConstructorArgs) null));
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpSignature ((Stream) null));
// Accept
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpEncrypted ().Accept (null));
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpSignature (stream).Accept (null));
Assert.Throws<ArgumentNullException> (() => ctx.CanSign (null));
Assert.Throws<ArgumentNullException> (() => ctx.CanEncrypt (null));
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.CanSignAsync (null));
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.CanEncryptAsync (null));
// Delete
Assert.Throws<ArgumentNullException> (() => ctx.Delete ((PgpPublicKeyRing) null), "Delete");
Assert.Throws<ArgumentNullException> (() => ctx.Delete ((PgpSecretKeyRing) null), "Delete");
// Decrypt
Assert.Throws<ArgumentNullException> (() => ctx.Decrypt (null), "Decrypt");
// Encrypt
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, stream), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, stream), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt ((MailboxAddress[]) null, stream), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt ((PgpPublicKey[]) null, stream), "Encrypt");
Assert.Throws<ArgumentException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, emptyMailboxes, stream), "Encrypt");
Assert.Throws<ArgumentException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, emptyPubkeys, stream), "Encrypt");
Assert.Throws<ArgumentException> (() => ctx.Encrypt (emptyMailboxes, stream), "Encrypt");
Assert.Throws<ArgumentException> (() => ctx.Encrypt (emptyPubkeys, stream), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, mailboxes, null), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, pubkeys, null), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (mailboxes, null), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (pubkeys, null), "Encrypt");
// EncryptAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync ((MailboxAddress[]) null, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync ((PgpPublicKey[]) null, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, emptyMailboxes, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, emptyPubkeys, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.EncryptAsync (emptyMailboxes, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.EncryptAsync (emptyPubkeys, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, mailboxes, null), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, pubkeys, null), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (mailboxes, null), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (pubkeys, null), "EncryptAsync");
// Export
Assert.Throws<ArgumentNullException> (() => ctx.Export ((PgpPublicKeyRingBundle) null), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((MailboxAddress[]) null), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((PgpPublicKey[]) null), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((PgpPublicKeyRingBundle) null, stream, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((MailboxAddress[]) null, stream, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((PgpPublicKey[]) null, stream, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export (ctx.PublicKeyRingBundle, null, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export (mailboxes, null, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export (pubkeys, null, true), "Export");
// ExportAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((PgpPublicKeyRingBundle) null), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((MailboxAddress[]) null), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((PgpPublicKey[]) null), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((PgpPublicKeyRingBundle) null, stream, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((MailboxAddress[]) null, stream, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((PgpPublicKey[]) null, stream, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync (ctx.PublicKeyRingBundle, null, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync (mailboxes, null, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync (pubkeys, null, true), "ExportAsync");
// EnumeratePublicKey[Ring]s
Assert.Throws<ArgumentNullException> (() => ctx.EnumeratePublicKeyRings (null).FirstOrDefault ());
Assert.Throws<ArgumentNullException> (() => ctx.EnumeratePublicKeys (null).FirstOrDefault ());
Assert.Throws<ArgumentNullException> (() => ctx.EnumerateSecretKeyRings (null).FirstOrDefault ());
Assert.Throws<ArgumentNullException> (() => ctx.EnumerateSecretKeys (null).FirstOrDefault ());
// GenerateKeyPair
Assert.Throws<ArgumentNullException> (() => ctx.GenerateKeyPair (null, "password"));
Assert.Throws<ArgumentNullException> (() => ctx.GenerateKeyPair (mailboxes[0], null));
Assert.Throws<ArgumentException> (() => ctx.GenerateKeyPair (mailboxes[0], "password", DateTime.Now));
// DecryptTo
Assert.Throws<ArgumentNullException> (() => ctx.DecryptTo (null, stream), "DecryptTo");
Assert.Throws<ArgumentNullException> (() => ctx.DecryptTo (stream, null), "DecryptTo");
// DecryptToAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.DecryptToAsync (null, stream), "DecryptToAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.DecryptToAsync (stream, null), "DecryptToAsync");
// GetDigestAlgorithmName
Assert.Throws<ArgumentOutOfRangeException> (() => ctx.GetDigestAlgorithmName (DigestAlgorithm.None), "GetDigestAlgorithmName");
// GetPublicKeys
Assert.Throws<ArgumentNullException> (() => ctx.GetPublicKeys (null));
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.GetPublicKeysAsync (null));
Assert.Throws<PublicKeyNotFoundException> (() => ctx.GetPublicKeys (new MailboxAddress[] { clientEastwood }));
Assert.ThrowsAsync<PublicKeyNotFoundException> (() => ctx.GetPublicKeysAsync (new MailboxAddress[] { clientEastwood }));
// GetSigningKey
Assert.Throws<ArgumentNullException> (() => ctx.GetSigningKey (null));
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.GetSigningKeyAsync (null));
Assert.Throws<PrivateKeyNotFoundException> (() => ctx.GetSigningKey (clientEastwood));
Assert.ThrowsAsync<PrivateKeyNotFoundException> (() => ctx.GetSigningKeyAsync (clientEastwood));
// Import
Assert.Throws<ArgumentNullException> (() => ctx.Import ((Stream) null), "Import");
Assert.Throws<ArgumentNullException> (() => ctx.Import ((PgpPublicKeyRing) null), "Import");
Assert.Throws<ArgumentNullException> (() => ctx.Import ((PgpPublicKeyRingBundle) null), "Import");
Assert.Throws<ArgumentNullException> (() => ctx.Import ((PgpSecretKeyRing) null), "Import");
Assert.Throws<ArgumentNullException> (() => ctx.Import ((PgpSecretKeyRingBundle) null), "Import");
// ImportAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((Stream) null), "ImportAsync");
//Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((PgpPublicKeyRing) null), "ImportAsync");
//Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((PgpPublicKeyRingBundle) null), "ImportAsync");
//Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((PgpSecretKeyRing) null), "ImportAsync");
//Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((PgpSecretKeyRingBundle) null), "ImportAsync");
// Sign
Assert.Throws<ArgumentNullException> (() => ctx.Sign ((MailboxAddress) null, DigestAlgorithm.Sha1, stream), "Sign");
Assert.Throws<ArgumentNullException> (() => ctx.Sign ((PgpSecretKey) null, DigestAlgorithm.Sha1, stream), "Sign");
Assert.Throws<ArgumentNullException> (() => ctx.Sign (mailboxes[0], DigestAlgorithm.Sha1, null), "Sign");
Assert.Throws<ArgumentNullException> (() => ctx.Sign (key, DigestAlgorithm.Sha1, null), "Sign");
// SignAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, stream), "SignAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, stream), "SignAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAsync (mailboxes[0], DigestAlgorithm.Sha1, null), "SignAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAsync (key, DigestAlgorithm.Sha1, null), "SignAsync");
// SignAndEncrypt
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt ((MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt ((PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, stream), "SignAndEncrypt");
Assert.Throws<ArgumentException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, stream), "SignAndEncrypt");
Assert.Throws<ArgumentException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt ((MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt ((PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, (MailboxAddress[]) null, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, (PgpPublicKey[]) null, stream), "SignAndEncrypt");
Assert.Throws<ArgumentException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, stream), "SignAndEncrypt");
Assert.Throws<ArgumentException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, emptyPubkeys, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, pubkeys, null), "SignAndEncrypt");
// SignAndEncryptAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, (MailboxAddress[]) null, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, (PgpPublicKey[]) null, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, emptyPubkeys, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, pubkeys, null), "SignAndEncryptAsync");
// SignKey
Assert.Throws<ArgumentNullException> (() => ctx.SignKey (null, pubkeys[0]), "SignKey");
Assert.Throws<ArgumentNullException> (() => ctx.SignKey (key, null), "SignKey");
// Supports
Assert.Throws<ArgumentNullException> (() => ctx.Supports (null), "Supports");
// Verify
Assert.Throws<ArgumentNullException> (() => ctx.Verify (null, stream), "Verify");
Assert.Throws<ArgumentNullException> (() => ctx.Verify (stream, null), "Verify");
// VerifyAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.VerifyAsync (null, stream), "VerifyAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.VerifyAsync (stream, null), "VerifyAsync");
// MultipartEncrypted
// Encrypt
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt ((MailboxAddress[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt ((PgpPublicKey[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (null, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, (MailboxAddress[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (ctx, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (null, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, (PgpPublicKey[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (ctx, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (null, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (null, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, pubkeys, null));
// EncryptAsync
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync ((MailboxAddress[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync ((PgpPublicKey[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (null, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, (MailboxAddress[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (ctx, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (null, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, (PgpPublicKey[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (ctx, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (null, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (null, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, pubkeys, null));
// SignAndEncrypt
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt ((MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt ((PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (null, mailboxes[0], DigestAlgorithm.Sha1, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (null, key, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt ((MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt ((PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (null, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (null, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null));
// SignAndEncryptAsync
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (null, mailboxes[0], DigestAlgorithm.Sha1, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (null, key, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (null, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (null, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null));
var encrypted = new MultipartEncrypted ();
Assert.Throws<ArgumentNullException> (() => encrypted.Accept (null));
Assert.Throws<ArgumentNullException> (() => encrypted.Decrypt (null));
Assert.Throws<ArgumentNullException> (() => encrypted.Decrypt (null, out signatures));
// MultipartSigned.Create
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (null, mailboxes[0], DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, mailboxes[0], DigestAlgorithm.Sha1, null));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (null, key, DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, key, DigestAlgorithm.Sha1, null));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create ((PgpSecretKey) null, DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (key, DigestAlgorithm.Sha1, null));
// MultipartSigned.CreateAsync
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (null, mailboxes[0], DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (null, key, DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (ctx, key, DigestAlgorithm.Sha1, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (key, DigestAlgorithm.Sha1, null));
var signed = MultipartSigned.Create (key, DigestAlgorithm.Sha1, entity);
Assert.Throws<ArgumentNullException> (() => signed.Accept (null));
Assert.Throws<ArgumentOutOfRangeException> (() => signed.Prepare (EncodingConstraint.SevenBit, 0));
Assert.Throws<ArgumentNullException> (() => signed.Verify (null));
Assert.ThrowsAsync<ArgumentNullException> (() => signed.VerifyAsync (null));
}
}
static void PumpDataThroughFilter (IMimeFilter filter, string fileName, bool isText)
{
using (var stream = File.OpenRead (fileName)) {
using (var filtered = new FilteredStream (stream)) {
var buffer = new byte[1];
int outputLength;
int outputIndex;
int n;
if (isText)
filtered.Add (new Unix2DosFilter ());
while ((n = filtered.Read (buffer, 0, buffer.Length)) > 0)
filter.Filter (buffer, 0, n, out outputIndex, out outputLength);
filter.Flush (buffer, 0, 0, out outputIndex, out outputLength);
}
}
}
[Test]
public void TestOpenPgpDetectionFilter ()
{
var filter = new OpenPgpDetectionFilter ();
PumpDataThroughFilter (filter, Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp", "mimekit.gpg.pub"), true);
Assert.AreEqual (OpenPgpDataType.PublicKey, filter.DataType);
Assert.AreEqual (0, filter.BeginOffset);
Assert.AreEqual (1754, filter.EndOffset);
filter.Reset ();
PumpDataThroughFilter (filter, Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp", "mimekit.gpg.sec"), true);
Assert.AreEqual (OpenPgpDataType.PrivateKey, filter.DataType);
Assert.AreEqual (0, filter.BeginOffset);
Assert.AreEqual (3650, filter.EndOffset);
}
}
}
| jstedfast/MimeKit | UnitTests/Cryptography/PgpMimeTests.cs | C# | mit | 103,153 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="el_GR" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Number7</source>
<translation>Σχετικά με το Number7</translation>
</message>
<message>
<location line="+39"/>
<source><b>Number7</b> version</source>
<translation>Έκδοση Number7</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>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Πνευματική ιδιοκτησία </translation>
</message>
<message>
<location line="+0"/>
<source>The Number7 developers</source>
<translation>Οι Number7 προγραμματιστές </translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Βιβλίο Διευθύνσεων</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Διπλό-κλικ για επεξεργασία της διεύθυνσης ή της ετικέτας</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Δημιούργησε νέα διεύθυνση</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Αντέγραψε την επιλεγμένη διεύθυνση στο πρόχειρο του συστήματος</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Νέα διεύθυνση</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Number7 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>Αυτές είναι οι Number7 διευθύνσεις σας για να λαμβάνετε πληρωμές. Δίνοντας μία ξεχωριστή διεύθυνση σε κάθε αποστολέα, θα μπορείτε να ελέγχετε ποιος σας πληρώνει.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Δείξε &QR κωδικα</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Number7 address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως σας ανήκει μια συγκεκριμένη διεύθυνση Number7</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Υπέγραψε το μήνυμα</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Αντιγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Εξαγωγή δεδομένων καρτέλας σε αρχείο</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Εξαγωγή</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Number7 address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως ανήκει μια συγκεκριμένη διεύθυνση Number7</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Διαγραφή</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Number7 addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Αυτές είναι οι Number7 διευθύνσεις σας για να λαμβάνετε πληρωμές. Δίνοντας μία ξεχωριστή διεύθυνση σε κάθε αποστολέα, θα μπορείτε να ελέγχετε ποιος σας πληρώνει.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Αντιγραφή &επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Επεξεργασία</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Εξαγωγή Δεδομενων Βιβλίου Διευθύνσεων</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Εξαγωγή λαθών</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Αδυναμία εγγραφής στο αρχείο %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Ετικέτα</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(χωρίς ετικέτα)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Φράση πρόσβασης </translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Βάλτε κωδικό πρόσβασης</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Νέος κωδικός πρόσβασης</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Επανέλαβε τον νέο κωδικό πρόσβασης</translation>
</message>
<message>
<location 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>Εισάγετε τον νέο κωδικό πρόσβασης στον πορτοφόλι <br/> Παρακαλώ χρησιμοποιείστε ένα κωδικό με <b> 10 ή περισσότερους τυχαίους χαρακτήρες</b> ή <b> οχτώ ή παραπάνω λέξεις</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Αυτη η ενεργεία χρειάζεται τον κωδικό του πορτοφολιού για να ξεκλειδώσει το πορτοφόλι.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Ξεκλειδωσε το πορτοφολι</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Αυτη η ενεργεια χρειάζεται τον κωδικο του πορτοφολιου για να αποκρυπτογραφησειι το πορτοφολι.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Αποκρυπτογράφησε το πορτοφολι</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Εισάγετε τον παλιό και τον νεο κωδικο στο πορτοφολι.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Επιβεβαίωσε την κρυπτογραφηση του πορτοφολιού</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR NUMBER7S</b>!</source>
<translation>Προσοχη: Εαν κρυπτογραφησεις το πορτοφολι σου και χάσεις τον κωδικο σου θα χάσεις <b> ΟΛΑ ΣΟΥ ΤΑ NUMBER7S</b>!
Είσαι σίγουρος ότι θέλεις να κρυπτογραφησεις το πορτοφολι;</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Είστε σίγουροι ότι θέλετε να κρυπτογραφήσετε το πορτοφόλι σας;</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ΣΗΜΑΝΤΙΚΟ: Τα προηγούμενα αντίγραφα ασφαλείας που έχετε κάνει από το αρχείο του πορτοφόλιου σας θα πρέπει να αντικατασταθουν με το νέο που δημιουργείται, κρυπτογραφημένο αρχείο πορτοφόλιου. Για λόγους ασφαλείας, τα προηγούμενα αντίγραφα ασφαλείας του μη κρυπτογραφημένου αρχείου πορτοφόλιου θα καταστουν άχρηστα μόλις αρχίσετε να χρησιμοποιείτε το νέο κρυπτογραφημένο πορτοφόλι. </translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Προσοχη: το πλήκτρο Caps Lock είναι ενεργο.</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Κρυπτογραφημενο πορτοφολι</translation>
</message>
<message>
<location line="-56"/>
<source>Number7 will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your number7s from being stolen by malware infecting your computer.</source>
<translation>Το Number7 θα κλεισει τώρα για να τελειώσει την διαδικασία κρυπτογραφησης. Θυμησου ότι κρυπτογραφώντας το πορτοφολι σου δεν μπορείς να προστατέψεις πλήρως τα number7s σου από κλοπή στην περίπτωση όπου μολυνθεί ο υπολογιστής σου με κακόβουλο λογισμικο.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Η κρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Η κρυπτογράφηση του πορτοφολιού απέτυχε λογω εσωτερικού σφάλματος. Το πορτοφολι δεν κρυπτογραφηθηκε.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Οι εισαχθέντες κωδικοί δεν ταιριάζουν.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Ο κωδικος που εισήχθη για την αποκρυπτογραφηση του πορτοφολιού ήταν λαθος.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Η αποκρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Ο κωδικος του πορτοφολιού άλλαξε με επιτυχία.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Υπογραφή &Μηνύματος...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Συγχρονισμός με το δίκτυο...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Επισκόπηση</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Εμφάνισε γενική εικονα του πορτοφολιού</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Συναλλαγές</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Περιήγηση στο ιστορικο συνναλαγων</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Εξεργασια της λιστας των αποθηκευμενων διευθύνσεων και ετικετων</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Εμφάνισε την λίστα των διευθύνσεων για την παραλαβή πληρωμων</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>Έ&ξοδος</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Εξοδος από την εφαρμογή</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Number7</source>
<translation>Εμφάνισε πληροφορίες σχετικά με το Number7</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Σχετικά με &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Εμφάνισε πληροφορίες σχετικά με Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Επιλογές...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Εισαγωγή μπλοκ από τον σκληρο δίσκο ... </translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ στον σκληρο δισκο...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Number7 address</source>
<translation>Στείλε νομισματα σε μια διεύθυνση number7</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Number7</source>
<translation>Επεργασία ρυθμισεων επιλογών για το Number7</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Δημιουργία αντιγράφου ασφαλείας πορτοφολιού σε άλλη τοποθεσία</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Αλλαγή του κωδικού κρυπτογράφησης του πορτοφολιού</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Άνοιγμα κονσόλας αποσφαλμάτωσης και διαγνωστικών</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Number7</source>
<translation>Number7</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Αποστολή</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Παραλαβή </translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Διεύθυνσεις</translation>
</message>
<message>
<location line="+22"/>
<source>&About Number7</source>
<translation>&Σχετικα:Number7</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Εμφάνισε/Κρύψε</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Εμφάνιση ή αποκρύψη του κεντρικου παράθυρου </translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Κρυπτογραφήστε τα ιδιωτικά κλειδιά που ανήκουν στο πορτοφόλι σας </translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Number7 addresses to prove you own them</source>
<translation>Υπογράψτε ένα μήνυμα για να βεβαιώσετε πως είστε ο κάτοχος αυτής της διεύθυνσης</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Number7 addresses</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως ανήκει μια συγκεκριμένη διεύθυνση Number7</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Αρχείο</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Ρυθμίσεις</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Βοήθεια</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Εργαλειοθήκη καρτελών</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Number7 client</source>
<translation>Πελάτης Number7</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Number7 network</source>
<translation><numerusform>%n ενεργή σύνδεση στο δίκτυο Number7</numerusform><numerusform>%n ενεργές συνδέσεις στο δίκτυο Βitcoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Η πηγή του μπλοκ δεν ειναι διαθέσιμη... </translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Μεταποιημένα %1 απο % 2 (κατ 'εκτίμηση) μπλοκ της ιστορίας της συναλλαγής. </translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Έγινε λήψη %1 μπλοκ ιστορικού συναλλαγών</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n ώρες </numerusform><numerusform>%n ώρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n ημέρες </numerusform><numerusform>%n ημέρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n εβδομαδες</numerusform><numerusform>%n εβδομαδες</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 πίσω</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Το τελευταίο μπλοκ που ελήφθη δημιουργήθηκε %1 πριν.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Οι συναλλαγές μετά από αυτό δεν θα είναι ακόμη ορατες.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Σφάλμα</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Πληροφορία</translation>
</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>Η συναλλαγή ξεπερνάει το όριο.
Μπορεί να ολοκληρωθεί με μια αμοιβή των %1, η οποία αποδίδεται στους κόμβους που επεξεργάζονται τις συναλλαγές και βοηθούν στην υποστήριξη του δικτύου.
Θέλετε να συνεχίσετε;</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ενημερωμένο</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Ενημέρωση...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Επιβεβαίωση αμοιβής συναλλαγής</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Η συναλλαγή απεστάλη</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Εισερχόμενη συναλλαγή</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Ημερομηνία: %1
Ποσό: %2
Τύπος: %3
Διεύθυνση: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Χειρισμός URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Number7 address or malformed URI parameters.</source>
<translation>Το URI δεν μπορεί να αναλυθεί! Αυτό μπορεί να προκληθεί από μια μη έγκυρη διεύθυνση Number7 ή ακατάλληλη παραμέτρο URI.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>ξεκλείδωτο</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>κλειδωμένο</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Number7 can no longer continue safely and will quit.</source>
<translation>Παρουσιάστηκε ανεπανόρθωτο σφάλμα. Το Number7 δεν μπορεί πλέον να συνεχίσει με ασφάλεια και θα τερματισθει.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Ειδοποίηση Δικτύου</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Επεξεργασία Διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Η επιγραφή που σχετίζεται με αυτή την καταχώρηση του βιβλίου διευθύνσεων</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Διεύθυνση</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Η διεύθυνση που σχετίζεται με αυτή την καταχώρηση του βιβλίου διευθύνσεων. Μπορεί να τροποποιηθεί μόνο για τις διευθύνσεις αποστολής.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Νέα διεύθυνση λήψης</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Νέα διεύθυνση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Επεξεργασία διεύθυνσης λήψης</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Επεξεργασία διεύθυνσης αποστολής</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Η διεύθυνση "%1" βρίσκεται ήδη στο βιβλίο διευθύνσεων.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Number7 address.</source>
<translation>Η διεύθυνση "%1" δεν είναι έγκυρη Number7 διεύθυνση.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Δεν είναι δυνατό το ξεκλείδωμα του πορτοφολιού.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Η δημιουργία νέου κλειδιού απέτυχε.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Number7-Qt</source>
<translation>number7-qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>έκδοση</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>επιλογής γραμμής εντολών</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>επιλογές UI</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Όρισε γλώσσα, για παράδειγμα "de_DE"(προεπιλογή:τοπικές ρυθμίσεις)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Έναρξη ελαχιστοποιημένο</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Εμφάνισε την οθόνη εκκίνησης κατά την εκκίνηση(προεπιλογή:1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Ρυθμίσεις</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Κύριο</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Η προαιρετική αμοιβή για κάθε kB επισπεύδει την επεξεργασία των συναλλαγών σας. Οι περισσότερες συναλλαγές είναι 1 kB. </translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Αμοιβή &συναλλαγής</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Number7 after logging in to the system.</source>
<translation>Αυτόματη εκκίνηση του Number7 μετά την εισαγωγή στο σύστημα</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Number7 on system login</source>
<translation>&Έναρξη του Βιtcoin κατά την εκκίνηση του συστήματος</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Επαναφορα όλων των επιλογων του πελάτη σε default.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>Επαναφορα ρυθμίσεων</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Δίκτυο</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Number7 client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Αυτόματο άνοιγμα των θυρών Number7 στον δρομολογητή. Λειτουργεί μόνο αν ο δρομολογητής σας υποστηρίζει τη λειτουργία UPnP.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Απόδοση θυρών με χρήστη &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Number7 network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Σύνδεση στο Number7 δίκτυο μέσω διαμεσολαβητή SOCKS4 (π.χ. για σύνδεση μέσω Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Σύνδεση μέσω διαμεσολαβητή SOCKS</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP διαμεσολαβητή:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Διεύθυνση IP του διαμεσολαβητή (π.χ. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Θύρα:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Θύρα διαμεσολαβητή</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Έκδοση:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS εκδοση του διαμεσολαβητη (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Παράθυρο</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Εμφάνιση μόνο εικονιδίου στην περιοχή ειδοποιήσεων κατά την ελαχιστοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Ελαχιστοποίηση στην περιοχή ειδοποιήσεων αντί της γραμμής εργασιών</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Ελαχιστοποίηση αντί για έξοδο κατά το κλείσιμο του παραθύρου</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Ε&λαχιστοποίηση κατά το κλείσιμο</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>%Απεικόνιση</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Γλώσσα περιβάλλοντος εργασίας: </translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Number7.</source>
<translation>Εδώ μπορεί να ρυθμιστεί η γλώσσα διεπαφής χρήστη. Αυτή η ρύθμιση θα ισχύσει μετά την επανεκκίνηση του Number7.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Μονάδα μέτρησης:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Διαλέξτε την προεπιλεγμένη υποδιαίρεση που θα εμφανίζεται όταν στέλνετε νομίσματα.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Number7 addresses in the transaction list or not.</source>
<translation>Επιλέξτε αν θέλετε να εμφανίζονται οι διευθύνσεις Number7 στη λίστα συναλλαγών.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Εμφάνιση διευθύνσεων στη λίστα συναλλαγών</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&ΟΚ</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Ακύρωση</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Εφαρμογή</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>προεπιλογή</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Επιβεβαιώση των επιλογων επαναφοράς </translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Για ορισμένες ρυθμίσεις πρεπει η επανεκκίνηση να τεθεί σε ισχύ.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Θέλετε να προχωρήσετε;</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Number7.</source>
<translation>Αυτή η ρύθμιση θα ισχύσει μετά την επανεκκίνηση του Number7.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Number7 network after a connection is established, but this process has not completed yet.</source>
<translation>Οι πληροφορίες που εμφανίζονται μπορεί να είναι ξεπερασμένες. Το πορτοφόλι σας συγχρονίζεται αυτόματα με το δίκτυο Number7 μετά από μια σύνδεση, αλλά αυτή η διαδικασία δεν έχει ακόμη ολοκληρωθεί. </translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Υπόλοιπο</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Ανεπιβεβαίωτες</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Ανώριμος</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Εξορυγμενο υπόλοιπο που δεν έχει ακόμα ωριμάσει </translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Πρόσφατες συναλλαγές</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Το τρέχον υπόλοιπο</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Το άθροισμα των συναλλαγών που δεν έχουν ακόμα επιβεβαιωθεί και δεν προσμετρώνται στο τρέχον υπόλοιπό σας</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>εκτός συγχρονισμού</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start number7: click-to-pay handler</source>
<translation>Δεν είναι δυνατή η εκκίνηση του Number7: click-to-pay handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Κώδικας QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Αίτηση πληρωμής</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Ποσό:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Επιγραφή:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Μήνυμα:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Αποθήκευση ως...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Σφάλμα κατά την κωδικοποίηση του URI σε κώδικα QR</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Το αναγραφόμενο ποσό δεν είναι έγκυρο, παρακαλούμε να το ελέγξετε.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Το αποτέλεσμα της διεύθυνσης είναι πολύ μεγάλο. Μειώστε το μέγεθος για το κείμενο της ετικέτας/ μηνύματος.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Αποθήκευση κώδικα QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Εικόνες PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Όνομα Πελάτη</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>Μη διαθέσιμο</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Έκδοση Πελάτη</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Πληροφορία</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Χρησιμοποιηση της OpenSSL εκδοσης</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Χρόνος εκκίνησης</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Δίκτυο</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Αριθμός συνδέσεων</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Στο testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>αλυσίδα εμποδισμού</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Τρέχον αριθμός μπλοκ</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Κατ' εκτίμηση συνολικά μπλοκς</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Χρόνος τελευταίου μπλοκ</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Άνοιγμα</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>επιλογής γραμμής εντολών</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Number7-Qt help message to get a list with possible Number7 command-line options.</source>
<translation>Εμφανιση του Number7-Qt μήνυματος βοήθειας για να πάρετε μια λίστα με τις πιθανές επιλογές Number7 γραμμής εντολών.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Εμφάνιση</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Κονσόλα</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Ημερομηνία κατασκευής</translation>
</message>
<message>
<location line="-104"/>
<source>Number7 - Debug window</source>
<translation>Number7 - Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+25"/>
<source>Number7 Core</source>
<translation>Number7 Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Αρχείο καταγραφής εντοπισμού σφαλμάτων </translation>
</message>
<message>
<location line="+7"/>
<source>Open the Number7 debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Ανοίξτε το αρχείο καταγραφής εντοπισμού σφαλμάτων από τον τρέχοντα κατάλογο δεδομένων. Αυτό μπορεί να πάρει μερικά δευτερόλεπτα για τα μεγάλα αρχεία καταγραφής. </translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Καθαρισμός κονσόλας</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Number7 RPC console.</source>
<translation>Καλώς ήρθατε στην Number7 RPC κονσόλα.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Χρησιμοποιήστε το πάνω και κάτω βέλος για να περιηγηθείτε στο ιστορικο, και <b>Ctrl-L</b> για εκκαθαριση οθονης.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Γράψτε <b>βοήθεια</b> για μια επισκόπηση των διαθέσιμων εντολών</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Αποστολή σε πολλούς αποδέκτες ταυτόχρονα</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Προσθήκη αποδέκτη</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Διαγραφή όλων των πεδίων συναλλαγής</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Υπόλοιπο:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Επιβεβαίωση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>Αποστολη</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> σε %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Επιβεβαίωση αποστολής νομισμάτων</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Είστε βέβαιοι για την αποστολή %1;</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>και</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Η διεύθυνση του αποδέκτη δεν είναι σωστή. Παρακαλώ ελέγξτε ξανά.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Το ποσό πληρωμής πρέπει να είναι μεγαλύτερο από 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Το ποσό ξεπερνάει το διαθέσιμο υπόλοιπο</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Το σύνολο υπερβαίνει το υπόλοιπό σας όταν συμπεριληφθεί και η αμοιβή %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Βρέθηκε η ίδια διεύθυνση δύο φορές. Επιτρέπεται μία μόνο εγγραφή για κάθε διεύθυνση, σε κάθε διαδικασία αποστολής.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Σφάλμα: Η δημιουργία της συναλλαγής απέτυχε</translation>
</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>Σφάλμα: Η συναλλαγή απερρίφθη. Αυτό ενδέχεται να συμβαίνει αν κάποια από τα νομίσματα έχουν ήδη ξοδευθεί, όπως αν χρησιμοποιήσατε αντίγραφο του wallet.dat και τα νομίσματα ξοδεύθηκαν εκεί.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Ποσό:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Πληρωμή &σε:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Διεύθυνση αποστολής της πληρωμής (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</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>Εισάγετε μια επιγραφή για αυτή τη διεύθυνση ώστε να καταχωρηθεί στο βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Επιλογή διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Επικόλληση διεύθυνσης από το πρόχειρο</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Αφαίρεση αποδέκτη</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Number7 address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Εισάγετε μια διεύθυνση Number7 (π.χ. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Υπογραφές - Είσοδος / Επαλήθευση μήνυματος </translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Υπογραφή Μηνύματος</translation>
</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>Μπορείτε να υπογράφετε μηνύματα με τις διευθύνσεις σας, ώστε ν' αποδεικνύετε πως αυτές σας ανήκουν. Αποφεύγετε να υπογράφετε κάτι αόριστο καθώς ενδέχεται να εξαπατηθείτε. Υπογράφετε μόνο πλήρης δηλώσεις με τις οποίες συμφωνείτε.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Εισάγετε μια διεύθυνση Number7 (π.χ. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Επιλογή διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Επικόλληση διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Εισάγετε εδώ το μήνυμα που θέλετε να υπογράψετε</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Υπογραφή</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Αντέγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Number7 address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως σας ανήκει μια συγκεκριμένη διεύθυνση Number7</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Υπογραφη μήνυματος</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Επαναφορά όλων των πεδίων μήνυματος</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</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>Πληκτρολογήστε την υπογραφή διεύθυνσης, μήνυμα (βεβαιωθείτε ότι έχετε αντιγράψει τις αλλαγές γραμμής, κενά, tabs, κ.λπ. ακριβώς) και την υπογραφή παρακάτω, για να ελέγξει το μήνυμα. Να είστε προσεκτικοί για να μην διαβάσετε περισσότερα στην υπογραφή ό, τι είναι στην υπογραφή ίδιο το μήνυμα , για να μην εξαπατηθούν από έναν άνθρωπο -in - the-middle επίθεση.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Εισάγετε μια διεύθυνση Number7 (π.χ. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Number7 address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως υπογραφθηκε απο μια συγκεκριμένη διεύθυνση Number7</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Επαναφορά όλων επαλήθευμενων πεδίων μήνυματος </translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Number7 address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Εισάγετε μια διεύθυνση Number7 (π.χ. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Κάντε κλικ στο "Υπογραφή Μηνύματος" για να λάβετε την υπογραφή</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Number7 signature</source>
<translation>Εισαγωγή υπογραφής Number7</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Η διεύθυνση που εισήχθη είναι λάθος.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Παρακαλούμε ελέγξτε την διεύθυνση και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Η διεύθυνση που έχει εισαχθεί δεν αναφέρεται σε ένα πλήκτρο.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Το προσωπικό κλειδί εισαγμενης διευθυνσης δεν είναι διαθέσιμο.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Η υπογραφή του μηνύματος απέτυχε.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Μήνυμα υπεγράφη.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Η υπογραφή δεν μπόρεσε να αποκρυπτογραφηθεί.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Παρακαλούμε ελέγξτε την υπογραφή και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Η υπογραφή δεν ταιριάζει με το μήνυμα. </translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Η επιβεβαίωση του μηνύματος απέτυχε</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Μήνυμα επιβεβαιώθηκε.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Number7 developers</source>
<translation>Οι Number7 προγραμματιστές </translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/χωρίς σύνδεση;</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/χωρίς επιβεβαίωση</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 επιβεβαιώσεις</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Κατάσταση</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Πηγή</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Δημιουργία </translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Από</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Προς</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation> δική σας διεύθυνση </translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>eπιγραφή</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Πίστωση </translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>μη αποδεκτό</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Τέλος συναλλαγής </translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Καθαρό ποσό</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Μήνυμα</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Σχόλιο:</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID Συναλλαγής:</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 7 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>Πρέπει να περιμένετε 7 μπλοκ πριν μπορέσετε να χρησιμοποιήσετε τα νομίσματα που έχετε δημιουργήσει. Το μπλοκ που δημιουργήσατε μεταδόθηκε στο δίκτυο για να συμπεριληφθεί στην αλυσίδα των μπλοκ. Αν δεν μπει σε αυτή θα μετατραπεί σε "μη αποδεκτό" και δε θα μπορεί να καταναλωθεί. Αυτό συμβαίνει σπάνια όταν κάποιος άλλος κόμβος δημιουργήσει ένα μπλοκ λίγα δευτερόλεπτα πριν από εσάς.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Πληροφορίες αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Συναλλαγή</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>εισροές </translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>αληθής</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>αναληθής </translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, δεν έχει ακόμα μεταδοθεί μ' επιτυχία</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>άγνωστο</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Λεπτομέρειες συναλλαγής</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Αυτό το παράθυρο δείχνει μια λεπτομερή περιγραφή της συναλλαγής</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Τύπος</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Χωρίς σύνδεση (%1 επικυρώσεις)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Χωρίς επιβεβαίωση (%1 από %2 επικυρώσεις)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Επικυρωμένη (%1 επικυρώσεις)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Το υπόλοιπο από την εξόρυξη θα είναι διαθέσιμο μετά από %n μπλοκ</numerusform><numerusform>Το υπόλοιπο από την εξόρυξη θα είναι διαθέσιμο μετά από %n μπλοκ</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>Αυτό το μπλοκ δεν έχει παραληφθεί από κανέναν άλλο κόμβο και κατά πάσα πιθανότητα θα απορριφθεί!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Δημιουργήθηκε αλλά απορρίφθηκε</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Παραλαβή με</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ελήφθη από</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Αποστολή προς</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Πληρωμή προς εσάς</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Εξόρυξη</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(δ/α)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Κατάσταση συναλλαγής. Πηγαίνετε το ποντίκι πάνω από αυτό το πεδίο για να δείτε τον αριθμό των επικυρώσεων</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Ημερομηνία κι ώρα λήψης της συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Είδος συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Διεύθυνση αποστολής της συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Ποσό που αφαιρέθηκε ή προστέθηκε στο υπόλοιπο.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Όλα</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Σήμερα</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Αυτή την εβδομάδα</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Αυτόν τον μήνα</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Τον προηγούμενο μήνα</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Αυτό το έτος</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Έκταση...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Ελήφθη με</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Απεστάλη προς</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Προς εσάς</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Εξόρυξη</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Άλλο</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Αναζήτηση με βάση τη διεύθυνση ή την επιγραφή</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Ελάχιστο ποσό</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Αντιγραφή επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Αντιγραφή ποσού</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Αντιγραφη του ID Συναλλαγής</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Επεξεργασία επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Εμφάνιση λεπτομερειών συναλλαγής</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Εξαγωγή Στοιχείων Συναλλαγών</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Επικυρωμένες</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Τύπος</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Επιγραφή</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Σφάλμα εξαγωγής</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Αδυναμία εγγραφής στο αρχείο %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Έκταση:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>έως</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Εξαγωγή</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Εξαγωγή δεδομένων καρτέλας σε αρχείο</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Αρχεία δεδομένων πορτοφολιού (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Αποτυχία κατά τη δημιουργία αντιγράφου</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Παρουσιάστηκε σφάλμα κατά την αποθήκευση των δεδομένων πορτοφολιού στη νέα τοποθεσία.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Η δημιουργια αντιγραφου ασφαλειας πετυχε</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Τα δεδομένα πορτοφόλιου αποθηκεύτηκαν με επιτυχία στη νέα θέση. </translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Number7 version</source>
<translation>Έκδοση Number7</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or number7d</source>
<translation>Αποστολή εντολής στον εξυπηρετητή ή στο number7d</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Λίστα εντολών</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Επεξήγηση εντολής</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Επιλογές:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: number7.conf)</source>
<translation>Ορίστε αρχείο ρυθμίσεων (προεπιλογή: number7.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: number7d.pid)</source>
<translation>Ορίστε αρχείο pid (προεπιλογή: number7d.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Ορισμός φακέλου δεδομένων</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Όρισε το μέγεθος της βάσης προσωρινής αποθήκευσης σε megabytes(προεπιλογή:25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 6093 or testnet: 16093)</source>
<translation>Εισερχόμενες συνδέσεις στη θύρα <port> (προεπιλογή: 6093 ή στο testnet: 16093)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Μέγιστες αριθμός συνδέσεων με τους peers <n> (προεπιλογή: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Σύνδεση σε έναν κόμβο για την ανάκτηση διευθύνσεων από ομοτίμους, και αποσυνδέσh</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Διευκρινίστε τη δικιά σας δημόσια διεύθυνση.</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Όριο αποσύνδεσης προβληματικών peers (προεπιλογή: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Δευτερόλεπτα πριν επιτραπεί ξανά η σύνδεση των προβληματικών peers (προεπιλογή: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η πόρτα RPC %u για αναμονή IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 6094 or testnet: 16094)</source>
<translation>Εισερχόμενες συνδέσεις JSON-RPC στη θύρα <port> (προεπιλογή: 6094 or testnet: 16094)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Αποδοχή εντολών κονσόλας και JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Εκτέλεση στο παρασκήνιο κι αποδοχή εντολών</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Χρήση του δοκιμαστικού δικτύου</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Να δέχεσαι συνδέσεις από έξω(προεπιλογή:1)</translation>
</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=number7rpc
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 "Number7 Alert" admin@foo.com
</source>
<translation>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=number7rpc
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 "Number7 Alert" admin@foo.com
</translation>
</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>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η υποδοχη RPC %u για αναμονη του IPv6, επεσε πισω στο IPv4:%s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Αποθηκευση σε συγκεκριμένη διεύθυνση. Χρησιμοποιήστε τα πλήκτρα [Host] : συμβολισμός θύρα για IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Number7 is probably already running.</source>
<translation>Αδυναμία κλειδώματος του φακέλου δεδομένων %s. Πιθανώς το Number7 να είναι ήδη ενεργό.</translation>
</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>Σφάλμα: Η συναλλαγή απορρίφθηκε.
Αυτό ίσως οφείλεται στο ότι τα νομίσματά σας έχουν ήδη ξοδευτεί, π.χ. με την αντιγραφή του wallet.dat σε άλλο σύστημα και την χρήση τους εκεί, χωρίς η συναλλαγή να έχει καταγραφεί στο παρόν σύστημα.</translation>
</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>Σφάλμα: Αυτή η συναλλαγή απαιτεί αμοιβή συναλλαγής τουλάχιστον %s λόγω του μεγέθους, πολυπλοκότητας ή της χρήσης πρόσφατης παραλαβής κεφαλαίου</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Εκτέλεση της εντολής όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Ορίστε το μέγιστο μέγεθος των high-priority/low-fee συναλλαγων σε bytes (προεπιλογή: 27000)</translation>
</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>Αυτό είναι ένα προ-τεστ κυκλοφορίας - χρησιμοποιήστε το με δική σας ευθύνη - δεν χρησιμοποιείτε για εξόρυξη ή για αλλες εφαρμογές</translation>
</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>Προειδοποίηση: Η παράμετρος -paytxfee είναι πολύ υψηλή. Πρόκειται για την αμοιβή που θα πληρώνετε για κάθε συναλλαγή που θα στέλνετε.</translation>
</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>Προειδοποίηση: Εμφανίσεις συναλλαγων δεν μπορεί να είναι σωστες! Μπορεί να χρειαστεί να αναβαθμίσετε, ή άλλοι κόμβοι μπορεί να χρειαστεί να αναβαθμίστουν. </translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Number7 will not work properly.</source>
<translation>Προειδοποίηση: Παρακαλώ βεβαιωθείτε πως η ημερομηνία κι ώρα του συστήματός σας είναι σωστές. Αν το ρολόι του υπολογιστή σας πάει λάθος, ενδέχεται να μη λειτουργεί σωστά το Number7.</translation>
</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>Προειδοποίηση : Σφάλμα wallet.dat κατα την ανάγνωση ! Όλα τα κλειδιά αναγνωρισθηκαν σωστά, αλλά τα δεδομένα των συναλλαγών ή καταχωρήσεις στο βιβλίο διευθύνσεων μπορεί να είναι ελλιπείς ή λανθασμένα. </translation>
</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>Προειδοποίηση : το αρχειο wallet.dat ειναι διεφθαρμένο, τα δεδομένα σώζονται ! Original wallet.dat αποθηκεύονται ως πορτοφόλι { timestamp } bak στο % s ? . . Αν το υπόλοιπο του ή τις συναλλαγές σας, είναι λάθος θα πρέπει να επαναφέρετε από ένα αντίγραφο ασφαλείας</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Προσπάθεια για ανακτησει ιδιωτικων κλειδιων από ενα διεφθαρμένο αρχειο wallet.dat </translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Αποκλεισμός επιλογων δημιουργίας: </translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Σύνδεση μόνο με ορισμένους κόμβους</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Εντοπισθηκε διεφθαρμενη βαση δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Ανακαλύψτε την δικη σας IP διεύθυνση (προεπιλογή: 1 όταν ακούει και δεν - externalip) </translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Θελετε να δημιουργηθει τωρα η βαση δεδομενων του μπλοκ? </translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Σφάλμα κατά την ενεργοποίηση της βάσης δεδομένων μπλοκ</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Σφάλμα κατά την ενεργοποίηση της βάσης δεδομένων πορτοφόλιου %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Σφάλμα φορτωσης της βασης δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Σφάλμα φορτωσης της βασης δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Προειδοποίηση: Χαμηλός χώρος στο δίσκο </translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Σφάλμα: το πορτοφόλι είναι κλειδωμένο, δεν μπορεί να δημιουργηθεί συναλλαγή</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Λάθος: λάθος συστήματος:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>ταλαιπωρηθειτε για να ακούσετε σε οποιαδήποτε θύρα. Χρήση - ακούστε = 0 , αν θέλετε αυτό.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Αποτυχία αναγνωσης των block πληροφοριων</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Η αναγνωση του μπλοκ απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Ο συγχρονισμος του μπλοκ ευρετηριου απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Η δημιουργια του μπλοκ ευρετηριου απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Η δημιουργια των μπλοκ πληροφοριων απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Η δημιουργια του μπλοκ απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Αδυναμία εγγραφής πληροφοριων αρχειου</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Αποτυχία εγγραφής στη βάση δεδομένων νομίσματος</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Αποτυχία εγγραφής δείκτη συναλλαγών </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Αποτυχία εγγραφής αναίρεσης δεδομένων </translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Βρες ομότιμους υπολογιστές χρησιμοποιώντας αναζήτηση DNS(προεπιλογή:1)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Δημιουργία νομισμάτων (προκαθορισμος: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Πόσα μπλοκ να ελέγχθουν κατά την εκκίνηση (προεπιλογή:288,0=όλα)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Πόσο εξονυχιστική να είναι η επιβεβαίωση του μπλοκ(0-4, προεπιλογή:3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Δεν ειναι αρκετες περιγραφες αρχείων διαθέσιμες.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Εισαγωγή μπλοκ από εξωτερικό αρχείο blk000?.dat</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Ορίσμος του αριθμόυ θεματων στην υπηρεσία κλήσεων RPC (προεπιλογή: 4) </translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Επαλήθευση των μπλοκ... </translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Επαλήθευση πορτοφολιου... </translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Εισαγωγή μπλοκ από εξωτερικό αρχείο blk000?.dat</translation>
</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>Ορίσμος του αριθμό των νημάτων ελέγχου σεναρίου (μέχρι 16, 0 = auto, <0 = αφήνουν τους πολλους πυρήνες δωρεάν, default: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Πληροφορία</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Διατηρήση ένος πλήρες ευρετήριου συναλλαγών (προεπιλογή: 0) </translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Μέγιστος buffer λήψης ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Μέγιστος buffer αποστολής ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Μονο αποδοχη αλυσίδας μπλοκ που ταιριάζει με τα ενσωματωμένα σημεία ελέγχου (προεπιλογή: 1) </translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation> Συνδέση μόνο σε κόμβους του δικτύου <net> (IPv4, IPv6 ή Tor) </translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Έξοδος επιπλέον πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Έξοδος επιπλέον πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Χρονοσφραγίδα πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Number7 Wiki for SSL setup instructions)</source>
<translation>Ρυθμίσεις SSL: (ανατρέξτε στο Number7 Wiki για οδηγίες ρυθμίσεων SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Επιλέξτε την έκδοση του διαμεσολαβητη για να χρησιμοποιήσετε (4-5 , προεπιλογή: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στην κονσόλα αντί του αρχείου debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στον debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Ορίσμος του μέγιστου μέγεθος block σε bytes (προεπιλογή: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Ορίστε το μέγιστο μέγεθος block σε bytes (προεπιλογή: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Συρρίκνωση του αρχείο debug.log κατα την εκκίνηση του πελάτη (προεπιλογή: 1 όταν δεν-debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Η υπογραφή συναλλαγής απέτυχε </translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Ορισμός λήξης χρονικού ορίου σε χιλιοστά του δευτερολέπτου(προεπιλογή:5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Λάθος Συστήματος:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Το ποσό της συναλλαγής είναι πολύ μικρο </translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Τα ποσά των συναλλαγών πρέπει να είναι θετικα</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Η συναλλαγή ειναι πολύ μεγάλη </translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:1)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Χρήση διακομιστή μεσολάβησης για την επίτευξη των Tor κρυμμένων υπηρεσιων (προεπιλογή: ίδιο με το-proxy) </translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Όνομα χρήστη για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Προειδοποίηση: Αυτή η έκδοση είναι ξεπερασμένη, απαιτείται αναβάθμιση </translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Θα πρέπει να ξαναχτίστουν οι βάσεις δεδομένων που χρησιμοποιούντε-Αναδημιουργία αλλάγων-txindex </translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>Το αρχειο wallet.dat ειναι διεφθαρμένο, η διάσωση απέτυχε</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Κωδικός για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Αποδοχή συνδέσεων JSON-RPC από συγκεκριμένη διεύθυνση IP</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Αποστολή εντολών στον κόμβο <ip> (προεπιλογή: 127.0.0.1)</translation>
</message>
<message>
<location line="-7"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Αναβάθμισε το πορτοφόλι στην τελευταία έκδοση</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Όριο πλήθους κλειδιών pool <n> (προεπιλογή: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Επανέλεγχος της αλυσίδας μπλοκ για απούσες συναλλαγές</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Χρήση του OpenSSL (https) για συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Αρχείο πιστοποιητικού του διακομιστή (προεπιλογή: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Προσωπικό κλειδί του διακομιστή (προεπιλογή: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Αποδεκτά κρυπτογραφήματα (προεπιλογή: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Αυτό το κείμενο βοήθειας</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή (bind returned error %d, %s) </translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Σύνδεση μέσω διαμεσολαβητή socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Να επιτρέπονται οι έλεγχοι DNS για προσθήκη και σύνδεση κόμβων</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Φόρτωση διευθύνσεων...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Κατεστραμμένο Πορτοφόλι</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Number7</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Το Πορτοφόλι απαιτεί μια νεότερη έκδοση του Number7</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Number7 to complete</source>
<translation>Απαιτείται η επανεγγραφή του Πορτοφολιού, η οποία θα ολοκληρωθεί στην επανεκκίνηση του Number7</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Σφάλμα φόρτωσης αρχείου wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Άγνωστo δίκτυο ορίζεται σε onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Άγνωστo δίκτυο ορίζεται: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Λάθος ποσότητα</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Ανεπαρκές κεφάλαιο</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Προσέθεσε ένα κόμβο για σύνδεση και προσπάθησε να κρατήσεις την σύνδεση ανοιχτή</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Number7 is probably already running.</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή. Το Number7 είναι πιθανώς ήδη ενεργό.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Αμοιβή ανά KB που θα προστίθεται στις συναλλαγές που στέλνεις</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Φόρτωση πορτοφολιού...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Δεν μπορώ να υποβαθμίσω το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Ανίχνευση...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Η φόρτωση ολοκληρώθηκε</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Χρήση της %s επιλογής</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Σφάλμα</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Πρέπει να βάλεις ένα κωδικό στο αρχείο παραμέτρων: %s
Εάν το αρχείο δεν υπάρχει, δημιούργησε το με δικαιώματα μόνο για ανάγνωση από τον δημιουργό</translation>
</message>
</context>
</TS> | number7team/number7 | src/qt/locale/bitcoin_el_GR.ts | TypeScript | mit | 138,071 |
var _ = require("underscore"),
Events = require("./Events"),
querystring = require("querystring"),
httpClient = require("./httpClient"),
utils = require("./utils"),
logger = require("config-logger");
var environments = {
sandbox: {
restHost: "api-sandbox.oanda.com",
streamHost: "stream-sandbox.oanda.com",
secure: false
},
practice: {
restHost: "api-fxpractice.oanda.com",
streamHost: "stream-fxpractice.oanda.com"
},
live: {
restHost: "api-fxtrade.oanda.com",
streamHost: "stream-fxtrade.oanda.com"
}
};
var maxRequestsPerSecond = 15,
maxRequestsWarningThreshold = 1000;
/*
* config.environment
* config.accessToken
* config.username (Sandbox only)
*/
function OandaAdapter (config) {
config.environment = config.environment || "practice";
// this.accountId = accountId;
this.accessToken = config.accessToken;
this.restHost = environments[config.environment].restHost;
this.streamHost = environments[config.environment].streamHost;
this.secure = environments[config.environment].secure;
if (config.environment === "sandbox") {
this.username = config.username;
}
this.subscriptions = {};
this._eventsBuffer = [];
this._pricesBuffer = [];
this._sendRESTRequest = utils.rateLimit(this._sendRESTRequest, this, 1000 / maxRequestsPerSecond, maxRequestsWarningThreshold);
}
Events.mixin(OandaAdapter.prototype);
/*
* Subscribes to events for all accounts authorized by the token
*/
OandaAdapter.prototype.subscribeEvents = function (listener, context) {
var existingSubscriptions = this.getHandlers("event");
this.off("event", listener, context);
this.on("event", listener, context);
if (existingSubscriptions.length === 0) {
this._streamEvents();
}
};
OandaAdapter.prototype.unsubscribeEvents = function (listener, context) {
this.off("event", listener, context);
this._streamEvents();
};
OandaAdapter.prototype._streamEvents = function () {
var subscriptionCount = this.getHandlers("event").length;
if (this.eventsRequest) {
this.eventsRequest.abort();
}
if (subscriptionCount === 0) {
return;
}
clearTimeout(this.eventsTimeout);
this.eventsTimeout = setTimeout(this._eventsHeartbeatTimeout.bind(this), 20000);
this.eventsRequest = httpClient.sendRequest({
hostname: this.streamHost,
method: "GET",
path: "/v1/events",
headers: {
Authorization: "Bearer " + this.accessToken,
Connection: "Keep-Alive"
},
secure: this.secure
},
this._onEventsResponse.bind(this),
this._onEventsData.bind(this)
);
};
OandaAdapter.prototype._onEventsResponse = function (error, body, statusCode) {
if (statusCode !== 200) {
if (body && body.disconnect) {
this.trigger("message", null, "Events streaming API disconnected.\nOanda code " + body.disconnect.code + ": " + body.disconnect.message);
} else {
this.trigger("message", null, "Events streaming API disconnected with status " + statusCode);
}
}
clearTimeout(this.eventsTimeout);
this.eventsTimeout = setTimeout(this._eventsHeartbeatTimeout.bind(this), 20000);
};
OandaAdapter.prototype._onEventsData = function (data) {
// Single chunks sometimes contain more than one event. Each always end with /r/n. Whole chunk therefore not JSON parsable, so must split.
// Also, an event may be split accross data chunks, so must buffer.
data.split(/\r\n/).forEach(function (line) {
var update;
if (line) {
this._eventsBuffer.push(line);
try {
update = JSON.parse(this._eventsBuffer.join(""));
} catch (error) {
if (this._eventsBuffer.length <= 5) {
// Wait for next line.
return;
}
logger.error("Unable to parse Oanda events subscription update", this._eventsBuffer.join("\n"), error);
this._eventsBuffer = [];
return;
}
this._eventsBuffer = [];
if (update.heartbeat) {
clearTimeout(this.eventsTimeout);
this.eventsTimeout = setTimeout(this._eventsHeartbeatTimeout.bind(this), 20000);
return;
}
this.trigger("event", update);
}
}, this);
};
OandaAdapter.prototype._eventsHeartbeatTimeout = function () {
logger.warn("OandaAdapter: No heartbeat received from events stream for 20 seconds. Reconnecting.");
this._streamEvents();
};
OandaAdapter.prototype.getAccounts = function (callback) {
this._sendRESTRequest({
method: "GET",
path: "/v1/accounts" + (this.username ? "?username=" + this.username : "")
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body.accounts) {
callback(null, body.accounts);
} else {
callback("Unexpected accounts response");
}
});
};
OandaAdapter.prototype.getAccount = function (accountId, callback) {
this._sendRESTRequest({
method: "GET",
path: "/v1/accounts/" + accountId
}, callback);
};
OandaAdapter.prototype.getInstruments = function (accountId, callback) {
this._sendRESTRequest({
method: "GET",
path: "/v1/instruments?accountId=" + accountId + "&fields=" + ["instrument", "displayName", "pip", "maxTradeUnits", "precision", "maxTrailingStop", "minTrailingStop", "marginRate", "halted"].join("%2C"),
},
function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body.instruments) {
callback(null, body.instruments);
} else {
callback("Unexpected instruments response");
}
});
};
OandaAdapter.prototype.getPrice = function (symbol, callback) {
var multiple = _.isArray(symbol);
if (multiple) {
symbol = symbol.join("%2C");
}
this._sendRESTRequest({
method: "GET",
path: "/v1/prices?instruments=" + symbol
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body && body.prices[0]) {
callback(null, multiple ? body.prices : body.prices[0]);
} else {
callback("Unexpected price response for " + symbol);
}
});
};
OandaAdapter.prototype.subscribePrice = function (accountId, symbol, listener, context) {
var existingSubscriptions = this.getHandlers("price/" + symbol);
// Price stream needs an accountId to be passed for streaming prices, though prices for a connection are same anyway
if (!this.streamPrices) {
this.streamPrices = _.throttle(this._streamPrices.bind(this, accountId));
}
this.off("price/" + symbol, listener, context);
this.on("price/" + symbol, listener, context);
if (existingSubscriptions.length === 0) {
this.streamPrices();
}
};
OandaAdapter.prototype.unsubscribePrice = function (symbol, listener, context) {
this.off("price/" + symbol, listener, context);
this.streamPrices();
};
// Kills rates streaming keep alive request for account and creates a new one whenever subsciption list changes. Should always be throttled.
OandaAdapter.prototype._streamPrices = function (accountId) {
var changed;
this.priceSubscriptions = Object.keys(this.getHandlers()).reduce(function (memo, event) {
var match = event.match("^price/(.+)$");
if (match) {
memo.push(match[1]);
}
return memo;
}, []).sort().join("%2C");
changed = !this.lastPriceSubscriptions || this.priceSubscriptions !== this.lastPriceSubscriptions;
this.lastPriceSubscriptions = this.priceSubscriptions;
if (!changed) {
return;
}
if (this.pricesRequest) {
this.pricesRequest.abort();
}
if (this.priceSubscriptions === "") {
return;
}
clearTimeout(this.pricesTimeout);
this.pricesTimeout = setTimeout(this._pricesHeartbeatTimeout.bind(this), 10000);
this.pricesRequest = httpClient.sendRequest({
hostname: this.streamHost,
method: "GET",
path: "/v1/prices?accountId=" + accountId + "&instruments=" + this.priceSubscriptions,
headers: {
Authorization: "Bearer " + this.accessToken,
Connection: "Keep-Alive"
},
secure: this.secure
},
this._onPricesResponse.bind(this, accountId),
this._onPricesData.bind(this)
);
};
OandaAdapter.prototype._onPricesResponse = function (accountId, error, body, statusCode) {
if (statusCode !== 200) {
if (body && body.disconnect) {
this.trigger("message", accountId, "Prices streaming API disconnected.\nOanda code " + body.disconnect.code + ": " + body.disconnect.message);
} else {
this.trigger("message", accountId, "Prices streaming API disconnected with status " + statusCode);
}
}
clearTimeout(this.pricesTimeout);
this.pricesTimeout = setTimeout(this._pricesHeartbeatTimeout.bind(this), 10000);
};
OandaAdapter.prototype._onPricesData = function (data) {
// Single data chunks sometimes contain more than one tick. Each always end with /r/n. Whole chunk therefore not JSON parsable, so must split.
// A tick may also be split accross data chunks, so must buffer
data.split(/\r\n/).forEach(function (line) {
var update;
if (line) {
this._pricesBuffer.push(line);
try {
update = JSON.parse(this._pricesBuffer.join(""));
} catch (error) {
if (this._pricesBuffer.length <= 5) {
// Wait for next update.
return;
}
// Drop if cannot produce object after 5 updates
logger.error("Unable to parse Oanda price subscription update", this._pricesBuffer.join("\n"), error);
this._pricesBuffer = [];
return;
}
this._pricesBuffer = [];
if (update.heartbeat) {
clearTimeout(this.pricesTimeout);
this.pricesTimeout = setTimeout(this._pricesHeartbeatTimeout.bind(this), 10000);
return;
}
if (update.tick) {
update.tick.time = new Date(update.tick.time);
this.trigger("price/" + update.tick.instrument, update.tick);
}
}
}, this);
};
OandaAdapter.prototype._pricesHeartbeatTimeout = function () {
logger.warn("OandaAdapter: No heartbeat received from prices stream for 10 seconds. Reconnecting.");
delete this.lastPriceSubscriptions;
this._streamPrices();
};
/**
* Get historical price information about an instrument in candlestick format as defined at
* http://developer.oanda.com/rest-live/rates/#aboutCandlestickRepresentation
*/
OandaAdapter.prototype.getCandles = function (instrument, options, callback)
{
options = _.extend(options, {instrument: instrument});
this._sendRESTRequest({
method: "GET",
path: "/v1/candles?" + querystring.stringify(options),
headers: {
Authorization: "Bearer " + this.accessToken,
"X-Accept-Datetime-Format": "UNIX"
}
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body && body.candles) {
callback(null, body.candles);
} else if (body === "") {
// Body is an empty string if there are no candles to return
callback(null, []);
} else {
callback("Unexpected candles response for " + symbol);
}
});
};
OandaAdapter.prototype.getOpenPositions = function (accountId, callback) {
this._sendRESTRequest({
method: "GET",
path: "/v1/accounts/" + accountId + "/positions"
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body && body.positions) {
callback(null, body.positions);
} else {
callback("Unexpected response for open positions");
}
});
};
OandaAdapter.prototype.getOpenTrades = function (accountId, callback) {
this._sendRESTRequest({
method: "GET",
path: "/v1/accounts/" + accountId + "/trades"
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body && body.trades) {
callback(null, body.trades);
} else {
callback("Unexpected response for open trades");
}
});
};
/**
* @method createOrder
* @param {String} accountId Required.
* @param {Object} order
* @param {String} order.instrument Required. Instrument to open the order on.
* @param {Number} order.units Required. The number of units to open order for.
* @param {String} order.side Required. Direction of the order, either ‘buy’ or ‘sell’.
* @param {String} order.type Required. The type of the order ‘limit’, ‘stop’, ‘marketIfTouched’ or ‘market’.
* @param {String} order.expiry Required. If order type is ‘limit’, ‘stop’, or ‘marketIfTouched’. The value specified must be in a valid datetime format.
* @param {String} order.price Required. If order type is ‘limit’, ‘stop’, or ‘marketIfTouched’. The price where the order is set to trigger at.
* @param {Number} order.lowerBound Optional. The minimum execution price.
* @param {Number} order.upperBound Optional. The maximum execution price.
* @param {Number} order.stopLoss Optional. The stop loss price.
* @param {Number} order.takeProfit Optional. The take profit price.
* @param {Number} order.trailingStop Optional The trailing stop distance in pips, up to one decimal place.
* @param {Function} callback
*/
OandaAdapter.prototype.createOrder = function (accountId, order, callback) {
if (!order.instrument) {
return callback("'instrument' is a required field");
}
if (!order.units) {
return callback("'units' is a required field");
}
if (!order.side) {
return callback("'side' is a required field. Specify 'buy' or 'sell'");
}
if (!order.type) {
return callback("'type' is a required field. Specify 'market', 'marketIfTouched', 'stop' or 'limit'");
}
if ((order.type !== "market") && !order.expiry) {
return callback("'expiry' is a required field for order type '" + order.type + "'");
}
if ((order.type !== "market") && !order.price) {
return callback("'price' is a required field for order type '" + order.type + "'");
}
this._sendRESTRequest({
method: "POST",
path: "/v1/accounts/" + accountId + "/orders",
data: order,
headers: {
Authorization: "Bearer " + this.accessToken,
"Content-Type": "application/x-www-form-urlencoded"
},
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
callback(null, body);
});
};
OandaAdapter.prototype.closeTrade = function (accountId, tradeId, callback) {
this._sendRESTRequest({
method: "DELETE",
path: "/v1/accounts/" + accountId + "/trades/" + tradeId
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
if (body) {
callback(null, body);
} else {
callback("Unexpected response for open positions");
}
});
};
OandaAdapter.prototype.getOrders = function (accountId, callback)
{
this._sendRESTRequest({
method: "GET",
path: "/v1/accounts/" + accountId + "/orders",
headers: {
Authorization: "Bearer " + this.accessToken,
"Content-Type": "application/x-www-form-urlencoded"
},
}, function (error, body, statusCode) {
if (error) {
if (body && body.message) {
logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")");
return callback(body.message);
}
return callback(error);
}
callback(null, body);
});
};
OandaAdapter.prototype._sendRESTRequest = function (request, callback) {
request.hostname = this.restHost;
request.headers = request.headers || {
Authorization: "Bearer " + this.accessToken
};
request.secure = this.secure;
httpClient.sendRequest(request, callback);
};
OandaAdapter.prototype.kill = function () {
if (this.pricesRequest) {
this.pricesRequest.abort();
}
if (this.eventsRequest) {
this.eventsRequest.abort();
}
this.off();
};
module.exports = OandaAdapter; | naddison36/oanda-adapter | OandaAdapter.js | JavaScript | mit | 19,053 |
require "mscorlib"
require "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
require "System.Collections.Generic, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
require "System.Linq, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
require "System.Text, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
module CodeBuilder.DataSource.Exporter
require "PhysicalDataModel, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
class SqlServer2000Exporter < BaseExporter, IExporter
def Export(connectionString)
if connectionString == nil then
raise ArgumentNullException.new("connectionString", "Argument is null")
end
model = Model.new()
model.Database = "SqlServer2000"
return model
end
def GetTables()
return nil
end
def GetViews()
return nil
end
def GetColumns()
return nil
end
def GetKeys()
return nil
end
def GetPrimaryKeys()
return nil
end
end
end | xianrendzw/CodeBuilder.Ruby | CodeBuilder.Framework/Exporter/SQLServer/SqlServer2000Exporter.rb | Ruby | mit | 1,015 |
package com.semmle.jcorn;
import com.semmle.js.ast.Position;
public class SyntaxError extends RuntimeException {
private static final long serialVersionUID = -4883173648492364902L;
private final Position position;
public SyntaxError(String msg, Position loc, int raisedAt) {
super(msg);
this.position = loc;
}
public Position getPosition() {
return position;
}
}
| github/codeql | javascript/extractor/src/com/semmle/jcorn/SyntaxError.java | Java | mit | 392 |
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = Math.floor(Math.random() * 101);
}
insertionsort(nums);
dispArr(nums);
print();
putstr("Enter a value to count: ");
var val = parseInt(readline());
var retVal = count(nums, val);
print("Found " + retVal + " occurrences of " + val + ".");
| jomjose/js-algorithms | queues/queues (15).js | JavaScript | mit | 309 |
/**
* This package provides the necessary classes to slice and compose a file.
*
* @author Sergio Merino
*/
package assembler; | merinhunter/SecureApp | assembler/package-info.java | Java | mit | 131 |
import imageContainer from '../server/api/helpers/imageContainer';
const entries = [
{
html: '<img src="/img/60x30.png" alt="60x30" class="zoom" data-zoom-src="/img/60x30-original.png">',
},
{
html: `<div>
<img src="/img/20x50.jpg">
</div>
<img src="/img/40x10.svg" alt="40x10">`,
},
{
html: '<div>Hello, World!</div>',
},
];
describe('ImageContainer', () => {
const modifiedEntries = imageContainer(entries, __dirname);
it('Parses one image', () => {
expect(modifiedEntries[0].html).toContain('<div class="imageContainer" style="width: 60px;">');
expect(modifiedEntries[0].html).toContain('<div style="padding-bottom: 50%">');
});
it('Parses multiple images', () => {
expect(modifiedEntries[1].html).toContain('<div class="imageContainer" style="width: 20px;">');
expect(modifiedEntries[1].html).toContain('<div style="padding-bottom: 250%">');
expect(modifiedEntries[1].html).toContain('<div class="imageContainer" style="width: 40px;">');
expect(modifiedEntries[1].html).toContain('<div style="padding-bottom: 25%">');
});
it('Doesn’t parse things it shouldn’t', () => {
expect(modifiedEntries[2].html.length).toEqual(entries[2].html.length);
});
it('Doesn’t crash when passing in an empty array', () => {
const emptyEntries = [];
expect(emptyEntries).toEqual(imageContainer(emptyEntries));
});
});
| JohanLi/johanli.com | test/imageContainer.test.js | JavaScript | mit | 1,395 |
package betterwithaddons.crafting.recipes;
import betterwithaddons.crafting.ICraftingResult;
import betterwithaddons.util.ItemUtil;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class PackingRecipe
{
public ICraftingResult output;
public List<Ingredient> inputs;
public PackingRecipe(List<Ingredient> inputs, ICraftingResult output) {
this.output = output;
this.inputs = inputs;
}
public ICraftingResult getOutput(List<ItemStack> inputs, IBlockState compressState) {
return this.output.copy();
}
public boolean consume(List<ItemStack> inputs, IBlockState compressState, boolean simulate)
{
inputs = new ArrayList<>(inputs);
for (Ingredient ingredient : this.inputs) {
boolean matches = false;
Iterator<ItemStack> iterator = inputs.iterator();
while(iterator.hasNext()) {
ItemStack checkStack = iterator.next();
if(ingredient.apply(checkStack)) {
if(!simulate)
checkStack.shrink(ItemUtil.getSize(ingredient));
iterator.remove();
matches = true;
}
}
if(!matches)
return false;
}
return true;
}
} | DaedalusGame/BetterWithAddons | src/main/java/betterwithaddons/crafting/recipes/PackingRecipe.java | Java | mit | 1,468 |
<?php
namespace Frontend42;
return [
'migration' => [
'directory' => [
__NAMESPACE__ => __DIR__ . '/../../data/migrations'
],
],
];
| raum42/frontend42 | config/cli/migration.config.php | PHP | mit | 174 |
{{ Form::label('title', __('validation.attributes.title'), ['class' => 'label']) }}
<div class="mb-4">
{{ Form::text('title', old('title', $category->title), ['class' => 'input' . ($errors->has('title') ? ' has-error' : ''), 'required' => true]) }}
@if ($errors->has('title'))
<div class="invalid-feedback">
{{ $errors->first('title') }}
</div>
@endif
</div>
@include('shared._form_color', ['item' => $category])
{{ Form::button($submitTitle, ['type' => 'submit', 'class' => 'btn btn-primary']) }}
| Kaishiyoku/Crystal-RSS | resources/views/category/_form.blade.php | PHP | mit | 542 |
using System.ComponentModel;
namespace LinqAn.Google.Dimensions
{
/// <summary>
/// DCM creative type name of the DCM click matching the Google Analytics session (premium only).
/// </summary>
[Description("DCM creative type name of the DCM click matching the Google Analytics session (premium only).")]
public class DcmClickCreativeType: Dimension
{
/// <summary>
/// Instantiates a <seealso cref="DcmClickCreativeType" />.
/// </summary>
public DcmClickCreativeType(): base("DFA Creative Type (GA Model)",false,"ga:dcmClickCreativeType")
{
}
}
}
| kenshinthebattosai/LinqAn.Google | src/LinqAn.Google/Dimensions/DcmClickCreativeType.cs | C# | mit | 575 |
#include <QDebug>
#include <QFileDialog>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QProcess>
#include <QWidget>
#include "app.h"
#include "import.h"
#include "ui_import.h"
Import::Import(App* app) :
app(app),
platform(-1) {
this->ui.setupUi(this);
connect(this->ui.toolFilepath, SIGNAL(clicked()), this, SLOT(onFilepathTool()));
connect(this->ui.start, SIGNAL(clicked()), this, SLOT(onStart()));
connect(this->ui.filepath, SIGNAL(textChanged(const QString&)), this, SLOT(onFilepathChange()));
connect(&importProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(onImportFinished()));
}
Import::~Import() {
this->ui.filepath->setText("");
this->ui.start->setEnabled(false);
}
void Import::reset() {
}
void Import::onFilepathTool() {
QFileDialog fileDialog(this);
fileDialog.setOption(QFileDialog::DontUseNativeDialog, true);
connect(&fileDialog, SIGNAL(fileSelected(const QString&)), this, SLOT(onSelectedFilepath(const QString&)));
fileDialog.exec();
}
void Import::onSelectedFilepath(const QString& filepath) {
this->ui.filepath->setText(filepath);
}
void Import::onFilepathChange() {
if (this->ui.filepath->text().length() > 0) {
this->ui.start->setEnabled(true);
} else {
this->ui.start->setEnabled(false);
}
}
void Import::onStart() {
this->ui.start->setEnabled(false);
// close the db to not corrupt it.
this->app->getDb()->close();
QString mehtadataPath = app->mehtadataPath();
if (mehtadataPath.length() == 0) {
QMessageBox::critical(NULL, "Can't find mehtadata", "The import can't be executed because the exe mehtadata is not found.");
return;
}
// start the import
importProcess.setProgram(mehtadataPath);
QStringList arguments;
arguments << "-db" << this->app->getDb()->filename << "-import-es";
QProcessEnvironment env;
env.insert("PLATFORM_ID", QString::number(this->platform));
env.insert("GAMELIST", this->ui.filepath->text()) ;
importProcess.setProcessEnvironment(env);
importProcess.setArguments(arguments);
importProcess.start();
qDebug() << "OK";
qDebug() << arguments;
}
void Import::onImportFinished() {
this->ui.start->setEnabled(true);
this->app->getDb()->open(this->app->getDb()->filename);
this->app->getSelectedPlatform().id = -1;
this->app->onPlatformSelected(this->app->getCurrentItem(), NULL);
this->hide();
}
| remeh/mehstation-config | src/import.cpp | C++ | mit | 2,334 |
import {Component} from '@angular/core';
@Component({
selector: "recomendaciones",
templateUrl: "app/components/htmls/recomendacionesysugerencias/recomendaciones.html",
styleUrls: ["app/components/htmls/htmlStyles.css"]
})
export class RecomendacionesComponent {};
| everitosan/CursoUnamDemencia | app/components/htmls/recomendacionesysugerencias/recomendaciones.component.ts | TypeScript | mit | 273 |
/**
* Copyright (c) André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.types.builtins;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.types.Constructor;
/**
* <h1>9 Ordinary and Exotic Objects Behaviours</h1>
* <ul>
* <li>9.3 Built-in Function Objects
* </ul>
*/
public abstract class BuiltinConstructor extends BuiltinFunction implements Constructor {
private MethodHandle constructMethod;
/**
* Constructs a new built-in constructor function.
*
* @param realm
* the realm object
* @param name
* the function name
* @param arity
* the function arity
*/
protected BuiltinConstructor(Realm realm, String name, int arity) {
super(realm, name, arity);
}
/**
* Returns `(? extends BuiltinConstructor, ExecutionContext, Constructor, Object[]) {@literal ->} ScriptObject`
* method-handle.
*
* @return the call method handle
*/
public MethodHandle getConstructMethod() {
if (constructMethod == null) {
try {
Method method = getClass().getDeclaredMethod("construct", ExecutionContext.class, Constructor.class,
Object[].class);
constructMethod = lookup().unreflect(method);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
return constructMethod;
}
}
| anba/es6draft | src/main/java/com/github/anba/es6draft/runtime/types/builtins/BuiltinConstructor.java | Java | mit | 1,758 |
<?php
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This class contains the configuration information for the bundle.
*
* This information is solely responsible for how the different configuration
* sections are normalized, and merged.
*
* @author Michael Williams <mtotheikle@gmail.com>
*/
class Configuration implements ConfigurationInterface
{
/**
* Generates the configuration tree.
*
* @return TreeBuilder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('sonata_admin', 'array');
$rootNode
->fixXmlConfig('option')
->fixXmlConfig('admin_service')
->fixXmlConfig('template')
->fixXmlConfig('extension')
->children()
->arrayNode('security')
->addDefaultsIfNotSet()
->fixXmlConfig('admin_permission')
->fixXmlConfig('object_permission')
->children()
->scalarNode('handler')->defaultValue('sonata.admin.security.handler.noop')->end()
->arrayNode('information')
->useAttributeAsKey('id')
->prototype('array')
->performNoDeepMerging()
->beforeNormalization()
->ifString()
->then(function ($v) {
return array($v);
})
->end()
->prototype('scalar')->end()
->end()
->end()
->arrayNode('admin_permissions')
->defaultValue(array('CREATE', 'LIST', 'DELETE', 'UNDELETE', 'EXPORT', 'OPERATOR', 'MASTER'))
->prototype('scalar')->end()
->end()
->arrayNode('object_permissions')
->defaultValue(array('VIEW', 'EDIT', 'DELETE', 'UNDELETE', 'OPERATOR', 'MASTER', 'OWNER'))
->prototype('scalar')->end()
->end()
->scalarNode('acl_user_manager')->defaultNull()->end()
->end()
->end()
->scalarNode('title')->defaultValue('Sonata Admin')->cannotBeEmpty()->end()
->scalarNode('title_logo')->defaultValue('bundles/sonataadmin/logo_title.png')->cannotBeEmpty()->end()
->arrayNode('breadcrumbs')
->addDefaultsIfNotSet()
->children()
->scalarNode('child_admin_route')
->defaultValue('edit')
->info('Change the default route used to generate the link to the parent object, when in a child admin')
->end()
->end()
->end()
->arrayNode('options')
->addDefaultsIfNotSet()
->children()
->booleanNode('html5_validate')->defaultTrue()->end()
->booleanNode('sort_admins')->defaultFalse()->info('Auto order groups and admins by label or id')->end()
->booleanNode('confirm_exit')->defaultTrue()->end()
->booleanNode('use_select2')->defaultTrue()->end()
->booleanNode('use_icheck')->defaultTrue()->end()
->booleanNode('use_bootlint')->defaultFalse()->end()
->booleanNode('use_stickyforms')->defaultTrue()->end()
->integerNode('pager_links')->defaultNull()->end()
->scalarNode('form_type')->defaultValue('standard')->end()
->integerNode('dropdown_number_groups_per_colums')->defaultValue(2)->end()
->enumNode('title_mode')
->values(array('single_text', 'single_image', 'both'))
->defaultValue('both')
->cannotBeEmpty()
->end()
->booleanNode('lock_protection')
->defaultFalse()
->info('Enable locking when editing an object, if the corresponding object manager supports it.')
->end()
->end()
->end()
->arrayNode('dashboard')
->addDefaultsIfNotSet()
->fixXmlConfig('group')
->fixXmlConfig('block')
->children()
->arrayNode('groups')
->useAttributeAsKey('id')
->prototype('array')
->beforeNormalization()
->ifArray()
->then(function ($items) {
if (isset($items['provider'])) {
$disallowedItems = array('items', 'label');
foreach ($disallowedItems as $item) {
if (isset($items[$item])) {
throw new \InvalidArgumentException(sprintf('The config value "%s" cannot be used alongside "provider" config value', $item));
}
}
}
return $items;
})
->end()
->fixXmlConfig('item')
->fixXmlConfig('item_add')
->children()
->scalarNode('label')->end()
->scalarNode('label_catalogue')->end()
->scalarNode('icon')->defaultValue('<i class="fa fa-folder"></i>')->end()
->scalarNode('on_top')->defaultFalse()->info('Show menu item in side dashboard menu without treeview')->end()
->scalarNode('provider')->end()
->arrayNode('items')
->beforeNormalization()
->ifArray()
->then(function ($items) {
foreach ($items as $key => $item) {
if (is_array($item)) {
if (!array_key_exists('label', $item) || !array_key_exists('route', $item)) {
throw new \InvalidArgumentException('Expected either parameters "route" and "label" for array items');
}
if (!array_key_exists('route_params', $item)) {
$items[$key]['route_params'] = array();
}
$items[$key]['admin'] = '';
} else {
$items[$key] = array(
'admin' => $item,
'label' => '',
'route' => '',
'route_params' => array(),
'route_absolute' => true,
);
}
}
return $items;
})
->end()
->prototype('array')
->children()
->scalarNode('admin')->end()
->scalarNode('label')->end()
->scalarNode('route')->end()
->arrayNode('route_params')
->prototype('scalar')->end()
->end()
->booleanNode('route_absolute')
->info('Whether the generated url should be absolute')
->defaultTrue()
->end()
->end()
->end()
->end()
->arrayNode('item_adds')
->prototype('scalar')->end()
->end()
->arrayNode('roles')
->prototype('scalar')->defaultValue(array())->end()
->end()
->end()
->end()
->end()
->arrayNode('blocks')
->defaultValue(array(array(
'position' => 'left',
'settings' => array(),
'type' => 'sonata.admin.block.admin_list',
'roles' => array(),
)))
->prototype('array')
->fixXmlConfig('setting')
->children()
->scalarNode('type')->cannotBeEmpty()->end()
->arrayNode('roles')
->defaultValue(array())
->prototype('scalar')->end()
->end()
->arrayNode('settings')
->useAttributeAsKey('id')
->prototype('variable')->defaultValue(array())->end()
->end()
->scalarNode('position')->defaultValue('right')->end()
->scalarNode('class')->defaultValue('col-md-4')->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('admin_services')
->prototype('array')
->children()
->scalarNode('model_manager')->defaultNull()->end()
->scalarNode('form_contractor')->defaultNull()->end()
->scalarNode('show_builder')->defaultNull()->end()
->scalarNode('list_builder')->defaultNull()->end()
->scalarNode('datagrid_builder')->defaultNull()->end()
->scalarNode('translator')->defaultNull()->end()
->scalarNode('configuration_pool')->defaultNull()->end()
->scalarNode('route_generator')->defaultNull()->end()
->scalarNode('validator')->defaultNull()->end()
->scalarNode('security_handler')->defaultNull()->end()
->scalarNode('label')->defaultNull()->end()
->scalarNode('menu_factory')->defaultNull()->end()
->scalarNode('route_builder')->defaultNull()->end()
->scalarNode('label_translator_strategy')->defaultNull()->end()
->scalarNode('pager_type')->defaultNull()->end()
->arrayNode('templates')
->addDefaultsIfNotSet()
->children()
->arrayNode('form')
->prototype('scalar')->end()
->end()
->arrayNode('filter')
->prototype('scalar')->end()
->end()
->arrayNode('view')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('templates')
->addDefaultsIfNotSet()
->children()
->scalarNode('user_block')->defaultValue('SonataAdminBundle:Core:user_block.html.twig')->cannotBeEmpty()->end()
->scalarNode('add_block')->defaultValue('SonataAdminBundle:Core:add_block.html.twig')->cannotBeEmpty()->end()
->scalarNode('layout')->defaultValue('SonataAdminBundle::standard_layout.html.twig')->cannotBeEmpty()->end()
->scalarNode('ajax')->defaultValue('SonataAdminBundle::ajax_layout.html.twig')->cannotBeEmpty()->end()
->scalarNode('dashboard')->defaultValue('SonataAdminBundle:Core:dashboard.html.twig')->cannotBeEmpty()->end()
->scalarNode('search')->defaultValue('SonataAdminBundle:Core:search.html.twig')->cannotBeEmpty()->end()
->scalarNode('list')->defaultValue('SonataAdminBundle:CRUD:list.html.twig')->cannotBeEmpty()->end()
->scalarNode('filter')->defaultValue('SonataAdminBundle:Form:filter_admin_fields.html.twig')->cannotBeEmpty()->end()
->scalarNode('show')->defaultValue('SonataAdminBundle:CRUD:show.html.twig')->cannotBeEmpty()->end()
->scalarNode('show_compare')->defaultValue('SonataAdminBundle:CRUD:show_compare.html.twig')->cannotBeEmpty()->end()
->scalarNode('edit')->defaultValue('SonataAdminBundle:CRUD:edit.html.twig')->cannotBeEmpty()->end()
->scalarNode('preview')->defaultValue('SonataAdminBundle:CRUD:preview.html.twig')->cannotBeEmpty()->end()
->scalarNode('history')->defaultValue('SonataAdminBundle:CRUD:history.html.twig')->cannotBeEmpty()->end()
->scalarNode('acl')->defaultValue('SonataAdminBundle:CRUD:acl.html.twig')->cannotBeEmpty()->end()
->scalarNode('history_revision_timestamp')->defaultValue('SonataAdminBundle:CRUD:history_revision_timestamp.html.twig')->cannotBeEmpty()->end()
->scalarNode('action')->defaultValue('SonataAdminBundle:CRUD:action.html.twig')->cannotBeEmpty()->end()
->scalarNode('select')->defaultValue('SonataAdminBundle:CRUD:list__select.html.twig')->cannotBeEmpty()->end()
->scalarNode('list_block')->defaultValue('SonataAdminBundle:Block:block_admin_list.html.twig')->cannotBeEmpty()->end()
->scalarNode('search_result_block')->defaultValue('SonataAdminBundle:Block:block_search_result.html.twig')->cannotBeEmpty()->end()
->scalarNode('short_object_description')->defaultValue('SonataAdminBundle:Helper:short-object-description.html.twig')->cannotBeEmpty()->end()
->scalarNode('delete')->defaultValue('SonataAdminBundle:CRUD:delete.html.twig')->cannotBeEmpty()->end()
->scalarNode('batch')->defaultValue('SonataAdminBundle:CRUD:list__batch.html.twig')->cannotBeEmpty()->end()
->scalarNode('batch_confirmation')->defaultValue('SonataAdminBundle:CRUD:batch_confirmation.html.twig')->cannotBeEmpty()->end()
->scalarNode('inner_list_row')->defaultValue('SonataAdminBundle:CRUD:list_inner_row.html.twig')->cannotBeEmpty()->end()
->scalarNode('outer_list_rows_mosaic')->defaultValue('SonataAdminBundle:CRUD:list_outer_rows_mosaic.html.twig')->cannotBeEmpty()->end()
->scalarNode('outer_list_rows_list')->defaultValue('SonataAdminBundle:CRUD:list_outer_rows_list.html.twig')->cannotBeEmpty()->end()
->scalarNode('outer_list_rows_tree')->defaultValue('SonataAdminBundle:CRUD:list_outer_rows_tree.html.twig')->cannotBeEmpty()->end()
->scalarNode('base_list_field')->defaultValue('SonataAdminBundle:CRUD:base_list_field.html.twig')->cannotBeEmpty()->end()
->scalarNode('pager_links')->defaultValue('SonataAdminBundle:Pager:links.html.twig')->cannotBeEmpty()->end()
->scalarNode('pager_results')->defaultValue('SonataAdminBundle:Pager:results.html.twig')->cannotBeEmpty()->end()
->scalarNode('tab_menu_template')->defaultValue('SonataAdminBundle:Core:tab_menu_template.html.twig')->cannotBeEmpty()->end()
->scalarNode('knp_menu_template')->defaultValue('SonataAdminBundle:Menu:sonata_menu.html.twig')->cannotBeEmpty()->end()
->scalarNode('action_create')->defaultValue('SonataAdminBundle:CRUD:dashboard__action_create.html.twig')->cannotBeEmpty()->end()
->scalarNode('button_acl')->defaultValue('SonataAdminBundle:Button:acl_button.html.twig')->cannotBeEmpty()->end()
->scalarNode('button_create')->defaultValue('SonataAdminBundle:Button:create_button.html.twig')->cannotBeEmpty()->end()
->scalarNode('button_edit')->defaultValue('SonataAdminBundle:Button:edit_button.html.twig')->cannotBeEmpty()->end()
->scalarNode('button_history')->defaultValue('SonataAdminBundle:Button:history_button.html.twig')->cannotBeEmpty()->end()
->scalarNode('button_list')->defaultValue('SonataAdminBundle:Button:list_button.html.twig')->cannotBeEmpty()->end()
->scalarNode('button_show')->defaultValue('SonataAdminBundle:Button:show_button.html.twig')->cannotBeEmpty()->end()
->end()
->end()
->arrayNode('assets')
->addDefaultsIfNotSet()
->children()
->arrayNode('stylesheets')
->defaultValue(array(
'bundles/sonatacore/vendor/bootstrap/dist/css/bootstrap.min.css',
'bundles/sonatacore/vendor/components-font-awesome/css/font-awesome.min.css',
'bundles/sonatacore/vendor/ionicons/css/ionicons.min.css',
'bundles/sonataadmin/vendor/admin-lte/dist/css/AdminLTE.min.css',
'bundles/sonataadmin/vendor/admin-lte/dist/css/skins/skin-black.min.css',
'bundles/sonataadmin/vendor/iCheck/skins/square/blue.css',
'bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css',
'bundles/sonataadmin/vendor/jqueryui/themes/base/jquery-ui.css',
'bundles/sonatacore/vendor/select2/select2.css',
'bundles/sonatacore/vendor/select2-bootstrap-css/select2-bootstrap.min.css',
'bundles/sonataadmin/vendor/x-editable/dist/bootstrap3-editable/css/bootstrap-editable.css',
'bundles/sonataadmin/css/styles.css',
'bundles/sonataadmin/css/layout.css',
'bundles/sonataadmin/css/tree.css',
))
->prototype('scalar')->end()
->end()
->arrayNode('javascripts')
->defaultValue(array(
'bundles/sonatacore/vendor/jquery/dist/jquery.min.js',
'bundles/sonataadmin/vendor/jquery.scrollTo/jquery.scrollTo.min.js',
'bundles/sonatacore/vendor/moment/min/moment.min.js',
'bundles/sonataadmin/vendor/jqueryui/ui/minified/jquery-ui.min.js',
'bundles/sonataadmin/vendor/jqueryui/ui/minified/i18n/jquery-ui-i18n.min.js',
'bundles/sonatacore/vendor/bootstrap/dist/js/bootstrap.min.js',
'bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js',
'bundles/sonataadmin/vendor/jquery-form/jquery.form.js',
'bundles/sonataadmin/jquery/jquery.confirmExit.js',
'bundles/sonataadmin/vendor/x-editable/dist/bootstrap3-editable/js/bootstrap-editable.min.js',
'bundles/sonatacore/vendor/select2/select2.min.js',
'bundles/sonataadmin/vendor/admin-lte/dist/js/app.min.js',
'bundles/sonataadmin/vendor/iCheck/icheck.min.js',
'bundles/sonataadmin/vendor/slimScroll/jquery.slimscroll.min.js',
'bundles/sonataadmin/vendor/waypoints/lib/jquery.waypoints.min.js',
'bundles/sonataadmin/vendor/waypoints/lib/shortcuts/sticky.min.js',
'bundles/sonataadmin/Admin.js',
'bundles/sonataadmin/treeview.js',
))
->prototype('scalar')->end()
->end()
->end()
->end()
->arrayNode('extensions')
->useAttributeAsKey('id')
->defaultValue(array('admins' => array(), 'excludes' => array(), 'implements' => array(), 'extends' => array(), 'instanceof' => array(), 'uses' => array()))
->prototype('array')
->fixXmlConfig('admin')
->fixXmlConfig('exclude')
->fixXmlConfig('implement')
->fixXmlConfig('extend')
->fixXmlConfig('use')
->children()
->arrayNode('admins')
->prototype('scalar')->end()
->end()
->arrayNode('excludes')
->prototype('scalar')->end()
->end()
->arrayNode('implements')
->prototype('scalar')->end()
->end()
->arrayNode('extends')
->prototype('scalar')->end()
->end()
->arrayNode('instanceof')
->prototype('scalar')->end()
->end()
->arrayNode('uses')
->prototype('scalar')->end()
->validate()
->ifTrue(function ($v) {
return !empty($v) && version_compare(PHP_VERSION, '5.4.0', '<');
})
->thenInvalid('PHP >= 5.4.0 is required to use traits.')
->end()
->end()
->end()
->end()
->end()
->scalarNode('persist_filters')->defaultFalse()->end()
->booleanNode('show_mosaic_button')
->defaultTrue()
->info('Show mosaic button on all admin screens')
->end()
->end()
->end();
return $treeBuilder;
}
}
| amirlionor/admin | vendor/sonata-project/admin-bundle/DependencyInjection/Configuration.php | PHP | mit | 25,648 |
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstring>
#include "../include/globals.hpp"
#include "../include/classes.hpp"
#include "../include/functions.hpp"
struct cell{
double xStart;
double yStart;
double zStart;
};
int main(int argc, char** argv)
{
int a;
int run=0;
gsl_rng_set(r,98);
gsl_histogram_set_ranges_uniform(gas_in,-1,5);
gsl_histogram_set_ranges_uniform(gas_out,-1,5);
gsl_histogram_set_ranges_uniform(gas_real_in,-1,5);
Particle *cube = new Particle[N];
std::list<Particle*> gas;
std::list<Particle*> gasHistory;
double* rCM = new double[3];
double* rCMtemp = new double[3];
double* vCM = new double[3];
double energy = 0;
InitPositions(cube);
calcCM(cube,rCMStart,vCM);
calcCM(cube,rCM,vCM);
InitVelocities(cube);
ComputeAccelerations(cube);
/*
*for(run=0;run<10000;run++)
*{
* if(run%500==0)
* printf("(INIT) Zeitschritt %d\n",run);
* VelocityVerlet(cube,0,NULL);
* if(run%100 == 0)
* rescaleVelocities(cube);
* if(run%100 == 0)
* GenerateOutput(cube,gas,run);
*}
*/
gsl_histogram *cells = gsl_histogram_alloc(100);
gsl_histogram_set_ranges_uniform(cells,0,50);
double lcx = floor(L/rCutOff);
double rcx = L/lcx;
double c = 0;
double ci[3] = {0,0,0};
for(int i=0;i<N;i++)
{
for(int k=0;k<3;k++)
ci[k] = floor(cube[i].r[k]/rcx);
c = ci[0]*lcx*lcx+ci[1]*lcx+ci[2];
std::cout << c << std::endl;
gsl_histogram_increment(cells,c);
}
FILE* celldata = fopen("cell_list_test.dat","w");
gsl_histogram_fprintf(celldata,cells,"%f","%f");
fclose(celldata);
return 0;
}
| homeslike/OpticalTweezer | test/cell_list.cpp | C++ | mit | 1,878 |
using System;
using System.Collections.Generic;
using System.Text;
using _03BarracksFactory.Contracts;
namespace P03_BarraksWars.Core.Commands
{
class RetireCommand : Command
{
public RetireCommand(string[] data, IRepository repository, IUnitFactory unitFactory)
: base(data, repository, unitFactory)
{
}
public override string Execute()
{
try
{
this.Repository.RemoveUnit(this.Data[1]);
return $"{this.Data[1]} retured!";
}
catch (InvalidOperationException ex)
{
return ex.Message;
}
}
}
}
| CvetelinLozanov/SoftUni-C- | C# OOP Advanced/Reflection_And_Attributes-Exercise/P03_BarraksWars/P03_BarraksWars/Core/Commands/RetireCommand.cs | C# | mit | 700 |
/*
* Globalize Culture id
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd.
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "id", "default", {
name: "id",
englishName: "Indonesian",
nativeName: "Bahasa Indonesia",
language: "id",
numberFormat: {
",": ".",
".": ",",
percent: {
",": ".",
".": ","
},
currency: {
decimals: 0,
",": ".",
".": ",",
symbol: "Rp"
}
},
calendars: {
standard: {
firstDay: 1,
days: {
names: ["Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu"],
namesAbbr: ["Minggu","Sen","Sel","Rabu","Kamis","Jumat","Sabtu"],
namesShort: ["M","S","S","R","K","J","S"]
},
months: {
names: ["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","Nopember","Desember",""],
namesAbbr: ["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agust","Sep","Okt","Nop","Des",""]
},
AM: null,
PM: null,
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM yyyy",
t: "H:mm",
T: "H:mm:ss",
f: "dd MMMM yyyy H:mm",
F: "dd MMMM yyyy H:mm:ss",
M: "dd MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
| bevacqua/jscharting | bundle/JSC/cultures/globalize.culture.id.js | JavaScript | mit | 1,780 |
package de.codecentric.awesome.recommendation.core;
import java.util.HashMap;
import java.util.Map;
/**
* Created by afitz on 15.03.16.
*/
public class RecommendationLookup {
private static RecommendationLookup ourInstance = new RecommendationLookup();
private String standardProductRecommendation = "P999";
// Map<User, Product>
private final Map<String, String> recommendationMap = new HashMap<String, String>();
public static RecommendationLookup getInstance() {
return ourInstance;
}
private RecommendationLookup() {
recommendationMap.put("P00T", "P001");
recommendationMap.put("P001", "P002");
recommendationMap.put("P002", "P003");
recommendationMap.put("P003", "P003");
}
public Product getRecommendation (Product product) {
return new Product((recommendationMap.containsKey(product.getId()) ? recommendationMap.get(product.getId()) : standardProductRecommendation));
}
}
| cc-afitz/awesome-services | recommendation/src/main/java/de/codecentric/awesome/recommendation/core/RecommendationLookup.java | Java | mit | 979 |
# coding: utf-8
""" General utilities. """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import collections
import sys
import logging
import multiprocessing
# Third-party
import numpy as np
__all__ = ['get_pool']
# Create logger
logger = logging.getLogger(__name__)
class SerialPool(object):
def close(self):
return
def map(self, *args, **kwargs):
return map(*args, **kwargs)
def get_pool(mpi=False, threads=None):
""" Get a pool object to pass to emcee for parallel processing.
If mpi is False and threads is None, pool is None.
Parameters
----------
mpi : bool
Use MPI or not. If specified, ignores the threads kwarg.
threads : int (optional)
If mpi is False and threads is specified, use a Python
multiprocessing pool with the specified number of threads.
"""
if mpi:
from emcee.utils import MPIPool
# Initialize the MPI pool
pool = MPIPool()
# Make sure the thread we're running on is the master
if not pool.is_master():
pool.wait()
sys.exit(0)
logger.debug("Running with MPI...")
elif threads > 1:
logger.debug("Running with multiprocessing on {} cores..."
.format(threads))
pool = multiprocessing.Pool(threads)
else:
logger.debug("Running serial...")
pool = SerialPool()
return pool
def gram_schmidt(y):
""" Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """
n = y.shape[0]
if y.shape[1] != n:
raise ValueError("Invalid shape: {}".format(y.shape))
mo = np.zeros(n)
# Main loop
for i in range(n):
# Remove component in direction i
for j in range(i):
esc = np.sum(y[j]*y[i])
y[i] -= y[j]*esc
# Normalization
mo[i] = np.linalg.norm(y[i])
y[i] /= mo[i]
return mo
class use_backend(object):
def __init__(self, backend):
import matplotlib.pyplot as plt
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.pylabtools import backend2gui
self.shell = InteractiveShell.instance()
self.old_backend = backend2gui[str(plt.get_backend())]
self.new_backend = backend
def __enter__(self):
gui, backend = self.shell.enable_matplotlib(self.new_backend)
def __exit__(self, type, value, tb):
gui, backend = self.shell.enable_matplotlib(self.old_backend)
def inherit_docs(cls):
for name, func in vars(cls).items():
if not func.__doc__:
for parent in cls.__bases__:
try:
parfunc = getattr(parent, name)
except AttributeError: # parent doesn't have function
break
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
return cls
class ImmutableDict(collections.Mapping):
def __init__(self, somedict):
self._dict = dict(somedict) # make a copy
self._hash = None
def __getitem__(self, key):
return self._dict[key]
def __len__(self):
return len(self._dict)
def __iter__(self):
return iter(self._dict)
def __hash__(self):
if self._hash is None:
self._hash = hash(frozenset(self._dict.items()))
return self._hash
def __eq__(self, other):
return self._dict == other._dict
| abonaca/gary | gary/util.py | Python | mit | 3,607 |
import EmberObject from '@ember/object';
import { htmlSafe } from '@ember/string';
import RSVP from 'rsvp';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import {
render,
settled,
find,
click
} from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
const { resolve } = RSVP;
module('Integration | Component | school session types list', function(hooks) {
setupRenderingTest(hooks);
test('it renders', async function(assert) {
assert.expect(19);
let assessmentOption = EmberObject.create({
id: 1,
name: 'formative'
});
let sessionType1 = EmberObject.create({
id: 1,
school: 1,
title: 'not needed anymore',
assessment: false,
assessmentOption: resolve(null),
safeCalendarColor: htmlSafe('#ffffff'),
sessionCount: 2,
active: false,
});
let sessionType2 = EmberObject.create({
id: 2,
school: 1,
title: 'second',
assessment: true,
assessmentOption: resolve(assessmentOption),
safeCalendarColor: htmlSafe('#123456'),
sessionCount: 0,
active: true,
});
let sessionType3 = EmberObject.create({
id: 2,
school: 1,
title: 'first',
assessment: false,
assessmentOption: resolve(null),
safeCalendarColor: htmlSafe('#cccccc'),
sessionCount: 2,
active: true,
});
this.set('sessionTypes', [sessionType1, sessionType2, sessionType3]);
this.set('nothing', parseInt);
await render(hbs`{{school-session-types-list
sessionTypes=sessionTypes
manageSessionType=(action nothing)
}}`);
const rows = 'table tbody tr';
const firstSessionType = `${rows}:nth-of-type(1)`;
const firstTitle = `${firstSessionType} td:nth-of-type(1)`;
const firstSessionCount = `${firstSessionType} td:nth-of-type(2)`;
const firstAssessment = `${firstSessionType} td:nth-of-type(3) svg`;
const firstAssessmentOption = `${firstSessionType} td:nth-of-type(4)`;
const firstColorBox = `${firstSessionType} td:nth-of-type(6) .box`;
const secondSessionType = `${rows}:nth-of-type(2)`;
const secondTitle = `${secondSessionType} td:nth-of-type(1)`;
const secondSessionCount = `${secondSessionType} td:nth-of-type(2)`;
const secondAssessment = `${secondSessionType} td:nth-of-type(3) svg`;
const secondAssessmentOption = `${secondSessionType} td:nth-of-type(4)`;
const secondColorBox = `${secondSessionType} td:nth-of-type(6) .box`;
const thirdSessionType = `${rows}:nth-of-type(3)`;
const thirdTitle = `${thirdSessionType} td:nth-of-type(1)`;
const thirdSessionCount = `${thirdSessionType} td:nth-of-type(2)`;
const thirdAssessment = `${thirdSessionType} td:nth-of-type(3) svg`;
const thirdAssessmentOption = `${thirdSessionType} td:nth-of-type(4)`;
const thirdColorBox = `${thirdSessionType} td:nth-of-type(6) .box`;
assert.dom(firstTitle).hasText('first');
assert.dom(firstSessionCount).hasText('2');
assert.dom(firstAssessment).hasClass('no');
assert.dom(firstAssessment).hasClass('fa-ban');
assert.dom(firstAssessmentOption).hasText('');
assert.equal(find(firstColorBox).style.getPropertyValue('background-color').trim(), ('rgb(204, 204, 204)'));
assert.dom(secondTitle).hasText('second');
assert.dom(secondSessionCount).hasText('0');
assert.dom(secondAssessment).hasClass('yes');
assert.dom(secondAssessment).hasClass('fa-check');
assert.dom(secondAssessmentOption).hasText('formative');
assert.equal(find(secondColorBox).style.getPropertyValue('background-color').trim(), ('rgb(18, 52, 86)'));
assert.ok(find(thirdTitle).textContent.trim().startsWith('not needed anymore'));
assert.ok(find(thirdTitle).textContent.trim().endsWith('(inactive)'));
assert.dom(thirdSessionCount).hasText('2');
assert.dom(thirdAssessment).hasClass('no');
assert.dom(thirdAssessment).hasClass('fa-ban');
assert.dom(thirdAssessmentOption).hasText('');
assert.equal(find(thirdColorBox).style.getPropertyValue('background-color').trim(), ('rgb(255, 255, 255)'));
});
test('clicking edit fires action', async function(assert) {
assert.expect(1);
let sessionType = EmberObject.create({
id: 1,
school: 1,
title: 'first',
assessment: false,
assessmentOption: resolve(null),
calendarColor: '#fff'
});
this.set('sessionTypes', [sessionType]);
this.set('manageSessionType', sessionTypeId => {
assert.equal(sessionTypeId, 1);
});
await render(hbs`{{school-session-types-list
sessionTypes=sessionTypes
manageSessionType=(action manageSessionType)
}}`);
await settled();
const rows = 'table tbody tr';
const edit = `${rows}:nth-of-type(1) td:nth-of-type(7) .fa-edit`;
await click(edit);
});
test('clicking title fires action', async function(assert) {
assert.expect(1);
let sessionType = EmberObject.create({
id: 1,
school: 1,
title: 'first',
assessment: false,
assessmentOption: resolve(null),
calendarColor: '#fff'
});
this.set('sessionTypes', [sessionType]);
this.set('manageSessionType', sessionTypeId => {
assert.equal(sessionTypeId, 1);
});
await render(hbs`{{school-session-types-list
sessionTypes=sessionTypes
manageSessionType=(action manageSessionType)
}}`);
await settled();
const rows = 'table tbody tr';
const title = `${rows}:nth-of-type(1) td:nth-of-type(1) a`;
await click(title);
});
test('session types without sessions can be deleted', async function(assert) {
assert.expect(4);
let unlinkedSessionType = EmberObject.create({
id: 1,
school: 1,
title: 'unlinked',
active: true,
assessment: false,
assessmentOption: resolve(null),
calendarColor: '#fff',
sessionCount: 0,
deleteRecord(){
assert.ok(true, 'was deleted');
return resolve();
}
});
let linkedSessionType = EmberObject.create({
id: 1,
school: 1,
title: 'linked',
active: true,
assessment: false,
assessmentOption: resolve(null),
calendarColor: '#fff',
sessionCount: 5,
deleteRecord(){
assert.ok(true, 'was deleted');
return resolve();
}
});
this.set('sessionTypes', [linkedSessionType, unlinkedSessionType]);
this.set('nothing', parseInt);
await render(hbs`{{school-session-types-list
sessionTypes=sessionTypes
manageSessionType=(action nothing)
canDelete=true
}}`);
await settled();
const rows = 'table tbody tr';
const linkedTitle = `${rows}:nth-of-type(1) td:nth-of-type(1)`;
const unlinkedTitle = `${rows}:nth-of-type(2) td:nth-of-type(1)`;
const linkedTrash = `${rows}:nth-of-type(1) td:nth-of-type(7) .fa-trash.disabled`;
const unlinkedTrash = `${rows}:nth-of-type(2) td:nth-of-type(7) .fa-trash.enabled`;
assert.dom(linkedTitle).hasText('linked', 'linked is first');
assert.dom(unlinkedTitle).hasText('unlinked', 'unlinked is second');
assert.dom(linkedTrash).exists({ count: 1 }, 'linked has a disabled trash can');
assert.dom(unlinkedTrash).exists({ count: 1 }, 'unlinked has an enabled trash can');
});
test('clicking delete deletes the record', async function(assert) {
assert.expect(2);
let sessionType = EmberObject.create({
id: 1,
school: 1,
title: 'first',
assessment: false,
assessmentOption: resolve(null),
calendarColor: '#fff',
sessionCount: 0,
deleteRecord(){
assert.ok(true, 'was deleted');
},
save(){
assert.ok(true, 'was deleted');
return resolve();
},
});
this.set('sessionTypes', [sessionType]);
this.set('nothing', parseInt);
await render(hbs`{{school-session-types-list
sessionTypes=sessionTypes
manageSessionType=(action nothing)
canDelete=true
}}`);
await settled();
const rows = 'table tbody tr';
const trash = `${rows}:nth-of-type(1) td:nth-of-type(7) .fa-trash`;
await click(trash);
await settled();
});
});
| djvoa12/frontend | tests/integration/components/school-session-types-list-test.js | JavaScript | mit | 8,230 |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Dependinator.Common.ModelMetadataFolders;
using Dependinator.Common.ModelMetadataFolders.Private;
using Dependinator.Common.SettingsHandling;
using Dependinator.Utils;
using Dependinator.Utils.Dependencies;
using Dependinator.Utils.ErrorHandling;
using Dependinator.Utils.Net;
using Dependinator.Utils.OsSystem;
using Dependinator.Utils.Serialization;
using Dependinator.Utils.Threading;
using Microsoft.Win32;
namespace Dependinator.Common.Installation.Private
{
[SingleInstance]
internal class LatestVersionService : ILatestVersionService
{
private static readonly TimeSpan IdleTimerInterval = TimeSpan.FromMinutes(1);
private static readonly TimeSpan IdleTimeBeforeRestarting = TimeSpan.FromMinutes(10);
private static readonly string latestUri =
"https://api.github.com/repos/michael-reichenauer/Dependinator/releases/latest";
private static readonly string UserAgent = "Dependinator";
private readonly ModelMetadata modelMetadata;
private readonly ISettingsService settingsService;
private readonly IStartInstanceService startInstanceService;
private DispatcherTimer idleTimer;
private DateTime lastIdleCheck = DateTime.MaxValue;
public LatestVersionService(
IStartInstanceService startInstanceService,
ISettingsService settingsService,
ModelMetadata modelMetadata)
{
this.startInstanceService = startInstanceService;
this.settingsService = settingsService;
this.modelMetadata = modelMetadata;
}
public event EventHandler OnNewVersionAvailable;
public void StartCheckForLatestVersion()
{
idleTimer = new DispatcherTimer();
idleTimer.Tick += CheckIdleBeforeRestart;
idleTimer.Interval = IdleTimerInterval;
idleTimer.Start();
SystemEvents.PowerModeChanged += OnPowerModeChange;
}
public async Task CheckLatestVersionAsync()
{
if (settingsService.Get<Options>().DisableAutoUpdate)
{
return;
}
if (await IsNewRemoteVersionAvailableAsync())
{
await DownloadLatestVersionAsync();
await IsNewRemoteVersionAvailableAsync();
}
}
private async Task<bool> IsNewRemoteVersionAvailableAsync()
{
Version remoteVersion = await GetLatestRemoteVersionAsync();
Version currentVersion = Version.Parse(ProgramInfo.Version);
Version installedVersion = ProgramInfo.GetInstalledVersion();
Version setupVersion = ProgramInfo.GetSetupVersion();
LogVersion(currentVersion, installedVersion, remoteVersion, setupVersion);
return installedVersion < remoteVersion && setupVersion < remoteVersion;
}
private async Task<bool> DownloadLatestVersionAsync()
{
try
{
Log.Info($"Downloading remote setup {latestUri} ...");
LatestInfo latestInfo = GetCachedLatestVersionInfo();
if (latestInfo == null)
{
// No installed version.
return false;
}
using (HttpClientDownloadWithProgress httpClient = GetDownloadHttpClient())
{
await DownloadSetupAsync(httpClient, latestInfo);
return true;
}
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Error($"Failed to install new version {e}");
}
return false;
}
private static async Task<string> DownloadSetupAsync(
HttpClientDownloadWithProgress httpClient, LatestInfo latestInfo)
{
Asset setupFileInfo = latestInfo.assets.First(a => a.name == $"{ProgramInfo.Name}Setup.exe");
string downloadUrl = setupFileInfo.browser_download_url;
Log.Info($"Downloading {latestInfo.tag_name} from {downloadUrl} ...");
Timing t = Timing.Start();
httpClient.ProgressChanged += (totalFileSize, totalBytesDownloaded, progressPercentage) =>
{
Log.Info($"Downloading {latestInfo.tag_name} {progressPercentage}% (time: {t.Elapsed}) ...");
};
string setupPath = ProgramInfo.GetSetupFilePath();
if (File.Exists(setupPath))
{
File.Delete(setupPath);
}
await httpClient.StartDownloadAsync(downloadUrl, setupPath);
Log.Info($"Downloaded {latestInfo.tag_name} to {setupPath}");
return setupPath;
}
private async Task<Version> GetLatestRemoteVersionAsync()
{
try
{
M<LatestInfo> latestInfo = await GetLatestInfoAsync();
if (latestInfo.IsOk && latestInfo.Value.tag_name != null)
{
Version version = Version.Parse(latestInfo.Value.tag_name.Substring(1));
return version;
}
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Warn($"Failed to get latest version {e}");
}
return new Version(0, 0, 0, 0);
}
private async Task<M<LatestInfo>> GetLatestInfoAsync()
{
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("user-agent", UserAgent);
// Try get cached information about latest remote version
string eTag = GetCachedLatestVersionInfoEtag();
if (!string.IsNullOrEmpty(eTag))
{
// There is cached information, lets use the ETag when checking to follow
// GitHub Rate Limiting method.
httpClient.DefaultRequestHeaders.IfNoneMatch.Clear();
httpClient.DefaultRequestHeaders.IfNoneMatch.Add(new EntityTagHeaderValue(eTag));
}
HttpResponseMessage response = await httpClient.GetAsync(latestUri);
if (response.StatusCode == HttpStatusCode.NotModified || response.Content == null)
{
return GetCachedLatestVersionInfo();
}
string latestInfoText = await response.Content.ReadAsStringAsync();
Log.Debug("New version info");
if (response.Headers.ETag != null)
{
eTag = response.Headers.ETag.Tag;
CacheLatestVersionInfo(eTag, latestInfoText);
}
return Json.As<LatestInfo>(latestInfoText);
}
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Exception(e, "Failed to download latest setup");
return Error.From(e);
}
}
private LatestInfo GetCachedLatestVersionInfo()
{
ProgramSettings programSettings = settingsService.Get<ProgramSettings>();
return Json.As<LatestInfo>(programSettings.LatestVersionInfo);
}
private string GetCachedLatestVersionInfoEtag()
{
ProgramSettings programSettings = settingsService.Get<ProgramSettings>();
return programSettings.LatestVersionInfoETag;
}
private void CacheLatestVersionInfo(string eTag, string latestInfoText)
{
if (string.IsNullOrEmpty(eTag)) return;
// Cache the latest version info
settingsService.Edit<ProgramSettings>(s =>
{
s.LatestVersionInfoETag = eTag;
s.LatestVersionInfo = latestInfoText;
});
}
private static void LogVersion(Version current, Version installed, Version remote, Version setup)
{
Log.Usage(
$"Version current: {current}, installed: {installed}, remote: {remote}, setup {setup}");
}
private void NotifyIfNewVersionIsAvailable()
{
if (IsNewVersionInstalled())
{
OnNewVersionAvailable?.Invoke(this, EventArgs.Empty);
}
}
private void OnPowerModeChange(object sender, PowerModeChangedEventArgs e)
{
Log.Info($"Power mode {e.Mode}");
if (e.Mode == PowerModes.Resume)
{
if (IsNewVersionInstalled())
{
Log.Info("Newer version is installed, restart ...");
if (startInstanceService.StartInstance(modelMetadata.ModelFilePath))
{
// Newer version is started, close this instance
Application.Current.Shutdown(0);
}
}
}
}
private void CheckIdleBeforeRestart(object sender, EventArgs e)
{
TimeSpan timeSinceCheck = DateTime.UtcNow - lastIdleCheck;
bool wasSleeping = false;
if (timeSinceCheck > IdleTimerInterval + TimeSpan.FromMinutes(1))
{
// The timer did not tick within the expected timeout, thus computer was probably sleeping.
Log.Info($"Idle timer timeout, was: {timeSinceCheck}");
wasSleeping = true;
}
lastIdleCheck = DateTime.UtcNow;
TimeSpan idleTime = SystemIdle.GetLastInputIdleTimeSpan();
if (wasSleeping || idleTime > IdleTimeBeforeRestarting)
{
if (IsNewVersionInstalled())
{
if (startInstanceService.StartInstance(modelMetadata.ModelFilePath))
{
// Newer version is started, close this instance
Application.Current.Shutdown(0);
}
}
}
}
private static bool IsNewVersionInstalled()
{
Version currentVersion = Version.Parse(ProgramInfo.Version);
Version installedVersion = ProgramInfo.GetInstalledVersion();
Log.Debug($"Current version: {currentVersion} installed version: {installedVersion}");
return currentVersion < installedVersion;
}
private static HttpClientDownloadWithProgress GetDownloadHttpClient()
{
HttpClientDownloadWithProgress client = new HttpClientDownloadWithProgress();
client.NetworkActivityTimeout = TimeSpan.FromSeconds(30);
client.HttpClient.Timeout = TimeSpan.FromSeconds(60 * 5);
client.HttpClient.DefaultRequestHeaders.Add("user-agent", UserAgent);
return client;
}
// Type used when parsing latest version information json
public class LatestInfo
{
public Asset[] assets;
public string tag_name;
}
// Type used when parsing latest version information json
internal class Asset
{
public string browser_download_url;
public int download_count;
public string name;
}
}
}
| michael-reichenauer/Dependinator | Dependinator/Common/Installation/Private/LatestVersionService.cs | C# | mit | 11,771 |
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var authUserSchema = mongoose.Schema({
unique_ID : String,
username : String,
password : String,
role : String,
first_name : String,
last_name : String
});
// methods ======================
// generating a hash
authUserSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
authUserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('authUser', authUserSchema);
| ishwant/Auth-Server | app/models/authUser.js | JavaScript | mit | 791 |
<?php
namespace fm\KitBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class KitBundle extends Bundle
{
}
| davidpestana/erp.fm | src/fm/KitBundle/KitBundle.php | PHP | mit | 116 |
from notifications_utils.clients.antivirus.antivirus_client import (
AntivirusClient,
)
from notifications_utils.clients.redis.redis_client import RedisClient
from notifications_utils.clients.zendesk.zendesk_client import ZendeskClient
antivirus_client = AntivirusClient()
zendesk_client = ZendeskClient()
redis_client = RedisClient()
| alphagov/notifications-admin | app/extensions.py | Python | mit | 340 |
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Lib = require('../../lib');
// The contour extraction is great, except it totally fails for constraints because we
// need weird range loops and flipped contours instead of the usual format. This function
// does some weird manipulation of the extracted pathinfo data such that it magically
// draws contours correctly *as* constraints.
module.exports = function(pathinfo, operation) {
var i, pi0, pi1;
var op0 = function(arr) { return arr.reverse(); };
var op1 = function(arr) { return arr; };
switch(operation) {
case '][':
case ')[':
case '](':
case ')(':
var tmp = op0;
op0 = op1;
op1 = tmp;
// It's a nice rule, except this definitely *is* what's intended here.
/* eslint-disable: no-fallthrough */
case '[]':
case '[)':
case '(]':
case '()':
/* eslint-enable: no-fallthrough */
if(pathinfo.length !== 2) {
Lib.warn('Contour data invalid for the specified inequality range operation.');
return;
}
// In this case there should be exactly two contour levels in pathinfo. We
// simply concatenate the info into one pathinfo and flip all of the data
// in one. This will draw the contour as closed.
pi0 = pathinfo[0];
pi1 = pathinfo[1];
for(i = 0; i < pi0.edgepaths.length; i++) {
pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
}
for(i = 0; i < pi0.paths.length; i++) {
pi0.paths[i] = op0(pi0.paths[i]);
}
while(pi1.edgepaths.length) {
pi0.edgepaths.push(op1(pi1.edgepaths.shift()));
}
while(pi1.paths.length) {
pi0.paths.push(op1(pi1.paths.shift()));
}
pathinfo.pop();
break;
case '>=':
case '>':
if(pathinfo.length !== 1) {
Lib.warn('Contour data invalid for the specified inequality operation.');
return;
}
// In this case there should be exactly two contour levels in pathinfo. We
// simply concatenate the info into one pathinfo and flip all of the data
// in one. This will draw the contour as closed.
pi0 = pathinfo[0];
for(i = 0; i < pi0.edgepaths.length; i++) {
pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
}
for(i = 0; i < pi0.paths.length; i++) {
pi0.paths[i] = op0(pi0.paths[i]);
}
break;
}
};
| iongroup/plotly.js | src/traces/contourcarpet/convert_to_constraints.js | JavaScript | mit | 2,890 |
module.exports = {
defersToPromises : function(defers) {
if(Array.isArray(defers)) {
return defers.map(function(defer) {
return defer && defer.promise ?
defer.promise :
defer;
});
}
var res = {};
Object.keys(defers).forEach(function(key) {
res[key] = defers[key] && defers[key].promise ?
defers[key].promise :
defer;
});
return res;
}
}; | stenin-nikita/module-promise | test/utils/helpers.js | JavaScript | mit | 518 |
export default (sequelize, DataTypes) => {
const Product = sequelize.define('Product', {
name: DataTypes.STRING,
description: DataTypes.TEXT,
price: DataTypes.FLOAT,
releasedate: DataTypes.DATE
}, {
classMethods: {
associate: models => {
Product.belongsToMany(models.Cart, {through: 'ProductCart'});
Product.belongsToMany(models.Platform, {through: 'ProductPlatform'});
Product.belongsTo(models.SpecialEdition);
}
}
});
return Product;
};
| Kennyomg/gamersonline-uni | api/models/product.js | JavaScript | mit | 508 |
<?php
namespace Glucose\Exceptions\User;
class PrimaryKeyCollisionException extends \Glucose\Exceptions\Entity\DuplicateEntityException {
} | andsens/Glucose | Glucose/Exceptions/User/PrimaryKeyCollisionException.class.php | PHP | mit | 141 |
require "tenant/engine"
module Tenant
end
| cshirley/tenant_engine | lib/tenant.rb | Ruby | mit | 43 |
import { SET_SORT_ORDER } from '../constants/actions';
export default function (state = 'ASCENDING', action) {
switch (action.type) {
case SET_SORT_ORDER:
return action.order;
default:
return state;
}
}
| ColdForge/icebox | src/reducers/sortOrderReducer.js | JavaScript | mit | 212 |
import mongoose from 'mongoose';
const ModelPortfolioSchema = new mongoose.Schema({
id: String,
name: String,
displayName: String,
email: String,
securities: [{
symbol: String,
allocation: {type: Number, min: 0, max: 100},
}]
});
ModelPortfolioSchema.add({
subGroups: [ModelPortfolioSchema],
modelPortfolios: [ModelPortfolioSchema],
});
export default mongoose.model('ModelPortfolio', ModelPortfolioSchema);
| AlexisDeschamps/portfolio-rebalancer | server/db/mongo/models/modelPortfolio.js | JavaScript | mit | 430 |
<h2>Sprzątanie pobojowisk</h2>
<?php
f('jednostki_miasto');
$jednostki = jednostki_miasto($gracz);
if(!empty($_POST['cel']) && !empty($_POST['u'])){
f('sprzatanie_wyslij');
echo sprzatanie_wyslij($jednostki,$_POST['cel'],$_POST['u'],$gracz);
$gracz = gracz($gracz['gracz']);
f('jednostki_miasto');
$jednostki = jednostki_miasto($gracz);
} elseif(!empty($_GET['przerwij'])){
f('sprzatanie_przerwij');
echo sprzatanie_przerwij($gracz,$_GET['przerwij']);
$gracz = gracz($gracz['gracz']);
}
if(!empty($jednostki)){
$razem = 0;
$echo ="
<p>
<br style='clear:both'/>
<form action ='?a=sprzatanie' method='post'>
<table>
<tr>
<td>cel </td>
<td><input type='text' name='cel' class='input2' value ='".$_GET['cel']."'></td>
</tr>
";
foreach($jednostki as $oddzial){
if($oddzial['ilosc'] > 0){
$razem = 1;
$echo .="
<tr>
<td>".$oddzial['nazwa']." ( ".$oddzial['ilosc']." ) <span style='float:right'> udźwig: ".$oddzial['udzwig']."</span></td>
<td> <input type='text' class='input2' name='u[".$oddzial['id']."]' ></td>
</tr>
";
}
}
$echo .="
<tr>
<th colspan='2'><input type='submit' class='submit' value='wyślij'></th>
</tr>
</table>
</form>
</p>";
if($razem == 0){
echo "<p class='error'>Nie posiadasz jednostek</p>";
} else {
echo $echo;
}
} else echo "<p class='error'>Brak jednostek w grze</p>";
$wyslane = mysql_query("select * from osadnicy_sprzatanie inner join osadnicy_miasta on do_miasto = miasto where z_miasto = ".$gracz['aktywne_miasto']." order by koniec asc");
if(mysql_num_rows($wyslane) > 0){
echo "<hr/>Akcje<br/>
<table>
<tr>
<th>cel</th>
<th></th>
</tr>
";
$czas = time();
while($akcja = mysql_fetch_array($wyslane)){
$pozostalo = $akcja['koniec'] - $czas;
if($akcja['status'] == 0){
$tekst = "wyprawa kieruje się do miasta <i><b>".$akcja['nazwa']."</b></i>";
$opcja = " <a href='?a=sprzatanie&przerwij=".$akcja['id']."'>X</a>";
} else {
$tekst = "wyprawa powraca z miasta <i><b>".$akcja['nazwa']."</b></i>";
$opcja = "";
}
echo "
<tr align='center'>
<td>".$tekst."</td>
<td>
<span id='sp".$akcja['id']."'></span>
<script type='text/javascript'>liczCzas('sp".$akcja['id']."',".$pozostalo.");</script>
".$opcja."
</td>
</tr>";
}
echo "</table>";
}
?>
| WlasnaGra/Osadnicy | strony/gracz/sprzatanie.php | PHP | mit | 2,375 |
package net.tmachq.Ported_Blocks.tileentities.renderers;
import java.io.DataInputStream;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import org.lwjgl.opengl.GL11;
import net.tmachq.Ported_Blocks.models.SailModel;
public class TileEntitySailRenderer extends TileEntitySpecialRenderer {
private final SailModel model;
public TileEntitySailRenderer() {
this.model = new SailModel();
}
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float scale) {
int rotation = 180;
switch (te.getBlockMetadata() % 4) {
case 0:
rotation = 0;
break;
case 3:
rotation = 90;
break;
case 2:
rotation = 180;
break;
case 1:
rotation = 270;
break;
}
GL11.glPushMatrix();
int i = te.getBlockMetadata();
GL11.glTranslatef((float) x + 0.5F, (float) y + 1.5F, (float) z + 0.5F);
GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F);
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation("Ported_Blocks:textures/texturemaps/Sail_HD.png"));
GL11.glScalef(1.0F, -1F, -1F);
model.render((Entity)null, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F);
GL11.glPopMatrix();
}
private void adjustLightFixture(World world, int i, int j, int k, Block block) {
Tessellator tess = Tessellator.instance;
float brightness = block.getBlockBrightness(world, i, j, k);
int skyLight = world.getLightBrightnessForSkyBlocks(i, j, k, 0);
int modulousModifier = skyLight % 65536;
int divModifier = skyLight / 65536;
tess.setColorOpaque_F(brightness, brightness, brightness);
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) modulousModifier, divModifier);
}
} | TMAC-Coding/Ported-Blocks | src/net/tmachq/Ported_Blocks/tileentities/renderers/TileEntitySailRenderer.java | Java | mit | 2,561 |
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
enum MENUPARTS
{
MENUPartFiller0 = 0x0,
MP_MENUITEM = 0x1,
MP_MENUDROPDOWN = 0x2,
MP_MENUBARITEM = 0x3,
MP_MENUBARDROPDOWN = 0x4,
MP_CHEVRON = 0x5,
MP_SEPARATOR = 0x6,
};
END_ATF_NAMESPACE
| goodwinxp/Yorozuya | library/ATF/MENUPARTS.hpp | C++ | mit | 415 |
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-05-11 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
| jjp12383/Portfolio | test/karma.conf.js | JavaScript | mit | 1,620 |
var indexSectionsWithContent =
{
0: "dfrsw~",
1: "drs",
2: "dfrs~",
3: "rs",
4: "w"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "functions",
3: "variables",
4: "pages"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Functions",
3: "Variables",
4: "Pages"
};
| sabertazimi/hust-lab | network/webserver/docs/search/searchdata.js | JavaScript | mit | 313 |
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
## Database authenticatable
t.boolean :admin
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
| njazari/sef-founderwall | db/migrate/20161030044448_devise_create_users.rb | Ruby | mit | 1,378 |
class RoomSerializer < ActiveModel::Serializer
attribute :id
attribute :name, key: :title
end
| guidance-guarantee-programme/tesco_planner | app/serializers/room_serializer.rb | Ruby | mit | 98 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Authentication extends CI_Controller {
function index(){
$value = $this->input->cookie('remember_me');
if ($value == 'true') {
$arr = array(
'user' => $this->input->cookie('user'),
'real_name' => $this->input->cookie('real_name'),
'user_id' => $this->input->cookie('user_id'),
);
$this->session->set_userdata($arr);
}
$this->load->view('login_view');
}
function create_user(){
$this->load->library('myencryption');
$arr = array('username'=>$this->myencryption->encode('admin'),
'password'=>$this->myencryption->encode('123'));
$this->db->insert('user',$arr);
}
function resetPassword(){
$this->load->library('myencryption');
$this->load->library('form_validation');
$this->form_validation->set_rules('resetmail','Reset email','valid_email');
$this->form_validation->set_error_delimiters('<div class="alert alert-warning">','</div>');
if ($this->form_validation->run() == false) {
$this->load->view('login_view');
}else{
$mail = $this->input->post('resetmail');
$this->db->where('email_address',trim(strtolower($mail)));
$result = $this->db->get('user');
if ($result->num_rows() == 1 ){
function get_random_password($chars_min=8, $chars_max=10, $use_upper_case=true, $include_numbers=true, $include_special_chars=false){
$length = rand($chars_min, $chars_max);
$selection = 'aeuoyibcdfghjklmnpqrstvwxz';
if($include_numbers) {
$selection .= "1234567890";
}
if($include_special_chars) {
$selection .= "!@\"#$%&[]{}?|";
}
$password = "";
for($i=0; $i<$length; $i++) {
$current_letter = $use_upper_case ? (rand(0,1) ? strtoupper($selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))];
$password .= $current_letter;
}
return $password;
}
$newpass = get_random_password();
$this->db->where('email_address',trim(strtolower($mail)));
$newpass1 = $this->myencryption->encode($newpass);
$this->db->update('user',array('password'=>$newpass1));
if ($this->db->affected_rows() == 1){
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'thythona168@gmail.com',
'smtp_pass' => 'Broskomsot123',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email',$config);
$this->email->set_newline("\r\n");
// Set to, from, message, etc.
$this->email->from('thythona168@gmail.com', 'Rest password MSC');
$this->email->to($mail);
$this->email->subject('New Password');
$this->email->message('Your New Password is : '.$newpass);
if (! $this->email->send()) {
$arr['message'] = '<div class="alert alert-warning" style="text-align:left">Reset password failed. please try again later.</div>';
$this->load->view('login_view',$arr);
}else{
$arr['message'] = '<div class="alert alert-success" style="text-align:left">Reset password successful. Please check your email for the new password</div>';
$this->load->view('login_view',$arr);
}
}
}else{
$arr['message'] = '<div class="alert alert-warning">Given reset email dose not exist!</div>';
$this->load->view('login_view',$arr);
}
}
}
function validation(){
$this->load->library('myencryption');
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
$this->form_validation->set_error_delimiters('<div class="alert alert-warning">','</div>');
if ($this->form_validation->run() == false ) {
$this->load->view('login_view');
}else{
$username = $this->input->post('username');
$password = $this->input->post('password');
$rememberme = $this->input->post('rememberme');
$this->db->where('username',$this->myencryption->encode($username));
$this->db->where('password',$this->myencryption->encode($password));
$result = $this->db->get('user');
if ($result->num_rows()==1) {
$value = $result->row();
if ($rememberme == 'on'){
$arr = array('user'=>TRUE,'real_name'=>$value->real_name,'user_id'=>$value->id);
$this->session->set_userdata($arr);
$cookie = array(
'name' => 'remember_me',
'value' => 'true',
'expire' => '15000000',
'prefix' => ''
);
$this->input->set_cookie($cookie);
$cookie = array(
'name' => 'user',
'value' => TRUE,
'expire' => '15000000',
'prefix' => ''
);
$this->input->set_cookie($cookie);
$cookie = array(
'name' => 'real_name',
'value' => $value->real_name,
'expire' => '15000000',
'prefix' => ''
);
$this->input->set_cookie($cookie);
$cookie = array(
'name' => 'user_id',
'value' => $value->id,
'expire' => '15000000',
'prefix' => ''
);
$this->input->set_cookie($cookie);
}else{
$arr = array('user'=>TRUE,'real_name'=>$value->real_name,'user_id'=>$value->id);
$this->session->set_userdata($arr);
$cookie = array(
'name' => 'remember_me',
'value' => 'false',
'expire' => '15000000',
'prefix' => ''
);
$this->input->set_cookie($cookie);
}
redirect('home');
}else{
$arr['message'] = '<div class="alert alert-danger" style="text-align:left">Incorrect username or password !!! </div>';
$this->load->view('login_view',$arr);
}
}
}
} | tavhu/msc | application/controllers/Authentication.php | PHP | mit | 6,198 |
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Web Client
* Copyright (C) 2006, 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.webClient.build;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.types.*;
public class PackageJammerTask
extends Task {
//
// Constants
//
private static final Pattern RE_DEFINE = Pattern.compile("^AjxPackage\\.define\\(['\"]([^'\"]+)['\"]\\);?");
private static final Pattern RE_UNDEFINE = Pattern.compile("^AjxPackage\\.undefine\\(['\"]([^'\"]+)['\"]\\);?");
private static final Pattern RE_REQUIRE = Pattern.compile("^AjxPackage\\.require\\(['\"]([^'\"]+)['\"](.*?)\\);?");
private static final Pattern RE_REQUIRE_OBJ = Pattern.compile("^AjxPackage\\.require\\((\\s*\\{\\s*name\\s*:\")?([^'\"]+)['\"](.*?)\\);?");
private static final String OUTPUT_JS = "js";
private static final String OUTPUT_HTML = "html";
private static final String OUTPUT_ALL = "all";
//
// Data
//
// attributes
private File destFile;
private File jsFile;
private File htmlFile;
private List<Source> sources = new LinkedList<Source>();
private File dependsFile;
private String output = OUTPUT_JS;
private String basepath = "";
private String extension = ".js";
private boolean verbose = false;
// children
private Text prefix;
private Text suffix;
private List<JammerFiles> files = new LinkedList<JammerFiles>();
// internal state
private String depth;
private Map<String,Boolean> defines;
private boolean isJs = true;
private boolean isHtml = false;
private boolean isAll = false;
//
// Public methods
//
// attributes
public void setDestFile(File file) {
this.destFile = file;
}
public void setJsDestFile(File file) {
this.jsFile = file;
}
public void setHtmlDestFile(File file) {
this.htmlFile = file;
}
public void setJsDir(File dir) {
Source source = new Source();
source.setDir(dir);
this.sources.clear();
this.sources.add(source);
}
public void setDependsFile(File file) {
this.dependsFile = file;
}
public void setOutput(String output) {
this.output = output;
this.isAll = OUTPUT_ALL.equals(output);
this.isHtml = this.isAll || OUTPUT_HTML.equals(output);
this.isJs = this.isAll || OUTPUT_JS.equals(output) || !this.isHtml;
}
public void setBasePath(String basepath) {
this.basepath = basepath;
}
public void setExtension(String extension) {
this.extension = extension;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
// children
public Text createPrefix() {
return this.prefix = new Text();
}
public Text createSuffix() {
return this.suffix = new Text();
}
public FileList createFileList() {
JammerFileList fileList = new JammerFileList();
this.files.add(fileList);
return fileList;
}
public FileSet createFileSet() {
JammerFileSet fileSet = new JammerFileSet();
this.files.add(fileSet);
return fileSet;
}
public Source createSrc() {
Source source = new Source();
this.sources.add(source);
return source;
}
//
// Task methods
//
public void execute() throws BuildException {
this.depth = "";
this.defines = new HashMap<String,Boolean>();
PrintWriter jsOut = null;
PrintWriter htmlOut = null;
PrintWriter dependsOut = null;
try {
if (this.isJs) {
File file = this.jsFile != null ? this.jsFile : this.destFile;
log("Jamming to ",file.toString());
jsOut = new PrintWriter(new FileWriter(file));
}
if (this.isHtml) {
File file = this.htmlFile != null ? this.htmlFile : this.destFile;
log("Jamming to ",file.toString());
htmlOut = new PrintWriter(new FileWriter(file));
}
if (this.dependsFile != null) {
log("Dependencies saved to "+this.dependsFile);
dependsOut = new PrintWriter(new FileWriter(this.dependsFile));
}
if (this.prefix != null) {
PrintWriter out = OUTPUT_JS.equals(this.prefix.output) ? jsOut : htmlOut;
if (out != null) {
out.println(this.prefix.toString());
}
}
List<String> packages = new LinkedList<String>();
for (JammerFiles files : this.files) {
boolean wrap = files.isWrapped();
boolean isManifest = files.isManifest();
File dir = files.getDir(this.getProject());
for (String filename : files.getFiles(this.getProject())) {
File file = new File(dir, filename);
String pkg = path2package(stripExt(filename).replace(File.separatorChar, '/'));
packages.add(pkg);
if (this.isHtml && !isManifest) {
printHTML(htmlOut, pkg, files.getBasePath(), files.getExtension());
}
jamFile(jsOut, htmlOut, file, pkg, packages, wrap, true, dependsOut);
}
}
if (this.isHtml && packages.size() > 0 && htmlOut != null) {
htmlOut.println("<script type=\"text/javascript\">");
for (String pkg : packages) {
htmlOut.print("AjxPackage.define(\"");
htmlOut.print(pkg);
htmlOut.println("\");");
}
htmlOut.println("</script>");
}
if (this.suffix != null) {
PrintWriter out = OUTPUT_JS.equals(this.prefix.output) ? jsOut : htmlOut;
if (out != null) {
out.println(this.suffix.toString());
}
}
}
catch (IOException e) {
throw new BuildException(e);
}
finally {
if (jsOut != null) jsOut.close();
if (htmlOut != null) htmlOut.close();
if (dependsOut != null) dependsOut.close();
}
}
//
// Private methods
//
private void jamFile(PrintWriter jsOut, PrintWriter htmlOut, File ifile,
String pkg, List<String> packages,
boolean wrap, boolean top, PrintWriter dependsOut)
throws IOException {
if (this.verbose) log("file: ",ifile.toString());
BufferedReader in = new BufferedReader(new FileReader(ifile));
boolean isJS = ifile.getName().endsWith(".js");
// "wrap" source
if (this.isJs && isJS && pkg != null && wrap && jsOut != null) {
jsOut.print("if (AjxPackage.define(\"");
jsOut.print(pkg);
jsOut.println("\")) {");
}
// remember this file
if (dependsOut != null) {
dependsOut.println(ifile.getCanonicalPath());
dependsOut.flush();
}
// read file
String line;
while ((line = in.readLine()) != null) {
// define package
String define = matchDefine(line);
if (define != null) {
if (this.verbose) log("define ", define);
this.defines.put(package2path(define), true);
continue;
}
// undefine package
String undefine = matchUndefine(line);
if (undefine != null) {
if (this.verbose) log("undefine ", undefine);
this.defines.remove(package2path(undefine));
continue;
}
// require package
String require = matchRequire(line);
if (require != null) {
if (this.verbose) log("require ", require);
String path = package2path(require);
if (this.defines.get(path) == null) {
packages.add(require);
// output script tag
if (this.isHtml && !path.endsWith("__all__")) {
printHTML(htmlOut, require, null, null);
}
// implicitly define and jam on!
this.defines.put(path, true);
File file = this.getFileForPath(path);
String odepth = this.verbose ? this.depth : null;
if (this.verbose) this.depth += " ";
jamFile(jsOut, htmlOut, file, path2package(require), packages, wrap, false, dependsOut);
if (this.verbose) this.depth = odepth;
}
continue;
}
// leave line intact
if (this.isJs && isJS && jsOut != null) {
jsOut.println(line);
}
}
if (this.isJs && isJS && pkg != null && wrap && jsOut != null) {
jsOut.println("}");
}
in.close();
}
private File getFileForPath(String path) {
String name = path.replace('/',File.separatorChar)+".js";
File file = null;
for (Source source : this.sources) {
String filename = name;
if (source.prefix != null && name.startsWith(source.prefix+"/")) {
filename = name.substring(source.prefix.length() + 1);
}
file = new File(source.dir, filename);
if (file.exists()) {
break;
}
}
return file;
}
private void printHTML(PrintWriter out, String pkg, String basePath, String extension) {
if (out == null) return;
String path = package2path(pkg);
out.print("<script type=\"text/javascript\" src=\"");
out.print(basePath != null ? basePath : this.basepath);
out.print(path);
out.print(extension != null ? extension : this.extension);
out.println("\"></script>");
}
private String matchDefine(String s) {
Matcher m = RE_DEFINE.matcher(s);
return m.matches() ? m.group(1) : null;
}
private String matchUndefine(String s) {
Matcher m = RE_UNDEFINE.matcher(s);
return m.matches() ? m.group(1) : null;
}
private String matchRequire(String s) {
Matcher m = RE_REQUIRE.matcher(s);
if (m.matches()){
return m.group(1);
}
m = RE_REQUIRE_OBJ.matcher(s);
if (m.matches()){
return m.group(2);
}
return null;
}
private void log(String... ss) {
System.out.print(this.depth);
for (String s : ss) {
System.out.print(s);
}
System.out.println();
}
//
// Private functions
//
private static String package2path(String pkg) {
return pkg.replace('.', '/').replaceAll("\\*$", "__all__");
}
private static String path2package(String path) {
return path.replace('/', '.').replaceAll("\\*$", "__all__");
}
private static String stripExt(String fname) {
return fname.replaceAll("\\..+$", "");
}
//
// Classes
//
private static interface JammerFiles {
public boolean isWrapped();
public boolean isManifest();
public String getBasePath();
public String getExtension();
public File getDir(Project project);
public String[] getFiles(Project project);
}
public static class JammerFileList
extends FileList
implements JammerFiles {
//
// Data
//
private boolean wrap = true;
private boolean manifest = true;
private String basePath;
private String extension;
//
// Public methods
//
public void setWrap(boolean wrap) {
this.wrap = wrap;
}
public boolean isWrapped() {
return this.wrap;
}
public void setManifest(boolean manifest) {
this.manifest = manifest;
}
public boolean isManifest() {
return this.manifest;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return this.basePath;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getExtension() {
return this.extension;
}
} // class JammerFileList
public static class JammerFileSet
extends FileSet
implements JammerFiles {
//
// Data
//
private boolean wrap = true;
private boolean manifest = true;
private String basePath;
private String extension;
//
// Public methods
//
public String[] getFiles(Project project) {
return this.getDirectoryScanner(project).getIncludedFiles();
}
public void setWrap(boolean wrap) {
this.wrap = wrap;
}
public boolean isWrapped() {
return wrap;
}
public void setManifest(boolean manifest) {
this.manifest = manifest;
}
public boolean isManifest() {
return this.manifest;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return this.basePath;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getExtension() {
return this.extension;
}
} // class JammerFileList
public static class Text {
public String output = PackageJammerTask.OUTPUT_JS;
private StringBuilder str = new StringBuilder();
public void setOutput(String output) {
this.output = output;
}
public void addText(String s) {
str.append(s);
}
public String toString() { return str.toString(); }
}
public class Source {
public File dir;
public String prefix;
public void setDir(File dir) {
this.dir = dir;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
} // class PackageJammerTask
| nico01f/z-pec | ZimbraWebClient/src/com/zimbra/webClient/build/PackageJammerTask.java | Java | mit | 14,020 |
var pub = {},
Q,
Knex;
module.exports = function ($inject) {
$inject = $inject || {};
Q = $inject.Q;
Knex = $inject.Knex;
return pub;
};
pub.get = function(tableName) {
var q = Q.defer();
pub.getMetadata(tableName)
.then(function(relations) {
q.resolve(relations[0]);
});
return q.promise;
};
pub.getMetadata = function(tableName) {
return Knex.knex.raw('SELECT ' +
'KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME, ' +
'KCU1.COLUMN_NAME AS FK_COLUMN_NAME, ' +
'KCU2.CONSTRAINT_NAME AS REFERENCED_CONSTRAINT_NAME, ' +
'KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME, ' +
'KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME ' +
'FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC ' +
'INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 ' +
'ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG ' +
'AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA ' +
'AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME ' +
'AND KCU1.TABLE_NAME = RC.TABLE_NAME ' +
'INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2 ' +
'ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG ' +
'AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA ' +
'AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME ' +
'AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION ' +
'AND KCU2.TABLE_NAME = RC.REFERENCED_TABLE_NAME ' +
'WHERE kcu1.table_name = ?', tableName);
};
| heinzelmannchen/mysql2json | lib/relations.js | JavaScript | mit | 1,911 |
using System.Web.Mvc;
using FFLTask.SRV.ServiceInterface;
using FFLTask.UI.PC.Filter;
using FFLTask.SRV.ViewModel.Account;
using FFLTask.SRV.ViewModel.Shared;
namespace FFLTask.UI.PC.Controllers
{
public class RegisterController : BaseController
{
private IRegisterService _registerService;
public RegisterController(IRegisterService registerService)
{
_registerService = registerService;
}
#region URL: /Register
[HttpGet]
[CheckCookieEnabled]
public ActionResult Index()
{
return View(new RegisterModel());
}
[HttpPost]
public ActionResult Index(RegisterModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
model.ImageCode = imageCodeHelper.CheckResult();
if (model.ImageCode.ImageCodeError != ImageCodeError.NoError)
{
return View(model);
}
if (_registerService.GetUserByName(model.UserName) > 0)
{
ModelState.AddModelError("UserName", "*用户名已被使用");
return View(model);
}
int userId = _registerService.Do(model);
userHelper.SetUserId(userId.ToString());
return RedirectToAction("Profile", "User");
}
#endregion
#region Ajax
public JsonResult IsUserNameExist(string name)
{
bool duplicated = _registerService.GetUserByName(name) > 0;
return Json(duplicated);
}
#endregion
}
}
| feilang864/task.zyfei.net | UI/PC/Controllers/RegisterController.cs | C# | mit | 1,657 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name')->unique();
$table->string('empresa')->unique();
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique()->nullable();
$table->string('password', 60);
$table->integer('role_id');
$table->rememberToken()->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| 3dlink/age | database/migrations/2014_10_12_000000_create_users_table.php | PHP | mit | 774 |
# frozen_string_literal: true
require 'fieldhand/metadata_format'
module Fieldhand
# A parser for ListMetadataFormats responses.
#
# See https://www.openarchives.org/OAI/openarchivesprotocol.html#ListMetadataFormats
class ListMetadataFormatsParser
attr_reader :response_parser
# Return a parser for the given response parser.
def initialize(response_parser)
@response_parser = response_parser
end
# Return an array of `MetadataFormat`s found in the response.
def items
response_parser.
root.
locate('ListMetadataFormats/metadataFormat').
map { |item| MetadataFormat.new(item, response_parser.response_date) }
end
end
end
| altmetric/fieldhand | lib/fieldhand/list_metadata_formats_parser.rb | Ruby | mit | 699 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Botos</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body{
color: #28fe14;
background-color: black;
font-family: "Courier New";
font-size: 15pt;
cursor: default
}
</style>
<script type="text/javascript">
document.ondragstart = function(){return false;}
document.oncontextmenu = function(){return false;}
document.onselectstart = function(){return false;}
</script>
</head>
<body>
| BirkhoffLee/Botos | cmd/extra/main.header.php | PHP | mit | 633 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Resources
{
// Intentionally excluding visibility so it defaults to internal except for
// the one public version in System.Resources.ResourceManager which defines
// another version of this partial class with the public visibility
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
sealed partial class NeutralResourcesLanguageAttribute : Attribute
{
private readonly string _culture;
public NeutralResourcesLanguageAttribute(string cultureName)
{
if (cultureName == null)
throw new ArgumentNullException("cultureName");
_culture = cultureName;
}
public string CultureName
{
get { return _culture; }
}
}
}
| mafiya69/corefx | src/Common/src/System/Resources/NeutralResourcesLanguageAttribute.cs | C# | mit | 984 |